path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
---|---|---|
ajax/libs/angular-google-maps/2.0.13/angular-google-maps.js | sufuf3/cdnjs | /*! angular-google-maps 2.0.13 2015-02-25
* AngularJS directives for Google Maps
* git: https://github.com/angular-ui/angular-google-maps.git
*/
;
(function( window, angular, undefined ){
'use strict';
/*
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE 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.
angular-google-maps
https://github.com/angular-ui/angular-google-maps
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps.providers', []);
angular.module('uiGmapgoogle-maps.wrapped', []);
angular.module('uiGmapgoogle-maps.extensions', ['uiGmapgoogle-maps.wrapped', 'uiGmapgoogle-maps.providers']);
angular.module('uiGmapgoogle-maps.directives.api.utils', ['uiGmapgoogle-maps.extensions']);
angular.module('uiGmapgoogle-maps.directives.api.managers', []);
angular.module('uiGmapgoogle-maps.directives.api.options', ['uiGmapgoogle-maps.directives.api.utils']);
angular.module('uiGmapgoogle-maps.directives.api.options.builders', []);
angular.module('uiGmapgoogle-maps.directives.api.models.child', ['uiGmapgoogle-maps.directives.api.utils', 'uiGmapgoogle-maps.directives.api.options', 'uiGmapgoogle-maps.directives.api.options.builders']);
angular.module('uiGmapgoogle-maps.directives.api.models.parent', ['uiGmapgoogle-maps.directives.api.managers', 'uiGmapgoogle-maps.directives.api.models.child', 'uiGmapgoogle-maps.providers']);
angular.module('uiGmapgoogle-maps.directives.api', ['uiGmapgoogle-maps.directives.api.models.parent']);
angular.module('uiGmapgoogle-maps', ['uiGmapgoogle-maps.directives.api', 'uiGmapgoogle-maps.providers']);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.providers').factory('uiGmapMapScriptLoader', [
'$q', 'uiGmapuuid', function($q, uuid) {
var getScriptUrl, includeScript, isGoogleMapsLoaded, scriptId;
scriptId = void 0;
getScriptUrl = function(options) {
if (options.china) {
return 'http://maps.google.cn/maps/api/js?';
} else {
return 'https://maps.googleapis.com/maps/api/js?';
}
};
includeScript = function(options) {
var query, script;
query = _.map(options, function(v, k) {
return k + '=' + v;
});
if (scriptId) {
document.getElementById(scriptId).remove();
}
query = query.join('&');
script = document.createElement('script');
script.id = scriptId = "ui_gmap_map_load_" + (uuid.generate());
script.type = 'text/javascript';
script.src = getScriptUrl(options) + query;
return document.body.appendChild(script);
};
isGoogleMapsLoaded = function() {
return angular.isDefined(window.google) && angular.isDefined(window.google.maps);
};
return {
load: function(options) {
var deferred, randomizedFunctionName;
deferred = $q.defer();
if (isGoogleMapsLoaded()) {
deferred.resolve(window.google.maps);
return deferred.promise;
}
randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000);
window[randomizedFunctionName] = function() {
window[randomizedFunctionName] = null;
deferred.resolve(window.google.maps);
};
if (window.navigator.connection && window.navigator.connection.type === window.Connection.NONE) {
document.addEventListener('online', function() {
if (!isGoogleMapsLoaded()) {
return includeScript(options);
}
});
} else {
includeScript(options);
}
return deferred.promise;
}
};
}
]).provider('uiGmapGoogleMapApi', function() {
this.options = {
china: false,
v: '3.17',
libraries: '',
language: 'en',
sensor: 'false'
};
this.configure = function(options) {
angular.extend(this.options, options);
};
this.$get = [
'uiGmapMapScriptLoader', (function(_this) {
return function(loader) {
return loader.load(_this.options);
};
})(this)
];
return this;
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').service('uiGmapExtendGWin', function() {
return {
init: _.once(function() {
if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) {
return;
}
google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open;
google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close;
google.maps.InfoWindow.prototype._isOpen = false;
google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) {
if (recurse != null) {
return;
}
this._isOpen = true;
this._open(map, anchor, true);
};
google.maps.InfoWindow.prototype.close = function(recurse) {
if (recurse != null) {
return;
}
this._isOpen = false;
this._close(true);
};
google.maps.InfoWindow.prototype.isOpen = function(val) {
if (val == null) {
val = void 0;
}
if (val == null) {
return this._isOpen;
} else {
return this._isOpen = val;
}
};
/*
Do the same for InfoBox
TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier
*/
if (window.InfoBox) {
window.InfoBox.prototype._open = window.InfoBox.prototype.open;
window.InfoBox.prototype._close = window.InfoBox.prototype.close;
window.InfoBox.prototype._isOpen = false;
window.InfoBox.prototype.open = function(map, anchor) {
this._isOpen = true;
this._open(map, anchor);
};
window.InfoBox.prototype.close = function() {
this._isOpen = false;
this._close();
};
window.InfoBox.prototype.isOpen = function(val) {
if (val == null) {
val = void 0;
}
if (val == null) {
return this._isOpen;
} else {
return this._isOpen = val;
}
};
}
if (window.MarkerLabel_) {
return window.MarkerLabel_.prototype.setContent = function() {
var content;
content = this.marker_.get('labelContent');
if (!content || _.isEqual(this.oldContent, content)) {
return;
}
if (typeof (content != null ? content.nodeType : void 0) === 'undefined') {
this.labelDiv_.innerHTML = content;
this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;
this.oldContent = content;
} else {
this.labelDiv_.innerHTML = '';
this.labelDiv_.appendChild(content);
content = content.cloneNode(true);
this.labelDiv_.innerHTML = '';
this.eventDiv_.appendChild(content);
this.oldContent = content;
}
};
}
})
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').service('uiGmapLodash', function() {
/*
Author Nick McCready
Intersection of Objects if the arrays have something in common each intersecting object will be returned
in an new array.
*/
this.intersectionObjects = function(array1, array2, comparison) {
var res;
if (comparison == null) {
comparison = void 0;
}
res = _.map(array1, (function(_this) {
return function(obj1) {
return _.find(array2, function(obj2) {
if (comparison != null) {
return comparison(obj1, obj2);
} else {
return _.isEqual(obj1, obj2);
}
});
};
})(this));
return _.filter(res, function(o) {
return o != null;
});
};
this.containsObject = _.includeObject = function(obj, target, comparison) {
if (comparison == null) {
comparison = void 0;
}
if (obj === null) {
return false;
}
return _.any(obj, (function(_this) {
return function(value) {
if (comparison != null) {
return comparison(value, target);
} else {
return _.isEqual(value, target);
}
};
})(this));
};
this.differenceObjects = function(array1, array2, comparison) {
if (comparison == null) {
comparison = void 0;
}
return _.filter(array1, (function(_this) {
return function(value) {
return !_this.containsObject(array2, value, comparison);
};
})(this));
};
this.withoutObjects = this.differenceObjects;
this.indexOfObject = function(array, item, comparison, isSorted) {
var i, length;
if (array == null) {
return -1;
}
i = 0;
length = array.length;
if (isSorted) {
if (typeof isSorted === "number") {
i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return (array[i] === item ? i : -1);
}
}
while (i < length) {
if (comparison != null) {
if (comparison(array[i], item)) {
return i;
}
} else {
if (_.isEqual(array[i], item)) {
return i;
}
}
i++;
}
return -1;
};
this["extends"] = function(arrayOfObjectsToCombine) {
return _.reduce(arrayOfObjectsToCombine, function(combined, toAdd) {
return _.extend(combined, toAdd);
}, {});
};
this.isNullOrUndefined = function(thing) {
return _.isNull(thing || _.isUndefined(thing));
};
return this;
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.extensions').factory('uiGmapString', function() {
return function(str) {
this.contains = function(value, fromIndex) {
return str.indexOf(value, fromIndex) !== -1;
};
return this;
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmap_sync', [
function() {
return {
fakePromise: function() {
var _cb;
_cb = void 0;
return {
then: function(cb) {
return _cb = cb;
},
resolve: function() {
return _cb.apply(void 0, arguments);
}
};
}
};
}
]).service('uiGmap_async', [
'$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q', 'uiGmapDataStructures', 'uiGmapGmapUtil', function($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) {
var ExposedPromise, PromiseQueueManager, SniffedPromise, defaultChunkSize, doChunk, doSkippPromise, each, errorObject, isInProgress, kickPromise, logTryCatch, managePromiseQueue, map, maybeCancelPromises, promiseStatus, promiseTypes, tryCatch;
promiseTypes = uiGmapPromise.promiseTypes;
isInProgress = uiGmapPromise.isInProgress;
promiseStatus = uiGmapPromise.promiseStatus;
ExposedPromise = uiGmapPromise.ExposedPromise;
SniffedPromise = uiGmapPromise.SniffedPromise;
kickPromise = function(sniffedPromise, cancelCb) {
var promise;
promise = sniffedPromise.promise();
promise.promiseType = sniffedPromise.promiseType;
if (promise.$$state) {
$log.debug("promiseType: " + promise.promiseType + ", state: " + (promiseStatus(promise.$$state.status)));
}
promise.cancelCb = cancelCb;
return promise;
};
doSkippPromise = function(sniffedPromise, lastPromise) {
if (sniffedPromise.promiseType === promiseTypes.create && lastPromise.promiseType !== promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes.init) {
$log.debug("lastPromise.promiseType " + lastPromise.promiseType + ", newPromiseType: " + sniffedPromise.promiseType + ", SKIPPED MUST COME AFTER DELETE ONLY");
return true;
}
return false;
};
maybeCancelPromises = function(queue, sniffedPromise, lastPromise) {
var first;
if (sniffedPromise.promiseType === promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes["delete"]) {
if ((lastPromise.cancelCb != null) && _.isFunction(lastPromise.cancelCb) && isInProgress(lastPromise)) {
$log.debug("promiseType: " + sniffedPromise.promiseType + ", CANCELING LAST PROMISE type: " + lastPromise.promiseType);
lastPromise.cancelCb('cancel safe');
first = queue.peek();
if ((first != null) && isInProgress(first)) {
if (first.hasOwnProperty("cancelCb") && _.isFunction(first.cancelCb)) {
$log.debug("promiseType: " + first.promiseType + ", CANCELING FIRST PROMISE type: " + first.promiseType);
return first.cancelCb('cancel safe');
} else {
return $log.warn('first promise was not cancelable');
}
}
}
}
};
/*
From a High Level:
This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces.
This is a function and should not be considered a class.
So it is run to manage the state (cancel, skip, link) as needed.
Purpose:
The whole point is to check if there is existing async work going on. If so we wait on it.
arguments:
- existingPiecesObj = Queue<Promises>
- sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise)
with its intended type.
- cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator
Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise
gracefully without messing up state.
Synopsis:
- Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering)
where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete
- Every Promise that comes is is enqueue and linked to the last promise in the queue.
- A promise can be skipped or canceled to save cycles.
Saved Cycles:
- Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in
after a delete promise.
- Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type.
NOTE:
- You should not muck with existingPieces as its state is dependent on this functional loop.
- PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole
purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces.
*/
PromiseQueueManager = function(existingPiecesObj, sniffedPromise, cancelCb) {
var lastPromise, newPromise;
if (!existingPiecesObj.existingPieces) {
existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue();
return existingPiecesObj.existingPieces.enqueue(kickPromise(sniffedPromise, cancelCb));
} else {
lastPromise = _.last(existingPiecesObj.existingPieces._content);
if (doSkippPromise(sniffedPromise, lastPromise)) {
return;
}
maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise);
newPromise = ExposedPromise(lastPromise["finally"](function() {
return kickPromise(sniffedPromise, cancelCb);
}));
newPromise.cancelCb = cancelCb;
newPromise.promiseType = sniffedPromise.promiseType;
existingPiecesObj.existingPieces.enqueue(newPromise);
return lastPromise["finally"](function() {
return existingPiecesObj.existingPieces.dequeue();
});
}
};
managePromiseQueue = function(objectToLock, promiseType, msg, cancelCb, fnPromise) {
var cancelLogger;
if (msg == null) {
msg = '';
}
cancelLogger = function(msg) {
$log.debug("" + msg + ": " + msg);
return cancelCb(msg);
};
return PromiseQueueManager(objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger);
};
defaultChunkSize = 80;
errorObject = {
value: null
};
tryCatch = function(fn, ctx, args) {
var e;
try {
return fn.apply(ctx, args);
} catch (_error) {
e = _error;
errorObject.value = e;
return errorObject;
}
};
logTryCatch = function(fn, ctx, deferred, args) {
var msg, result;
result = tryCatch(fn, ctx, args);
if (result === errorObject) {
msg = "error within chunking iterator: " + errorObject.value;
$log.error(msg);
deferred.reject(msg);
}
if (result === 'cancel safe') {
return false;
}
return true;
};
/*
Author: Nicholas McCready & jfriend00
_async handles things asynchronous-like :), to allow the UI to be free'd to do other things
Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui
The design of any functionality of _async is to be like lodash/underscore and replicate it but call things
asynchronously underneath. Each should be sufficient for most things to be derived from.
Optional Asynchronous Chunking via promises.
*/
doChunk = function(array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index) {
var cnt, i, keepGoing;
if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) {
cnt = chunkSizeOrDontChunk;
} else {
cnt = array.length;
}
i = index;
keepGoing = true;
while (keepGoing && cnt-- && i < (array ? array.length : i + 1)) {
keepGoing = logTryCatch(chunkCb, void 0, overallD, [array[i], i]);
++i;
}
if (array) {
if (keepGoing && i < array.length) {
index = i;
if (chunkSizeOrDontChunk) {
if ((pauseCb != null) && _.isFunction(pauseCb)) {
logTryCatch(pauseCb, void 0, overallD, []);
}
return $timeout(function() {
return doChunk(array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index);
}, pauseMilli, false);
}
} else {
return overallD.resolve();
}
}
};
each = function(array, chunk, chunkSizeOrDontChunk, pauseCb, index, pauseMilli) {
var error, overallD, ret;
if (chunkSizeOrDontChunk == null) {
chunkSizeOrDontChunk = defaultChunkSize;
}
if (index == null) {
index = 0;
}
if (pauseMilli == null) {
pauseMilli = 1;
}
ret = void 0;
overallD = uiGmapPromise.defer();
ret = overallD.promise;
if (!pauseMilli) {
error = 'pause (delay) must be set from _async!';
$log.error(error);
overallD.reject(error);
return ret;
}
if (array === void 0 || (array != null ? array.length : void 0) <= 0) {
overallD.resolve();
return ret;
}
doChunk(array, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index);
return ret;
};
map = function(objs, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli) {
var results;
results = [];
if (!((objs != null) && (objs != null ? objs.length : void 0) > 0)) {
return uiGmapPromise.resolve(results);
}
return each(objs, function(o) {
return results.push(iterator(o));
}, chunkSizeOrDontChunk, pauseCb, index, pauseMilli).then(function() {
return results;
});
};
return {
each: each,
map: map,
managePromiseQueue: managePromiseQueue,
promiseLock: managePromiseQueue,
defaultChunkSize: defaultChunkSize,
chunkSizeFrom: function(fromSize, ret) {
if (ret == null) {
ret = void 0;
}
if (_.isNumber(fromSize)) {
ret = fromSize;
}
if (uiGmapGmapUtil.isFalse(fromSize) || fromSize === false) {
ret = false;
}
return ret;
}
};
}
]);
}).call(this);
;(function() {
var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapBaseObject', function() {
var BaseObject, baseObjectKeywords;
baseObjectKeywords = ['extended', 'included'];
BaseObject = (function() {
function BaseObject() {}
BaseObject.extend = function(obj) {
var key, value, _ref;
for (key in obj) {
value = obj[key];
if (__indexOf.call(baseObjectKeywords, key) < 0) {
this[key] = value;
}
}
if ((_ref = obj.extended) != null) {
_ref.apply(this);
}
return this;
};
BaseObject.include = function(obj) {
var key, value, _ref;
for (key in obj) {
value = obj[key];
if (__indexOf.call(baseObjectKeywords, key) < 0) {
this.prototype[key] = value;
}
}
if ((_ref = obj.included) != null) {
_ref.apply(this);
}
return this;
};
return BaseObject;
})();
return BaseObject;
});
}).call(this);
;
/*
Useful function callbacks that should be defined at later time.
Mainly to be used for specs to verify creation / linking.
This is to lead a common design in notifying child stuff.
*/
(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapChildEvents', function() {
return {
onChildCreation: function(child) {}
};
});
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapCtrlHandle', [
'$q', function($q) {
var CtrlHandle;
return CtrlHandle = {
handle: function($scope, $element) {
$scope.$on('$destroy', function() {
return CtrlHandle.handle($scope);
});
$scope.deferred = $q.defer();
return {
getScope: function() {
return $scope;
}
};
},
mapPromise: function(scope, ctrl) {
var mapScope;
mapScope = ctrl.getScope();
mapScope.deferred.promise.then(function(map) {
return scope.map = map;
});
return mapScope.deferred.promise;
}
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").service("uiGmapEventsHelper", [
"uiGmapLogger", function($log) {
return {
setEvents: function(gObject, scope, model, ignores) {
if (angular.isDefined(scope.events) && (scope.events != null) && angular.isObject(scope.events)) {
return _.compact(_.map(scope.events, function(eventHandler, eventName) {
var doIgnore;
if (ignores) {
doIgnore = _(ignores).contains(eventName);
}
if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName]) && !doIgnore) {
return google.maps.event.addListener(gObject, eventName, function() {
if (!scope.$evalAsync) {
scope.$evalAsync = function() {};
}
return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments]));
});
}
}));
}
},
removeEvents: function(listeners) {
if (!listeners) {
return;
}
return listeners.forEach(function(l) {
if (l) {
return google.maps.event.removeListener(l);
}
});
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapFitHelper', [
'uiGmapLogger', 'uiGmap_async', function($log, _async) {
return {
fit: function(gMarkers, gMap) {
var bounds, everSet;
if (gMap && gMarkers && gMarkers.length > 0) {
bounds = new google.maps.LatLngBounds();
everSet = false;
gMarkers.forEach((function(_this) {
return function(gMarker) {
if (gMarker) {
if (!everSet) {
everSet = true;
}
return bounds.extend(gMarker.getPosition());
}
};
})(this));
if (everSet) {
return gMap.fitBounds(bounds);
}
}
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapGmapUtil', [
'uiGmapLogger', '$compile', function(Logger, $compile) {
var getCoords, getLatitude, getLongitude, validateCoords, _isFalse, _isTruthy;
_isTruthy = function(value, bool, optionsArray) {
return value === bool || optionsArray.indexOf(value) !== -1;
};
_isFalse = function(value) {
return _isTruthy(value, false, ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO']);
};
getLatitude = function(value) {
if (Array.isArray(value) && value.length === 2) {
return value[1];
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return value.coordinates[1];
} else {
return value.latitude;
}
};
getLongitude = function(value) {
if (Array.isArray(value) && value.length === 2) {
return value[0];
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return value.coordinates[0];
} else {
return value.longitude;
}
};
getCoords = function(value) {
if (!value) {
return;
}
if (Array.isArray(value) && value.length === 2) {
return new google.maps.LatLng(value[1], value[0]);
} else if (angular.isDefined(value.type) && value.type === 'Point') {
return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]);
} else {
return new google.maps.LatLng(value.latitude, value.longitude);
}
};
validateCoords = function(coords) {
if (angular.isUndefined(coords)) {
return false;
}
if (_.isArray(coords)) {
if (coords.length === 2) {
return true;
}
} else if ((coords != null) && (coords != null ? coords.type : void 0)) {
if (coords.type === 'Point' && _.isArray(coords.coordinates) && coords.coordinates.length === 2) {
return true;
}
}
if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) {
return true;
}
return false;
};
return {
setCoordsFromEvent: function(prevValue, newLatLon) {
if (!prevValue) {
return;
}
if (Array.isArray(prevValue) && prevValue.length === 2) {
prevValue[1] = newLatLon.lat();
prevValue[0] = newLatLon.lng();
} else if (angular.isDefined(prevValue.type) && prevValue.type === 'Point') {
prevValue.coordinates[1] = newLatLon.lat();
prevValue.coordinates[0] = newLatLon.lng();
} else {
prevValue.latitude = newLatLon.lat();
prevValue.longitude = newLatLon.lng();
}
return prevValue;
},
getLabelPositionPoint: function(anchor) {
var xPos, yPos;
if (anchor === void 0) {
return void 0;
}
anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor);
xPos = parseFloat(anchor[1]);
yPos = parseFloat(anchor[2]);
if ((xPos != null) && (yPos != null)) {
return new google.maps.Point(xPos, yPos);
}
},
createWindowOptions: function(gMarker, scope, content, defaults) {
var options;
if ((content != null) && (defaults != null) && ($compile != null)) {
options = angular.extend({}, defaults, {
content: this.buildContent(scope, defaults, content),
position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords)
});
if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) {
if (options.boxClass == null) {
} else {
options.pixelOffset = {
height: 0,
width: -2
};
}
}
return options;
} else {
if (!defaults) {
Logger.error('infoWindow defaults not defined');
if (!content) {
return Logger.error('infoWindow content not defined');
}
} else {
return defaults;
}
}
},
buildContent: function(scope, defaults, content) {
var parsed, ret;
if (defaults.content != null) {
ret = defaults.content;
} else {
if ($compile != null) {
content = content.replace(/^\s+|\s+$/g, '');
parsed = content === '' ? '' : $compile(content)(scope);
if (parsed.length > 0) {
ret = parsed[0];
}
} else {
ret = content;
}
}
return ret;
},
defaultDelay: 50,
isTrue: function(value) {
return _isTruthy(value, true, ['true', 'TRUE', 1, 'y', 'Y', 'yes', 'YES']);
},
isFalse: _isFalse,
isFalsy: function(value) {
return _isTruthy(value, false, [void 0, null]) || _isFalse(value);
},
getCoords: getCoords,
validateCoords: validateCoords,
equalCoords: function(coord1, coord2) {
return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2);
},
validatePath: function(path) {
var array, i, polygon, trackMaxVertices;
i = 0;
if (angular.isUndefined(path.type)) {
if (!Array.isArray(path) || path.length < 2) {
return false;
}
while (i < path.length) {
if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === 'function' && typeof path[i].lng === 'function'))) {
return false;
}
i++;
}
return true;
} else {
if (angular.isUndefined(path.coordinates)) {
return false;
}
if (path.type === 'Polygon') {
if (path.coordinates[0].length < 4) {
return false;
}
array = path.coordinates[0];
} else if (path.type === 'MultiPolygon') {
trackMaxVertices = {
max: 0,
index: 0
};
_.forEach(path.coordinates, function(polygon, index) {
if (polygon[0].length > this.max) {
this.max = polygon[0].length;
return this.index = index;
}
}, trackMaxVertices);
polygon = path.coordinates[trackMaxVertices.index];
array = polygon[0];
if (array.length < 4) {
return false;
}
} else if (path.type === 'LineString') {
if (path.coordinates.length < 2) {
return false;
}
array = path.coordinates;
} else {
return false;
}
while (i < array.length) {
if (array[i].length !== 2) {
return false;
}
i++;
}
return true;
}
},
convertPathPoints: function(path) {
var array, i, latlng, result, trackMaxVertices;
i = 0;
result = new google.maps.MVCArray();
if (angular.isUndefined(path.type)) {
while (i < path.length) {
latlng;
if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) {
latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude);
} else if (typeof path[i].lat === 'function' && typeof path[i].lng === 'function') {
latlng = path[i];
}
result.push(latlng);
i++;
}
} else {
array;
if (path.type === 'Polygon') {
array = path.coordinates[0];
} else if (path.type === 'MultiPolygon') {
trackMaxVertices = {
max: 0,
index: 0
};
_.forEach(path.coordinates, function(polygon, index) {
if (polygon[0].length > this.max) {
this.max = polygon[0].length;
return this.index = index;
}
}, trackMaxVertices);
array = path.coordinates[trackMaxVertices.index][0];
} else if (path.type === 'LineString') {
array = path.coordinates;
}
while (i < array.length) {
result.push(new google.maps.LatLng(array[i][1], array[i][0]));
i++;
}
}
return result;
},
extendMapBounds: function(map, points) {
var bounds, i;
bounds = new google.maps.LatLngBounds();
i = 0;
while (i < points.length) {
bounds.extend(points.getAt(i));
i++;
}
return map.fitBounds(bounds);
},
getPath: function(object, key) {
var obj;
if ((key == null) || !_.isString(key)) {
return key;
}
obj = object;
_.each(key.split('.'), function(value) {
if (obj) {
return obj = obj[value];
}
});
return obj;
},
validateBoundPoints: function(bounds) {
if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) {
return false;
}
return true;
},
convertBoundPoints: function(bounds) {
var result;
result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude));
return result;
},
fitMapBounds: function(map, bounds) {
return map.fitBounds(bounds);
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapIsReady', [
'$q', '$timeout', function($q, $timeout) {
var ctr, promises, proms;
ctr = 0;
proms = [];
promises = function() {
return $q.all(proms);
};
return {
spawn: function() {
var d;
d = $q.defer();
proms.push(d.promise);
ctr += 1;
return {
instance: ctr,
deferred: d
};
},
promises: promises,
instances: function() {
return ctr;
},
promise: function(expect) {
var d, ohCrap;
if (expect == null) {
expect = 1;
}
d = $q.defer();
ohCrap = function() {
return $timeout(function() {
if (ctr !== expect) {
return ohCrap();
} else {
return d.resolve(promises());
}
});
};
ohCrap();
return d.promise;
},
reset: function() {
ctr = 0;
return proms.length = 0;
}
};
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [
"uiGmapBaseObject", function(BaseObject) {
var Linked;
Linked = (function(_super) {
__extends(Linked, _super);
function Linked(scope, element, attrs, ctrls) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.ctrls = ctrls;
}
return Linked;
})(BaseObject);
return Linked;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapLogger', [
'$log', function($log) {
var LEVELS, Logger, log, maybeExecLevel;
LEVELS = {
log: 1,
info: 2,
debug: 3,
warn: 4,
error: 5,
none: 6
};
maybeExecLevel = function(level, current, fn) {
if (level >= current) {
return fn();
}
};
log = function(logLevelFnName, msg) {
if ($log != null) {
return $log[logLevelFnName](msg);
} else {
return console[logLevelFnName](msg);
}
};
Logger = (function() {
function Logger() {
var logFns;
this.doLog = true;
logFns = {};
['log', 'info', 'debug', 'warn', 'error'].forEach((function(_this) {
return function(level) {
return logFns[level] = function(msg) {
if (_this.doLog) {
return maybeExecLevel(LEVELS[level], _this.currentLevel, function() {
return log(level, msg);
});
}
};
};
})(this));
this.LEVELS = LEVELS;
this.currentLevel = LEVELS.error;
this.log = logFns['log'];
this.info = logFns['info'];
this.debug = logFns['debug'];
this.warn = logFns['warn'];
this.error = logFns['error'];
}
Logger.prototype.spawn = function() {
return new Logger();
};
Logger.prototype.setLog = function(someLogger) {
return $log = someLogger;
};
return Logger;
})();
return new Logger();
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelKey', [
'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapPromise', '$q', '$timeout', function(BaseObject, GmapUtil, uiGmapPromise, $q, $timeout) {
var ModelKey;
return ModelKey = (function(_super) {
__extends(ModelKey, _super);
function ModelKey(scope) {
this.scope = scope;
this.updateChild = __bind(this.updateChild, this);
this.destroy = __bind(this.destroy, this);
this.setChildScope = __bind(this.setChildScope, this);
this.getChanges = __bind(this.getChanges, this);
this.getProp = __bind(this.getProp, this);
this.setIdKey = __bind(this.setIdKey, this);
this.modelKeyComparison = __bind(this.modelKeyComparison, this);
ModelKey.__super__.constructor.call(this);
this["interface"] = {};
this["interface"].scopeKeys = [];
this.defaultIdKey = 'id';
this.idKey = void 0;
}
ModelKey.prototype.evalModelHandle = function(model, modelKey) {
if ((model == null) || (modelKey == null)) {
return;
}
if (modelKey === 'self') {
return model;
} else {
if (_.isFunction(modelKey)) {
modelKey = modelKey();
}
return GmapUtil.getPath(model, modelKey);
}
};
ModelKey.prototype.modelKeyComparison = function(model1, model2) {
var hasCoords, isEqual, scope;
hasCoords = _.contains(this["interface"].scopeKeys, 'coords');
if (hasCoords && (this.scope.coords != null) || !hasCoords) {
scope = this.scope;
}
if (scope == null) {
throw 'No scope set!';
}
if (hasCoords) {
isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords));
if (!isEqual) {
return isEqual;
}
}
isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) {
return function(k) {
return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]);
};
})(this));
return isEqual;
};
ModelKey.prototype.setIdKey = function(scope) {
return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey;
};
ModelKey.prototype.setVal = function(model, key, newValue) {
var thingToSet;
thingToSet = this.modelOrKey(model, key);
thingToSet = newValue;
return model;
};
ModelKey.prototype.modelOrKey = function(model, key) {
if (key == null) {
return;
}
if (key !== 'self') {
return model[key];
}
return model;
};
ModelKey.prototype.getProp = function(propName, model) {
return this.modelOrKey(model, propName);
};
/*
For the cases were watching a large object we only want to know the list of props
that actually changed.
Also we want to limit the amount of props we analyze to whitelisted props that are
actually tracked by scope. (should make things faster with whitelisted)
*/
ModelKey.prototype.getChanges = function(now, prev, whitelistedProps) {
var c, changes, prop;
if (whitelistedProps) {
prev = _.pick(prev, whitelistedProps);
now = _.pick(now, whitelistedProps);
}
changes = {};
prop = {};
c = {};
for (prop in now) {
if (!prev || prev[prop] !== now[prop]) {
if (_.isArray(now[prop])) {
changes[prop] = now[prop];
} else if (_.isObject(now[prop])) {
c = this.getChanges(now[prop], (prev ? prev[prop] : null));
if (!_.isEmpty(c)) {
changes[prop] = c;
}
} else {
changes[prop] = now[prop];
}
}
}
return changes;
};
ModelKey.prototype.scopeOrModelVal = function(key, scope, model, doWrap) {
var maybeWrap, modelKey, modelProp, scopeProp;
if (doWrap == null) {
doWrap = false;
}
maybeWrap = function(isScope, ret, doWrap) {
if (doWrap == null) {
doWrap = false;
}
if (doWrap) {
return {
isScope: isScope,
value: ret
};
}
return ret;
};
scopeProp = scope[key];
if (_.isFunction(scopeProp)) {
return maybeWrap(true, scopeProp(model), doWrap);
}
if (_.isObject(scopeProp)) {
return maybeWrap(true, scopeProp, doWrap);
}
if (!_.isString(scopeProp)) {
return maybeWrap(true, scopeProp, doWrap);
}
modelKey = scopeProp;
if (!modelKey) {
modelProp = model[key];
} else {
modelProp = modelKey === 'self' ? model : model[modelKey];
}
if (_.isFunction(modelProp)) {
return maybeWrap(false, modelProp(), doWrap);
}
return maybeWrap(false, modelProp, doWrap);
};
ModelKey.prototype.setChildScope = function(keys, childScope, model) {
_.each(keys, (function(_this) {
return function(name) {
var isScopeObj, newValue;
isScopeObj = _this.scopeOrModelVal(name, childScope, model, true);
if (!isScopeObj.isScope) {
newValue = isScopeObj.value;
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
}
};
})(this));
return childScope.model = model;
};
ModelKey.prototype.destroy = function(manualOverride) {
var _ref;
if (manualOverride == null) {
manualOverride = false;
}
if ((this.scope != null) && !((_ref = this.scope) != null ? _ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {
return this.scope.$destroy();
} else {
return this.clean();
}
};
ModelKey.prototype.updateChild = function(child, model) {
if (model[this.idKey] == null) {
this.$log.error("Model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.");
return;
}
return child.updateModel(model);
};
return ModelKey;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelsWatcher', [
'uiGmapLogger', 'uiGmap_async', '$q', 'uiGmapPromise', function(Logger, _async, $q, uiGmapPromise) {
return {
didQueueInitPromise: function(existingPiecesObj, scope) {
if (scope.models.length === 0) {
_async.promiseLock(existingPiecesObj, uiGmapPromise.promiseTypes.init, null, null, ((function(_this) {
return function() {
return uiGmapPromise.resolve();
};
})(this)));
return true;
}
return false;
},
figureOutState: function(idKey, scope, childObjects, comparison, callBack) {
var adds, children, mappedScopeModelIds, removals, updates;
adds = [];
mappedScopeModelIds = {};
removals = [];
updates = [];
scope.models.forEach(function(m) {
var child;
if (m[idKey] != null) {
mappedScopeModelIds[m[idKey]] = {};
if (childObjects.get(m[idKey]) == null) {
return adds.push(m);
} else {
child = childObjects.get(m[idKey]);
if (!comparison(m, child.clonedModel)) {
return updates.push({
model: m,
child: child
});
}
}
} else {
return Logger.error(' id missing for model #{m.toString()},\ncan not use do comparison/insertion');
}
});
children = childObjects.values();
children.forEach(function(c) {
var id;
if (c == null) {
Logger.error('child undefined in ModelsWatcher.');
return;
}
if (c.model == null) {
Logger.error('child.model undefined in ModelsWatcher.');
return;
}
id = c.model[idKey];
if (mappedScopeModelIds[id] == null) {
return removals.push(c);
}
});
return {
adds: adds,
removals: removals,
updates: updates
};
}
};
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [
'$q', '$timeout', 'uiGmapLogger', function($q, $timeout, $log) {
var ExposedPromise, SniffedPromise, defer, isInProgress, isResolved, promise, promiseStatus, promiseStatuses, promiseTypes, resolve, strPromiseStatuses;
promiseTypes = {
create: 'create',
update: 'update',
"delete": 'delete',
init: 'init'
};
promiseStatuses = {
IN_PROGRESS: 0,
RESOLVED: 1,
REJECTED: 2
};
strPromiseStatuses = (function() {
var obj;
obj = {};
obj["" + promiseStatuses.IN_PROGRESS] = 'in-progress';
obj["" + promiseStatuses.RESOLVED] = 'resolved';
obj["" + promiseStatuses.REJECTED] = 'rejected';
return obj;
})();
isInProgress = function(promise) {
if (promise.$$state) {
return promise.$$state.status === promiseStatuses.IN_PROGRESS;
}
if (!promise.hasOwnProperty("$$v")) {
return true;
}
};
isResolved = function(promise) {
if (promise.$$state) {
return promise.$$state.status === promiseStatuses.RESOLVED;
}
if (promise.hasOwnProperty("$$v")) {
return true;
}
};
promiseStatus = function(status) {
return strPromiseStatuses[status] || 'done w error';
};
ExposedPromise = function(promise) {
var cancelDeferred, combined, wrapped;
cancelDeferred = $q.defer();
combined = $q.all([promise, cancelDeferred.promise]);
wrapped = $q.defer();
promise.then(cancelDeferred.resolve, (function() {}), function(notify) {
cancelDeferred.notify(notify);
return wrapped.notify(notify);
});
combined.then(function(successes) {
return wrapped.resolve(successes[0] || successes[1]);
}, function(error) {
return wrapped.reject(error);
});
wrapped.promise.cancel = function(reason) {
if (reason == null) {
reason = 'canceled';
}
return cancelDeferred.reject(reason);
};
wrapped.promise.notify = function(msg) {
if (msg == null) {
msg = 'cancel safe';
}
wrapped.notify(msg);
if (promise.hasOwnProperty('notify')) {
return promise.notify(msg);
}
};
if (promise.promiseType != null) {
wrapped.promise.promiseType = promise.promiseType;
}
return wrapped.promise;
};
SniffedPromise = function(fnPromise, promiseType) {
return {
promise: fnPromise,
promiseType: promiseType
};
};
defer = function() {
return $q.defer();
};
resolve = function() {
var d;
d = $q.defer();
d.resolve.apply(void 0, arguments);
return d.promise;
};
promise = function(fnToWrap) {
var d;
if (!_.isFunction(fnToWrap)) {
$log.error("uiGmapPromise.promise() only accepts functions");
return;
}
d = $q.defer();
$timeout(function() {
var result;
result = fnToWrap();
return d.resolve(result);
});
return d.promise;
};
return {
defer: defer,
promise: promise,
resolve: resolve,
promiseTypes: promiseTypes,
isInProgress: isInProgress,
isResolved: isResolved,
promiseStatus: promiseStatus,
ExposedPromise: ExposedPromise,
SniffedPromise: SniffedPromise
};
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropMap", function() {
/*
Simple Object Map with a length property to make it easy to track length/size
*/
var PropMap;
return PropMap = (function() {
function PropMap() {
this.removeAll = __bind(this.removeAll, this);
this.slice = __bind(this.slice, this);
this.push = __bind(this.push, this);
this.keys = __bind(this.keys, this);
this.values = __bind(this.values, this);
this.remove = __bind(this.remove, this);
this.put = __bind(this.put, this);
this.stateChanged = __bind(this.stateChanged, this);
this.get = __bind(this.get, this);
this.length = 0;
this.dict = {};
this.didValsStateChange = false;
this.didKeysStateChange = false;
this.allVals = [];
this.allKeys = [];
}
PropMap.prototype.get = function(key) {
return this.dict[key];
};
PropMap.prototype.stateChanged = function() {
this.didValsStateChange = true;
return this.didKeysStateChange = true;
};
PropMap.prototype.put = function(key, value) {
if (this.get(key) == null) {
this.length++;
}
this.stateChanged();
return this.dict[key] = value;
};
PropMap.prototype.remove = function(key, isSafe) {
var value;
if (isSafe == null) {
isSafe = false;
}
if (isSafe && !this.get(key)) {
return void 0;
}
value = this.dict[key];
delete this.dict[key];
this.length--;
this.stateChanged();
return value;
};
PropMap.prototype.valuesOrKeys = function(str) {
var keys, vals;
if (str == null) {
str = 'Keys';
}
if (!this["did" + str + "StateChange"]) {
return this['all' + str];
}
vals = [];
keys = [];
_.each(this.dict, function(v, k) {
vals.push(v);
return keys.push(k);
});
this.didKeysStateChange = false;
this.didValsStateChange = false;
this.allVals = vals;
this.allKeys = keys;
return this['all' + str];
};
PropMap.prototype.values = function() {
return this.valuesOrKeys('Vals');
};
PropMap.prototype.keys = function() {
return this.valuesOrKeys();
};
PropMap.prototype.push = function(obj, key) {
if (key == null) {
key = "key";
}
return this.put(obj[key], obj);
};
PropMap.prototype.slice = function() {
return this.keys().map((function(_this) {
return function(k) {
return _this.remove(k);
};
})(this));
};
PropMap.prototype.removeAll = function() {
return this.slice();
};
PropMap.prototype.each = function(cb) {
return _.each(this.dict, function(v, k) {
return cb(v);
});
};
PropMap.prototype.map = function(cb) {
return _.map(this.dict, function(v, k) {
return cb(v);
});
};
return PropMap;
})();
});
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropertyAction", [
"uiGmapLogger", function(Logger) {
var PropertyAction;
PropertyAction = function(setterFn) {
this.setIfChange = function(newVal, oldVal) {
var callingKey;
callingKey = this.exp;
if (!_.isEqual(oldVal, newVal)) {
return setterFn(callingKey, newVal);
}
};
this.sic = this.setIfChange;
return this;
};
return PropertyAction;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapClustererMarkerManager', [
'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', function($log, FitHelper, PropMap) {
var ClustererMarkerManager;
ClustererMarkerManager = (function() {
ClustererMarkerManager.type = 'ClustererMarkerManager';
function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) {
if (opt_markers == null) {
opt_markers = {};
}
this.opt_options = opt_options != null ? opt_options : {};
this.opt_events = opt_events;
this.checkSync = __bind(this.checkSync, this);
this.getGMarkers = __bind(this.getGMarkers, this);
this.fit = __bind(this.fit, this);
this.destroy = __bind(this.destroy, this);
this.clear = __bind(this.clear, this);
this.draw = __bind(this.draw, this);
this.removeMany = __bind(this.removeMany, this);
this.remove = __bind(this.remove, this);
this.addMany = __bind(this.addMany, this);
this.update = __bind(this.update, this);
this.add = __bind(this.add, this);
this.type = ClustererMarkerManager.type;
this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, this.opt_options);
this.propMapGMarkers = new PropMap();
this.attachEvents(this.opt_events, 'opt_events');
this.clusterer.setIgnoreHidden(true);
this.noDrawOnSingleAddRemoves = true;
$log.info(this);
}
ClustererMarkerManager.prototype.checkKey = function(gMarker) {
var msg;
if (gMarker.key == null) {
msg = 'gMarker.key undefined and it is REQUIRED!!';
return $log.error(msg);
}
};
ClustererMarkerManager.prototype.add = function(gMarker) {
this.checkKey(gMarker);
this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves);
this.propMapGMarkers.put(gMarker.key, gMarker);
return this.checkSync();
};
ClustererMarkerManager.prototype.update = function(gMarker) {
this.remove(gMarker);
return this.add(gMarker);
};
ClustererMarkerManager.prototype.addMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.add(gMarker);
};
})(this));
};
ClustererMarkerManager.prototype.remove = function(gMarker) {
var exists;
this.checkKey(gMarker);
exists = this.propMapGMarkers.get(gMarker.key);
if (exists) {
this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves);
this.propMapGMarkers.remove(gMarker.key);
}
return this.checkSync();
};
ClustererMarkerManager.prototype.removeMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.remove(gMarker);
};
})(this));
};
ClustererMarkerManager.prototype.draw = function() {
return this.clusterer.repaint();
};
ClustererMarkerManager.prototype.clear = function() {
this.removeMany(this.getGMarkers());
return this.clusterer.repaint();
};
ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) {
var eventHandler, eventName, _results;
if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {
_results = [];
for (eventName in options) {
eventHandler = options[eventName];
if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {
$log.info("" + optionsName + ": Attaching event: " + eventName + " to clusterer");
_results.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName]));
} else {
_results.push(void 0);
}
}
return _results;
}
};
ClustererMarkerManager.prototype.clearEvents = function(options, optionsName) {
var eventHandler, eventName, _results;
if (angular.isDefined(options) && (options != null) && angular.isObject(options)) {
_results = [];
for (eventName in options) {
eventHandler = options[eventName];
if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) {
$log.info("" + optionsName + ": Clearing event: " + eventName + " to clusterer");
_results.push(google.maps.event.clearListeners(this.clusterer, eventName));
} else {
_results.push(void 0);
}
}
return _results;
}
};
ClustererMarkerManager.prototype.destroy = function() {
this.clearEvents(this.opt_events, 'opt_events');
return this.clear();
};
ClustererMarkerManager.prototype.fit = function() {
return FitHelper.fit(this.getGMarkers(), this.clusterer.getMap());
};
ClustererMarkerManager.prototype.getGMarkers = function() {
return this.clusterer.getMarkers().values();
};
ClustererMarkerManager.prototype.checkSync = function() {};
return ClustererMarkerManager;
})();
return ClustererMarkerManager;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps.directives.api.managers").factory("uiGmapMarkerManager", [
"uiGmapLogger", "uiGmapFitHelper", "uiGmapPropMap", function(Logger, FitHelper, PropMap) {
var MarkerManager;
MarkerManager = (function() {
MarkerManager.type = 'MarkerManager';
function MarkerManager(gMap, opt_markers, opt_options) {
this.getGMarkers = __bind(this.getGMarkers, this);
this.fit = __bind(this.fit, this);
this.handleOptDraw = __bind(this.handleOptDraw, this);
this.clear = __bind(this.clear, this);
this.draw = __bind(this.draw, this);
this.removeMany = __bind(this.removeMany, this);
this.remove = __bind(this.remove, this);
this.addMany = __bind(this.addMany, this);
this.update = __bind(this.update, this);
this.add = __bind(this.add, this);
this.type = MarkerManager.type;
this.gMap = gMap;
this.gMarkers = new PropMap();
this.$log = Logger;
this.$log.info(this);
}
MarkerManager.prototype.add = function(gMarker, optDraw) {
var exists, msg;
if (optDraw == null) {
optDraw = true;
}
if (gMarker.key == null) {
msg = "gMarker.key undefined and it is REQUIRED!!";
Logger.error(msg);
throw msg;
}
exists = this.gMarkers.get(gMarker.key);
if (!exists) {
this.handleOptDraw(gMarker, optDraw, true);
return this.gMarkers.put(gMarker.key, gMarker);
}
};
MarkerManager.prototype.update = function(gMarker, optDraw) {
if (optDraw == null) {
optDraw = true;
}
this.remove(gMarker, optDraw);
return this.add(gMarker, optDraw);
};
MarkerManager.prototype.addMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(gMarker) {
return _this.add(gMarker);
};
})(this));
};
MarkerManager.prototype.remove = function(gMarker, optDraw) {
if (optDraw == null) {
optDraw = true;
}
this.handleOptDraw(gMarker, optDraw, false);
if (this.gMarkers.get(gMarker.key)) {
return this.gMarkers.remove(gMarker.key);
}
};
MarkerManager.prototype.removeMany = function(gMarkers) {
return gMarkers.forEach((function(_this) {
return function(marker) {
return _this.remove(marker);
};
})(this));
};
MarkerManager.prototype.draw = function() {
var deletes;
deletes = [];
this.gMarkers.each((function(_this) {
return function(gMarker) {
if (!gMarker.isDrawn) {
if (gMarker.doAdd) {
gMarker.setMap(_this.gMap);
return gMarker.isDrawn = true;
} else {
return deletes.push(gMarker);
}
}
};
})(this));
return deletes.forEach((function(_this) {
return function(gMarker) {
gMarker.isDrawn = false;
return _this.remove(gMarker, true);
};
})(this));
};
MarkerManager.prototype.clear = function() {
this.gMarkers.each(function(gMarker) {
return gMarker.setMap(null);
});
delete this.gMarkers;
return this.gMarkers = new PropMap();
};
MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) {
if (optDraw === true) {
if (doAdd) {
gMarker.setMap(this.gMap);
} else {
gMarker.setMap(null);
}
return gMarker.isDrawn = true;
} else {
gMarker.isDrawn = false;
return gMarker.doAdd = doAdd;
}
};
MarkerManager.prototype.fit = function() {
return FitHelper.fit(this.getGMarkers(), this.gMap);
};
MarkerManager.prototype.getGMarkers = function() {
return this.gMarkers.values();
};
return MarkerManager;
})();
return MarkerManager;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').factory('uiGmapadd-events', [
'$timeout', function($timeout) {
var addEvent, addEvents;
addEvent = function(target, eventName, handler) {
return google.maps.event.addListener(target, eventName, function() {
handler.apply(this, arguments);
return $timeout((function() {}), true);
});
};
addEvents = function(target, eventName, handler) {
var remove;
if (handler) {
return addEvent(target, eventName, handler);
}
remove = [];
angular.forEach(eventName, function(_handler, key) {
return remove.push(addEvent(target, key, _handler));
});
return function() {
angular.forEach(remove, function(listener) {
return google.maps.event.removeListener(listener);
});
return remove = null;
};
};
return addEvents;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').factory('uiGmaparray-sync', [
'uiGmapadd-events', function(mapEvents) {
return function(mapArray, scope, pathEval, pathChangedFn) {
var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener;
isSetFromScope = false;
scopePath = scope.$eval(pathEval);
if (!scope["static"]) {
legacyHandlers = {
set_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return scopePath[index] = value;
} else {
scopePath[index].latitude = value.lat();
return scopePath[index].longitude = value.lng();
}
},
insert_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return scopePath.splice(index, 0, value);
} else {
return scopePath.splice(index, 0, {
latitude: value.lat(),
longitude: value.lng()
});
}
},
remove_at: function(index) {
if (isSetFromScope) {
return;
}
return scopePath.splice(index, 1);
}
};
geojsonArray;
if (scopePath.type === 'Polygon') {
geojsonArray = scopePath.coordinates[0];
} else if (scopePath.type === 'LineString') {
geojsonArray = scopePath.coordinates;
}
geojsonHandlers = {
set_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return;
}
geojsonArray[index][1] = value.lat();
return geojsonArray[index][0] = value.lng();
},
insert_at: function(index) {
var value;
if (isSetFromScope) {
return;
}
value = mapArray.getAt(index);
if (!value) {
return;
}
if (!value.lng || !value.lat) {
return;
}
return geojsonArray.splice(index, 0, [value.lng(), value.lat()]);
},
remove_at: function(index) {
if (isSetFromScope) {
return;
}
return geojsonArray.splice(index, 1);
}
};
mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers);
}
legacyWatcher = function(newPath) {
var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;
isSetFromScope = true;
oldArray = mapArray;
changed = false;
if (newPath) {
i = 0;
oldLength = oldArray.getLength();
newLength = newPath.length;
l = Math.min(oldLength, newLength);
newValue = void 0;
while (i < l) {
oldValue = oldArray.getAt(i);
newValue = newPath[i];
if (typeof newValue.equals === 'function') {
if (!newValue.equals(oldValue)) {
oldArray.setAt(i, newValue);
changed = true;
}
} else {
if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) {
oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude));
changed = true;
}
}
i++;
}
while (i < newLength) {
newValue = newPath[i];
if (typeof newValue.lat === 'function' && typeof newValue.lng === 'function') {
oldArray.push(newValue);
} else {
oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude));
}
changed = true;
i++;
}
while (i < oldLength) {
oldArray.pop();
changed = true;
i++;
}
}
isSetFromScope = false;
if (changed) {
return pathChangedFn(oldArray);
}
};
geojsonWatcher = function(newPath) {
var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue;
isSetFromScope = true;
oldArray = mapArray;
changed = false;
if (newPath) {
array;
if (scopePath.type === 'Polygon') {
array = newPath.coordinates[0];
} else if (scopePath.type === 'LineString') {
array = newPath.coordinates;
}
i = 0;
oldLength = oldArray.getLength();
newLength = array.length;
l = Math.min(oldLength, newLength);
newValue = void 0;
while (i < l) {
oldValue = oldArray.getAt(i);
newValue = array[i];
if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) {
oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0]));
changed = true;
}
i++;
}
while (i < newLength) {
newValue = array[i];
oldArray.push(new google.maps.LatLng(newValue[1], newValue[0]));
changed = true;
i++;
}
while (i < oldLength) {
oldArray.pop();
changed = true;
i++;
}
}
isSetFromScope = false;
if (changed) {
return pathChangedFn(oldArray);
}
};
watchListener;
if (!scope["static"]) {
if (angular.isUndefined(scopePath.type)) {
watchListener = scope.$watchCollection(pathEval, legacyWatcher);
} else {
watchListener = scope.$watch(pathEval, geojsonWatcher, true);
}
}
return function() {
if (mapArrayListener) {
mapArrayListener();
mapArrayListener = null;
}
if (watchListener) {
watchListener();
return watchListener = null;
}
};
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapChromeFixes", [
'$timeout', function($timeout) {
return {
maybeRepaint: function(el) {
if (el) {
el.style.opacity = 0.9;
return $timeout(function() {
return el.style.opacity = 1;
});
}
}
};
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.options.builders').service('uiGmapCommonOptionsBuilder', [
'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapModelKey', function(BaseObject, $log, ModelKey) {
var CommonOptionsBuilder;
return CommonOptionsBuilder = (function(_super) {
__extends(CommonOptionsBuilder, _super);
function CommonOptionsBuilder() {
this.watchProps = __bind(this.watchProps, this);
this.buildOpts = __bind(this.buildOpts, this);
this.hasModel = _(this.scope).chain().keys().contains('model').value();
}
CommonOptionsBuilder.prototype.props = [
'clickable', 'draggable', 'editable', 'visible', {
prop: 'stroke',
isColl: true
}
];
CommonOptionsBuilder.prototype.buildOpts = function(customOpts, forEachOpts) {
var model, opts, stroke;
if (customOpts == null) {
customOpts = {};
}
if (forEachOpts == null) {
forEachOpts = {};
}
if (!this.scope) {
$log.error('this.scope not defined in CommonOptionsBuilder can not buildOpts');
return;
}
if (!this.map) {
$log.error('this.map not defined in CommonOptionsBuilder can not buildOpts');
return;
}
model = this.hasModel ? this.scope.model : this.scope;
stroke = this.scopeOrModelVal('stroke', this.scope, model);
opts = angular.extend(customOpts, this.DEFAULTS, {
map: this.map,
strokeColor: stroke != null ? stroke.color : void 0,
strokeOpacity: stroke != null ? stroke.opacity : void 0,
strokeWeight: stroke != null ? stroke.weight : void 0
});
angular.forEach(angular.extend(forEachOpts, {
clickable: true,
draggable: false,
editable: false,
"static": false,
fit: false,
visible: true,
zIndex: 0,
icons: []
}), (function(_this) {
return function(defaultValue, key) {
var val;
val = _this.scopeOrModelVal(key, _this.scope, model);
if (angular.isUndefined(val)) {
return opts[key] = defaultValue;
} else {
return opts[key] = model[key];
}
};
})(this));
if (opts["static"]) {
opts.editable = false;
}
return opts;
};
CommonOptionsBuilder.prototype.watchProps = function(props) {
if (props == null) {
props = this.props;
}
return props.forEach((function(_this) {
return function(prop) {
if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) {
if (prop != null ? prop.isColl : void 0) {
return _this.scope.$watchCollection(prop.prop, _this.setMyOptions);
} else {
return _this.scope.$watch(prop, _this.setMyOptions);
}
}
};
})(this));
};
return CommonOptionsBuilder;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.options.builders').factory('uiGmapPolylineOptionsBuilder', [
'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {
var PolylineOptionsBuilder;
return PolylineOptionsBuilder = (function(_super) {
__extends(PolylineOptionsBuilder, _super);
function PolylineOptionsBuilder() {
return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments);
}
PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints) {
return PolylineOptionsBuilder.__super__.buildOpts.call(this, {
path: pathPoints
}, {
geodesic: false
});
};
return PolylineOptionsBuilder;
})(CommonOptionsBuilder);
}
]).factory('uiGmapShapeOptionsBuilder', [
'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) {
var ShapeOptionsBuilder;
return ShapeOptionsBuilder = (function(_super) {
__extends(ShapeOptionsBuilder, _super);
function ShapeOptionsBuilder() {
return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments);
}
ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, forEachOpts) {
var fill, model;
model = this.hasModel ? this.scope.model : this.scope;
fill = this.scopeOrModelVal('fill', this.scope, model);
customOpts = angular.extend(customOpts, {
fillColor: fill != null ? fill.color : void 0,
fillOpacity: fill != null ? fill.opacity : void 0
});
return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, forEachOpts);
};
return ShapeOptionsBuilder;
})(CommonOptionsBuilder);
}
]).factory('uiGmapPolygonOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var PolygonOptionsBuilder;
return PolygonOptionsBuilder = (function(_super) {
__extends(PolygonOptionsBuilder, _super);
function PolygonOptionsBuilder() {
return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments);
}
PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints) {
return PolygonOptionsBuilder.__super__.buildOpts.call(this, {
path: pathPoints
}, {
geodesic: false
});
};
return PolygonOptionsBuilder;
})(ShapeOptionsBuilder);
}
]).factory('uiGmapRectangleOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var RectangleOptionsBuilder;
return RectangleOptionsBuilder = (function(_super) {
__extends(RectangleOptionsBuilder, _super);
function RectangleOptionsBuilder() {
return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments);
}
RectangleOptionsBuilder.prototype.buildOpts = function(bounds) {
return RectangleOptionsBuilder.__super__.buildOpts.call(this, {
bounds: bounds
});
};
return RectangleOptionsBuilder;
})(ShapeOptionsBuilder);
}
]).factory('uiGmapCircleOptionsBuilder', [
'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) {
var CircleOptionsBuilder;
return CircleOptionsBuilder = (function(_super) {
__extends(CircleOptionsBuilder, _super);
function CircleOptionsBuilder() {
return CircleOptionsBuilder.__super__.constructor.apply(this, arguments);
}
CircleOptionsBuilder.prototype.buildOpts = function(center, radius) {
return CircleOptionsBuilder.__super__.buildOpts.call(this, {
center: center,
radius: radius
});
};
return CircleOptionsBuilder;
})(ShapeOptionsBuilder);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api.options').service('uiGmapMarkerOptions', [
'uiGmapLogger', 'uiGmapGmapUtil', function($log, GmapUtil) {
return _.extend(GmapUtil, {
createOptions: function(coords, icon, defaults, map) {
var opts;
if (defaults == null) {
defaults = {};
}
opts = angular.extend({}, defaults, {
position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords),
visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords)
});
if ((defaults.icon != null) || (icon != null)) {
opts = angular.extend(opts, {
icon: defaults.icon != null ? defaults.icon : icon
});
}
if (map != null) {
opts.map = map;
}
return opts;
},
isLabel: function(options) {
if (options == null) {
return false;
}
return (options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null);
}
});
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapBasePolyChildModel', [
'uiGmapLogger', '$timeout', 'uiGmaparray-sync', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function($log, $timeout, arraySync, GmapUtil, EventsHelper) {
return function(Builder, gFactory) {
var BasePolyChildModel;
return BasePolyChildModel = (function(_super) {
__extends(BasePolyChildModel, _super);
BasePolyChildModel.include(GmapUtil);
function BasePolyChildModel(scope, attrs, map, defaults, model) {
var create;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.defaults = defaults;
this.model = model;
this.clean = __bind(this.clean, this);
this.clonedModel = _.clone(this.model, true);
this.isDragging = false;
this.internalEvents = {
dragend: (function(_this) {
return function() {
return _.defer(function() {
return _this.isDragging = false;
});
};
})(this),
dragstart: (function(_this) {
return function() {
return _this.isDragging = true;
};
})(this)
};
create = (function(_this) {
return function() {
var pathPoints;
if (_this.isDragging) {
return;
}
pathPoints = _this.convertPathPoints(_this.scope.path);
if (_this.gObject != null) {
_this.clean();
}
if (pathPoints.length > 0) {
_this.gObject = gFactory(_this.buildOpts(pathPoints));
}
if (_this.gObject) {
if (_this.scope.fit) {
_this.extendMapBounds(map, pathPoints);
}
arraySync(_this.gObject.getPath(), _this.scope, 'path', function(pathPoints) {
if (_this.scope.fit) {
return _this.extendMapBounds(map, pathPoints);
}
});
if (angular.isDefined(scope.events) && angular.isObject(scope.events)) {
_this.listeners = _this.model ? EventsHelper.setEvents(_this.gObject, _this.scope, _this.model) : EventsHelper.setEvents(_this.gObject, _this.scope, _this.scope);
}
return _this.internalListeners = _this.model ? EventsHelper.setEvents(_this.gObject, {
events: _this.internalEvents
}, _this.model) : EventsHelper.setEvents(_this.gObject, {
events: _this.internalEvents
}, _this.scope);
}
};
})(this);
create();
scope.$watch('path', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue) || !_this.gObject) {
return create();
}
};
})(this), true);
if (!scope["static"] && angular.isDefined(scope.editable)) {
scope.$watch('editable', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (_ref = _this.gObject) != null ? _ref.setEditable(newValue) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.draggable)) {
scope.$watch('draggable', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (_ref = _this.gObject) != null ? _ref.setDraggable(newValue) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.visible)) {
scope.$watch('visible', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
}
return (_ref = _this.gObject) != null ? _ref.setVisible(newValue) : void 0;
};
})(this), true);
}
if (angular.isDefined(scope.geodesic)) {
scope.$watch('geodesic', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
newValue = !_this.isFalse(newValue);
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) {
scope.$watch('stroke.weight', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) {
scope.$watch('stroke.color', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.opacity)) {
scope.$watch('stroke.opacity', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
if (angular.isDefined(scope.icons)) {
scope.$watch('icons', (function(_this) {
return function(newValue, oldValue) {
var _ref;
if (newValue !== oldValue) {
return (_ref = _this.gObject) != null ? _ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0;
}
};
})(this), true);
}
scope.$on('$destroy', (function(_this) {
return function() {
_this.clean();
return _this.scope = null;
};
})(this));
if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.color)) {
scope.$watch('fill.color', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.opacity)) {
scope.$watch('fill.opacity', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
if (angular.isDefined(scope.zIndex)) {
scope.$watch('zIndex', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath()));
}
};
})(this));
}
}
BasePolyChildModel.prototype.clean = function() {
var _ref;
EventsHelper.removeEvents(this.listeners);
EventsHelper.removeEvents(this.internalListeners);
if ((_ref = this.gObject) != null) {
_ref.setMap(null);
}
return this.gObject = null;
};
return BasePolyChildModel;
})(Builder);
};
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , &
http://jsfiddle.net/YsQdh/88/
*/
(function() {
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapDrawFreeHandChildModel', [
'uiGmapLogger', '$q', function($log, $q) {
var drawFreeHand, freeHandMgr;
drawFreeHand = function(map, polys, enable) {
var move, poly;
poly = new google.maps.Polyline({
map: map,
clickable: false
});
move = google.maps.event.addListener(map, 'mousemove', function(e) {
return poly.getPath().push(e.latLng);
});
google.maps.event.addListenerOnce(map, 'mouseup', function(e) {
var path;
google.maps.event.removeListener(move);
path = poly.getPath();
poly.setMap(null);
polys.push(new google.maps.Polygon({
map: map,
path: path
}));
poly = null;
google.maps.event.clearListeners(map.getDiv(), 'mousedown');
return enable();
});
return void 0;
};
freeHandMgr = function(map, defaultOptions) {
var disableMap, enable;
this.map = map;
if (!defaultOptions) {
defaultOptions = {
draggable: true,
zoomControl: true,
scrollwheel: true,
disableDoubleClickZoom: true
};
}
enable = (function(_this) {
return function() {
var _ref;
if ((_ref = _this.deferred) != null) {
_ref.resolve();
}
return _.defer(function() {
return _this.map.setOptions(_.extend(_this.oldOptions, defaultOptions));
});
};
})(this);
disableMap = (function(_this) {
return function() {
$log.info('disabling map move');
_this.oldOptions = map.getOptions();
_this.oldOptions.center = map.getCenter();
return _this.map.setOptions({
draggable: false,
zoomControl: false,
scrollwheel: false,
disableDoubleClickZoom: false
});
};
})(this);
this.engage = (function(_this) {
return function(polys) {
_this.polys = polys;
_this.deferred = $q.defer();
disableMap();
$log.info('DrawFreeHandChildModel is engaged (drawing).');
google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) {
return drawFreeHand(_this.map, _this.polys, enable);
});
return _this.deferred.promise;
};
})(this);
return this;
};
return freeHandMgr;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapMarkerChildModel', [
'uiGmapModelKey', 'uiGmapGmapUtil', 'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction', 'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise', function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) {
var MarkerChildModel;
MarkerChildModel = (function(_super) {
var destroy;
__extends(MarkerChildModel, _super);
MarkerChildModel.include(GmapUtil);
MarkerChildModel.include(EventsHelper);
MarkerChildModel.include(MarkerOptions);
destroy = function(child) {
if ((child != null ? child.gObject : void 0) != null) {
child.removeEvents(child.externalListeners);
child.removeEvents(child.internalListeners);
if (child != null ? child.gObject : void 0) {
if (child.removeFromManager) {
child.gManager.remove(child.gObject);
}
child.gObject.setMap(null);
return child.gObject = null;
}
}
};
function MarkerChildModel(scope, model, keys, gMap, defaults, doClick, gManager, doDrawSelf, trackModel, needRedraw) {
var action;
this.model = model;
this.keys = keys;
this.gMap = gMap;
this.defaults = defaults;
this.doClick = doClick;
this.gManager = gManager;
this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true;
this.trackModel = trackModel != null ? trackModel : true;
this.needRedraw = needRedraw != null ? needRedraw : false;
this.internalEvents = __bind(this.internalEvents, this);
this.setLabelOptions = __bind(this.setLabelOptions, this);
this.setOptions = __bind(this.setOptions, this);
this.setIcon = __bind(this.setIcon, this);
this.setCoords = __bind(this.setCoords, this);
this.isNotValid = __bind(this.isNotValid, this);
this.maybeSetScopeValue = __bind(this.maybeSetScopeValue, this);
this.createMarker = __bind(this.createMarker, this);
this.setMyScope = __bind(this.setMyScope, this);
this.updateModel = __bind(this.updateModel, this);
this.handleModelChanges = __bind(this.handleModelChanges, this);
this.destroy = __bind(this.destroy, this);
this.clonedModel = _.extend({}, this.model);
this.deferred = uiGmapPromise.defer();
_.each(this.keys, (function(_this) {
return function(v, k) {
return _this[k + 'Key'] = _.isFunction(_this.keys[k]) ? _this.keys[k]() : _this.keys[k];
};
})(this));
this.idKey = this.idKeyKey || 'id';
if (this.model[this.idKey] != null) {
this.id = this.model[this.idKey];
}
MarkerChildModel.__super__.constructor.call(this, scope);
this.scope.getGMarker = (function(_this) {
return function() {
return _this.gObject;
};
})(this);
this.firstTime = true;
if (this.trackModel) {
this.scope.model = this.model;
this.scope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.handleModelChanges(newValue, oldValue);
}
};
})(this), true);
} else {
action = new PropertyAction((function(_this) {
return function(calledKey, newVal) {
if (!_this.firstTime) {
return _this.setMyScope(calledKey, scope);
}
};
})(this), false);
_.each(this.keys, function(v, k) {
return scope.$watch(k, action.sic, true);
});
}
this.scope.$on('$destroy', (function(_this) {
return function() {
return destroy(_this);
};
})(this));
this.createMarker(this.model);
$log.info(this);
}
MarkerChildModel.prototype.destroy = function(removeFromManager) {
if (removeFromManager == null) {
removeFromManager = true;
}
this.removeFromManager = removeFromManager;
return this.scope.$destroy();
};
MarkerChildModel.prototype.handleModelChanges = function(newValue, oldValue) {
var changes, ctr, len;
changes = this.getChanges(newValue, oldValue, IMarker.keys);
if (!this.firstTime) {
ctr = 0;
len = _.keys(changes).length;
return _.each(changes, (function(_this) {
return function(v, k) {
var doDraw;
ctr += 1;
doDraw = len === ctr;
_this.setMyScope(k, newValue, oldValue, false, true, doDraw);
return _this.needRedraw = true;
};
})(this));
}
};
MarkerChildModel.prototype.updateModel = function(model) {
this.clonedModel = _.extend({}, model);
return this.setMyScope('all', model, this.model);
};
MarkerChildModel.prototype.renderGMarker = function(doDraw, validCb) {
var coords;
if (doDraw == null) {
doDraw = true;
}
coords = this.getProp(this.coordsKey, this.model);
if (coords != null) {
if (!this.validateCoords(coords)) {
$log.debug('MarkerChild does not have coords yet. They may be defined later.');
return;
}
if (validCb != null) {
validCb();
}
if (doDraw && this.gObject) {
return this.gManager.add(this.gObject);
}
} else {
if (doDraw && this.gObject) {
return this.gManager.remove(this.gObject);
}
}
};
MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit, doDraw) {
var justCreated;
if (oldModel == null) {
oldModel = void 0;
}
if (isInit == null) {
isInit = false;
}
if (doDraw == null) {
doDraw = true;
}
if (model == null) {
model = this.model;
} else {
this.model = model;
}
if (!this.gObject) {
this.setOptions(this.scope, doDraw);
justCreated = true;
}
switch (thingThatChanged) {
case 'all':
return _.each(this.keys, (function(_this) {
return function(v, k) {
return _this.setMyScope(k, model, oldModel, isInit, doDraw);
};
})(this));
case 'icon':
return this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon, doDraw);
case 'coords':
return this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords, doDraw);
case 'options':
if (!justCreated) {
return this.createMarker(model, oldModel, isInit, doDraw);
}
}
};
MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit, doDraw) {
if (oldModel == null) {
oldModel = void 0;
}
if (isInit == null) {
isInit = false;
}
if (doDraw == null) {
doDraw = true;
}
this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions, doDraw);
return this.firstTime = false;
};
MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter, doDraw) {
if (gSetter == null) {
gSetter = void 0;
}
if (doDraw == null) {
doDraw = true;
}
if (gSetter != null) {
return gSetter(this.scope, doDraw);
}
};
if (MarkerChildModel.doDrawSelf && doDraw) {
MarkerChildModel.gManager.draw();
}
MarkerChildModel.prototype.isNotValid = function(scope, doCheckGmarker) {
var hasIdenticalScopes, hasNoGmarker;
if (doCheckGmarker == null) {
doCheckGmarker = true;
}
hasNoGmarker = !doCheckGmarker ? false : this.gObject === void 0;
hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false;
return hasIdenticalScopes || hasNoGmarker;
};
MarkerChildModel.prototype.setCoords = function(scope, doDraw) {
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope) || (this.gObject == null)) {
return;
}
return this.renderGMarker(doDraw, (function(_this) {
return function() {
var newGValue, newModelVal, oldGValue;
newModelVal = _this.getProp(_this.coordsKey, _this.model);
newGValue = _this.getCoords(newModelVal);
oldGValue = _this.gObject.getPosition();
if ((oldGValue != null) && (newGValue != null)) {
if (newGValue.lng() === oldGValue.lng() && newGValue.lat() === oldGValue.lat()) {
return;
}
}
_this.gObject.setPosition(newGValue);
return _this.gObject.setVisible(_this.validateCoords(newModelVal));
};
})(this));
};
MarkerChildModel.prototype.setIcon = function(scope, doDraw) {
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope) || (this.gObject == null)) {
return;
}
return this.renderGMarker(doDraw, (function(_this) {
return function() {
var coords, newValue, oldValue;
oldValue = _this.gObject.getIcon();
newValue = _this.getProp(_this.iconKey, _this.model);
if (oldValue === newValue) {
return;
}
_this.gObject.setIcon(newValue);
coords = _this.getProp(_this.coordsKey, _this.model);
_this.gObject.setPosition(_this.getCoords(coords));
return _this.gObject.setVisible(_this.validateCoords(coords));
};
})(this));
};
MarkerChildModel.prototype.setOptions = function(scope, doDraw) {
var _ref;
if (doDraw == null) {
doDraw = true;
}
if (this.isNotValid(scope, false)) {
return;
}
this.renderGMarker(doDraw, (function(_this) {
return function() {
var coords, icon, _options;
coords = _this.getProp(_this.coordsKey, _this.model);
icon = _this.getProp(_this.iconKey, _this.model);
_options = _this.getProp(_this.optionsKey, _this.model);
_this.opts = _this.createOptions(coords, icon, _options);
if (_this.isLabel(_this.gObject) !== _this.isLabel(_this.opts) && (_this.gObject != null)) {
_this.gManager.remove(_this.gObject);
_this.gObject = void 0;
}
if (_this.gObject != null) {
_this.gObject.setOptions(_this.setLabelOptions(_this.opts));
}
if (!_this.gObject) {
if (_this.isLabel(_this.opts)) {
_this.gObject = new MarkerWithLabel(_this.setLabelOptions(_this.opts));
} else {
_this.gObject = new google.maps.Marker(_this.opts);
}
_.extend(_this.gObject, {
model: _this.model
});
}
if (_this.externalListeners) {
_this.removeEvents(_this.externalListeners);
}
if (_this.internalListeners) {
_this.removeEvents(_this.internalListeners);
}
_this.externalListeners = _this.setEvents(_this.gObject, _this.scope, _this.model, ['dragend']);
_this.internalListeners = _this.setEvents(_this.gObject, {
events: _this.internalEvents(),
$evalAsync: function() {}
}, _this.model);
if (_this.id != null) {
return _this.gObject.key = _this.id;
}
};
})(this));
if (this.gObject && (this.gObject.getMap() || this.gManager.type !== MarkerManager.type)) {
this.deferred.resolve(this.gObject);
} else {
if (!this.gObject) {
return this.deferred.reject('gObject is null');
}
if (!(((_ref = this.gObject) != null ? _ref.getMap() : void 0) && this.gManager.type === MarkerManager.type)) {
$log.debug('gObject has no map yet');
this.deferred.resolve(this.gObject);
}
}
if (this.model[this.fitKey]) {
return this.gManager.fit();
}
};
MarkerChildModel.prototype.setLabelOptions = function(opts) {
opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor);
return opts;
};
MarkerChildModel.prototype.internalEvents = function() {
return {
dragend: (function(_this) {
return function(marker, eventName, model, mousearg) {
var events, modelToSet, newCoords;
modelToSet = _this.trackModel ? _this.scope.model : _this.model;
newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gObject.getPosition());
modelToSet = _this.setVal(model, _this.coordsKey, newCoords);
events = _this.scope.events;
if ((events != null ? events.dragend : void 0) != null) {
events.dragend(marker, eventName, modelToSet, mousearg);
}
return _this.scope.$apply();
};
})(this),
click: (function(_this) {
return function(marker, eventName, model, mousearg) {
var click;
click = _.isFunction(_this.clickKey) ? _this.clickKey : _this.getProp(_this.clickKey, _this.model);
if (_this.doClick && (click != null)) {
return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg));
}
};
})(this)
};
};
return MarkerChildModel;
})(ModelKey);
return MarkerChildModel;
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygonChildModel', [
'uiGmapBasePolyChildModel', 'uiGmapPolygonOptionsBuilder', function(BaseGen, Builder) {
var PolygonChildModel, base, gFactory;
gFactory = function(opts) {
return new google.maps.Polygon(opts);
};
base = new BaseGen(Builder, gFactory);
return PolygonChildModel = (function(_super) {
__extends(PolygonChildModel, _super);
function PolygonChildModel() {
return PolygonChildModel.__super__.constructor.apply(this, arguments);
}
return PolygonChildModel;
})(base);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylineChildModel', [
'uiGmapBasePolyChildModel', 'uiGmapPolylineOptionsBuilder', function(BaseGen, Builder) {
var PolylineChildModel, base, gFactory;
gFactory = function(opts) {
return new google.maps.Polyline(opts);
};
base = BaseGen(Builder, gFactory);
return PolylineChildModel = (function(_super) {
__extends(PolylineChildModel, _super);
function PolylineChildModel() {
return PolylineChildModel.__super__.constructor.apply(this, arguments);
}
return PolylineChildModel;
})(base);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapWindowChildModel', [
'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapLogger', '$compile', '$http', '$templateCache', 'uiGmapChromeFixes', 'uiGmapEventsHelper', function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache, ChromeFixes, EventsHelper) {
var WindowChildModel;
WindowChildModel = (function(_super) {
__extends(WindowChildModel, _super);
WindowChildModel.include(GmapUtil);
WindowChildModel.include(EventsHelper);
function WindowChildModel(model, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) {
var maybeMarker;
this.model = model;
this.scope = scope;
this.opts = opts;
this.isIconVisibleOnClick = isIconVisibleOnClick;
this.mapCtrl = mapCtrl;
this.markerScope = markerScope;
this.element = element;
this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false;
this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true;
this.updateModel = __bind(this.updateModel, this);
this.destroy = __bind(this.destroy, this);
this.remove = __bind(this.remove, this);
this.getLatestPosition = __bind(this.getLatestPosition, this);
this.hideWindow = __bind(this.hideWindow, this);
this.showWindow = __bind(this.showWindow, this);
this.handleClick = __bind(this.handleClick, this);
this.watchOptions = __bind(this.watchOptions, this);
this.watchCoords = __bind(this.watchCoords, this);
this.createGWin = __bind(this.createGWin, this);
this.watchElement = __bind(this.watchElement, this);
this.watchAndDoShow = __bind(this.watchAndDoShow, this);
this.doShow = __bind(this.doShow, this);
this.clonedModel = _.clone(this.model, true);
this.getGmarker = function() {
var _ref, _ref1;
if (((_ref = this.markerScope) != null ? _ref['getGMarker'] : void 0) != null) {
return (_ref1 = this.markerScope) != null ? _ref1.getGMarker() : void 0;
}
};
this.listeners = [];
this.createGWin();
maybeMarker = this.getGmarker();
if (maybeMarker != null) {
maybeMarker.setClickable(true);
}
this.watchElement();
this.watchOptions();
this.watchCoords();
this.watchAndDoShow();
this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.destroy();
};
})(this));
$log.info(this);
}
WindowChildModel.prototype.doShow = function(wasOpen) {
if (this.scope.show === true || wasOpen) {
return this.showWindow();
} else {
return this.hideWindow();
}
};
WindowChildModel.prototype.watchAndDoShow = function() {
if (this.model.show != null) {
this.scope.show = this.model.show;
}
this.scope.$watch('show', this.doShow, true);
return this.doShow();
};
WindowChildModel.prototype.watchElement = function() {
return this.scope.$watch((function(_this) {
return function() {
var wasOpen, _ref;
if (!(_this.element || _this.html)) {
return;
}
if (_this.html !== _this.element.html() && _this.gObject) {
if ((_ref = _this.opts) != null) {
_ref.content = void 0;
}
wasOpen = _this.gObject.isOpen();
_this.remove();
return _this.createGWin(wasOpen);
}
};
})(this));
};
WindowChildModel.prototype.createGWin = function(isOpen) {
var defaults, maybeMarker, _opts, _ref, _ref1;
if (isOpen == null) {
isOpen = false;
}
maybeMarker = this.getGmarker();
defaults = {};
if (this.opts != null) {
if (this.scope.coords) {
this.opts.position = this.getCoords(this.scope.coords);
}
defaults = this.opts;
}
if (this.element) {
this.html = _.isObject(this.element) ? this.element.html() : this.element;
}
_opts = this.scope.options ? this.scope.options : defaults;
this.opts = this.createWindowOptions(maybeMarker, this.markerScope || this.scope, this.html, _opts);
if (this.opts != null) {
if (!this.gObject) {
if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) {
this.gObject = new window.InfoBox(this.opts);
} else {
this.gObject = new google.maps.InfoWindow(this.opts);
}
this.listeners.push(google.maps.event.addListener(this.gObject, 'domready', function() {
return ChromeFixes.maybeRepaint(this.content);
}));
this.listeners.push(google.maps.event.addListener(this.gObject, 'closeclick', (function(_this) {
return function() {
if (maybeMarker) {
maybeMarker.setAnimation(_this.oldMarkerAnimation);
if (_this.markerIsVisibleAfterWindowClose) {
_.delay(function() {
maybeMarker.setVisible(false);
return maybeMarker.setVisible(_this.markerIsVisibleAfterWindowClose);
}, 250);
}
}
_this.gObject.close();
_this.model.show = false;
if (_this.scope.closeClick != null) {
return _this.scope.$evalAsync(_this.scope.closeClick());
} else {
return _this.scope.$evalAsync();
}
};
})(this)));
}
this.gObject.setContent(this.opts.content);
this.handleClick(((_ref = this.scope) != null ? (_ref1 = _ref.options) != null ? _ref1.forceClick : void 0 : void 0) || isOpen);
return this.doShow(this.gObject.isOpen());
}
};
WindowChildModel.prototype.watchCoords = function() {
var scope;
scope = this.markerScope != null ? this.markerScope : this.scope;
return scope.$watch('coords', (function(_this) {
return function(newValue, oldValue) {
var pos;
if (newValue !== oldValue) {
if (newValue == null) {
_this.hideWindow();
} else if (!_this.validateCoords(newValue)) {
$log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model)));
return;
}
pos = _this.getCoords(newValue);
_this.gObject.setPosition(pos);
if (_this.opts) {
return _this.opts.position = pos;
}
}
};
})(this), true);
};
WindowChildModel.prototype.watchOptions = function() {
return this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.opts = newValue;
if (_this.gObject != null) {
_this.gObject.setOptions(_this.opts);
if ((_this.opts.visible != null) && _this.opts.visible) {
return _this.showWindow();
} else if (_this.opts.visible != null) {
return _this.hideWindow();
}
}
}
};
})(this), true);
};
WindowChildModel.prototype.handleClick = function(forceClick) {
var click, maybeMarker;
if (this.gObject == null) {
return;
}
maybeMarker = this.getGmarker();
click = (function(_this) {
return function() {
if (_this.gObject == null) {
_this.createGWin();
}
_this.showWindow();
if (maybeMarker != null) {
_this.initialMarkerVisibility = maybeMarker.getVisible();
_this.oldMarkerAnimation = maybeMarker.getAnimation();
return maybeMarker.setVisible(_this.isIconVisibleOnClick);
}
};
})(this);
if (forceClick) {
click();
}
if (maybeMarker) {
return this.listeners = this.listeners.concat(this.setEvents(maybeMarker, {
events: {
click: click
}
}, this.model));
}
};
WindowChildModel.prototype.showWindow = function() {
var compiled, show, templateScope;
if (this.gObject != null) {
show = (function(_this) {
return function() {
var isOpen, maybeMarker, pos;
if (!_this.gObject.isOpen()) {
maybeMarker = _this.getGmarker();
if ((_this.gObject != null) && (_this.gObject.getPosition != null)) {
pos = _this.gObject.getPosition();
}
if (maybeMarker) {
pos = maybeMarker.getPosition();
}
if (!pos) {
return;
}
_this.gObject.open(_this.mapCtrl, maybeMarker);
isOpen = _this.gObject.isOpen();
if (_this.model.show !== isOpen) {
return _this.model.show = isOpen;
}
}
};
})(this);
if (this.scope.templateUrl) {
return $http.get(this.scope.templateUrl, {
cache: $templateCache
}).then((function(_this) {
return function(content) {
var compiled, templateScope;
templateScope = _this.scope.$new();
if (angular.isDefined(_this.scope.templateParameter)) {
templateScope.parameter = _this.scope.templateParameter;
}
compiled = $compile(content.data)(templateScope);
_this.gObject.setContent(compiled[0]);
return show();
};
})(this));
} else if (this.scope.template) {
templateScope = this.scope.$new();
if (angular.isDefined(this.scope.templateParameter)) {
templateScope.parameter = this.scope.templateParameter;
}
compiled = $compile(this.scope.template)(templateScope);
this.gObject.setContent(compiled[0]);
return show();
} else {
return show();
}
}
};
WindowChildModel.prototype.hideWindow = function() {
if ((this.gObject != null) && this.gObject.isOpen()) {
return this.gObject.close();
}
};
WindowChildModel.prototype.getLatestPosition = function(overridePos) {
var maybeMarker;
maybeMarker = this.getGmarker();
if ((this.gObject != null) && (maybeMarker != null) && !overridePos) {
return this.gObject.setPosition(maybeMarker.getPosition());
} else {
if (overridePos) {
return this.gObject.setPosition(overridePos);
}
}
};
WindowChildModel.prototype.remove = function() {
this.hideWindow();
this.removeEvents(this.listeners);
this.listeners.length = 0;
delete this.gObject;
return delete this.opts;
};
WindowChildModel.prototype.destroy = function(manualOverride) {
var _ref;
if (manualOverride == null) {
manualOverride = false;
}
this.remove();
if ((this.scope != null) && !((_ref = this.scope) != null ? _ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) {
return this.scope.$destroy();
}
};
WindowChildModel.prototype.updateModel = function(model) {
this.clonedModel = _.extend({}, model);
return _.extend(this.model, this.clonedModel);
};
return WindowChildModel;
})(BaseObject);
return WindowChildModel;
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapCircleParentModel', [
'uiGmapLogger', '$timeout', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapCircleOptionsBuilder', function($log, $timeout, GmapUtil, EventsHelper, Builder) {
var CircleParentModel;
return CircleParentModel = (function(_super) {
__extends(CircleParentModel, _super);
CircleParentModel.include(GmapUtil);
CircleParentModel.include(EventsHelper);
function CircleParentModel(scope, element, attrs, map, DEFAULTS) {
var clean, gObject, lastRadius;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.DEFAULTS = DEFAULTS;
lastRadius = null;
clean = (function(_this) {
return function() {
lastRadius = null;
if (_this.listeners != null) {
_this.removeEvents(_this.listeners);
return _this.listeners = void 0;
}
};
})(this);
gObject = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));
this.setMyOptions = (function(_this) {
return function(newVals, oldVals) {
if (!_.isEqual(newVals, oldVals)) {
return gObject.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius));
}
};
})(this);
this.props = this.props.concat([
{
prop: 'center',
isColl: true
}, {
prop: 'fill',
isColl: true
}, 'radius'
]);
this.watchProps();
clean();
this.listeners = this.setEvents(gObject, scope, scope, ['radius_changed']);
if (this.listeners != null) {
this.listeners.push(google.maps.event.addListener(gObject, 'radius_changed', function() {
/*
possible google bug, and or because a circle has two radii
radius_changed appears to fire twice (original and new) which is not too helpful
therefore we will check for radius changes manually and bail out if nothing has changed
*/
var newRadius, work;
newRadius = gObject.getRadius();
if (newRadius === lastRadius) {
return;
}
lastRadius = newRadius;
work = function() {
var _ref, _ref1;
if (newRadius !== scope.radius) {
scope.radius = newRadius;
}
if (((_ref = scope.events) != null ? _ref.radius_changed : void 0) && _.isFunction((_ref1 = scope.events) != null ? _ref1.radius_changed : void 0)) {
return scope.events.radius_changed(gObject, 'radius_changed', scope, arguments);
}
};
if (!angular.mock) {
return scope.$evalAsync(function() {
return work();
});
} else {
return work();
}
}));
}
if (this.listeners != null) {
this.listeners.push(google.maps.event.addListener(gObject, 'center_changed', function() {
return scope.$evalAsync(function() {
if (angular.isDefined(scope.center.type)) {
scope.center.coordinates[1] = gObject.getCenter().lat();
return scope.center.coordinates[0] = gObject.getCenter().lng();
} else {
scope.center.latitude = gObject.getCenter().lat();
return scope.center.longitude = gObject.getCenter().lng();
}
});
}));
}
scope.$on('$destroy', (function(_this) {
return function() {
clean();
return gObject.setMap(null);
};
})(this));
$log.info(this);
}
return CircleParentModel;
})(Builder);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapDrawingManagerParentModel', [
'uiGmapLogger', '$timeout', 'uiGmapBaseObject', 'uiGmapEventsHelper', function($log, $timeout, BaseObject, EventsHelper) {
var DrawingManagerParentModel;
return DrawingManagerParentModel = (function(_super) {
__extends(DrawingManagerParentModel, _super);
DrawingManagerParentModel.include(EventsHelper);
function DrawingManagerParentModel(scope, element, attrs, map) {
var gObject, listeners;
this.scope = scope;
this.attrs = attrs;
this.map = map;
gObject = new google.maps.drawing.DrawingManager(this.scope.options);
gObject.setMap(this.map);
listeners = void 0;
if (this.scope.control != null) {
this.scope.control.getDrawingManager = function() {
return gObject;
};
}
if (!this.scope["static"] && this.scope.options) {
this.scope.$watch('options', function(newValue) {
return gObject != null ? gObject.setOptions(newValue) : void 0;
}, true);
}
if (this.scope.events != null) {
listeners = this.setEvents(gObject, this.scope, this.scope);
scope.$watch('events', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
if (listeners != null) {
_this.removeEvents(listeners);
}
return listeners = _this.setEvents(gObject, _this.scope, _this.scope);
}
};
})(this));
}
scope.$on('$destroy', (function(_this) {
return function() {
if (listeners != null) {
_this.removeEvents(listeners);
}
gObject.setMap(null);
return gObject = null;
};
})(this));
}
return DrawingManagerParentModel;
})(BaseObject);
}
]);
}).call(this);
;
/*
- interface for all markers to derrive from
- to enforce a minimum set of requirements
- attributes
- coords
- icon
- implementation needed on watches
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [
"uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) {
var IMarkerParentModel;
IMarkerParentModel = (function(_super) {
__extends(IMarkerParentModel, _super);
IMarkerParentModel.prototype.DEFAULTS = {};
function IMarkerParentModel(scope, element, attrs, map) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.map = map;
this.onDestroy = __bind(this.onDestroy, this);
this.onWatch = __bind(this.onWatch, this);
this.watch = __bind(this.watch, this);
this.validateScope = __bind(this.validateScope, this);
IMarkerParentModel.__super__.constructor.call(this, this.scope);
this.$log = Logger;
if (!this.validateScope(scope)) {
throw new String("Unable to construct IMarkerParentModel due to invalid scope");
}
this.doClick = angular.isDefined(attrs.click);
if (scope.options != null) {
this.DEFAULTS = scope.options;
}
this.watch('coords', this.scope);
this.watch('icon', this.scope);
this.watch('options', this.scope);
scope.$on("$destroy", (function(_this) {
return function() {
return _this.onDestroy(scope);
};
})(this));
}
IMarkerParentModel.prototype.validateScope = function(scope) {
var ret;
if (scope == null) {
this.$log.error(this.constructor.name + ": invalid scope used");
return false;
}
ret = scope.coords != null;
if (!ret) {
this.$log.error(this.constructor.name + ": no valid coords attribute found");
return false;
}
return ret;
};
IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) {
if (equalityCheck == null) {
equalityCheck = true;
}
return scope.$watch(propNameToWatch, (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.onWatch(propNameToWatch, scope, newValue, oldValue);
}
};
})(this), equalityCheck);
};
IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {};
IMarkerParentModel.prototype.onDestroy = function(scope) {
throw new String("OnDestroy Not Implemented!!");
};
return IMarkerParentModel;
})(ModelKey);
return IMarkerParentModel;
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIWindowParentModel", [
"uiGmapModelKey", "uiGmapGmapUtil", "uiGmapLogger", function(ModelKey, GmapUtil, Logger) {
var IWindowParentModel;
return IWindowParentModel = (function(_super) {
__extends(IWindowParentModel, _super);
IWindowParentModel.include(GmapUtil);
function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) {
IWindowParentModel.__super__.constructor.call(this, scope);
this.$log = Logger;
this.$timeout = $timeout;
this.$compile = $compile;
this.$http = $http;
this.$templateCache = $templateCache;
this.DEFAULTS = {};
if (scope.options != null) {
this.DEFAULTS = scope.options;
}
}
IWindowParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {
if (modelsPropToIterate === 'models') {
return scope[modelsPropToIterate][index];
}
return scope[modelsPropToIterate].get(index);
};
return IWindowParentModel;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapLayerParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', '$timeout', function(BaseObject, Logger, $timeout) {
var LayerParentModel;
LayerParentModel = (function(_super) {
__extends(LayerParentModel, _super);
function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0;
this.$log = $log != null ? $log : Logger;
this.createGoogleLayer = __bind(this.createGoogleLayer, this);
if (this.attrs.type == null) {
this.$log.info('type attribute for the layer directive is mandatory. Layer creation aborted!!');
return;
}
this.createGoogleLayer();
this.doShow = true;
if (angular.isDefined(this.attrs.show)) {
this.doShow = this.scope.show;
}
if (this.doShow && (this.gMap != null)) {
this.gObject.setMap(this.gMap);
}
this.scope.$watch('show', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.doShow = newValue;
if (newValue) {
return _this.gObject.setMap(_this.gMap);
} else {
return _this.gObject.setMap(null);
}
}
};
})(this), true);
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.gObject.setMap(null);
_this.gObject = null;
return _this.createGoogleLayer();
}
};
})(this), true);
this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.gObject.setMap(null);
};
})(this));
}
LayerParentModel.prototype.createGoogleLayer = function() {
var _base;
if (this.attrs.options == null) {
this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type]();
} else {
this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options);
}
if ((this.gObject != null) && (this.onLayerCreated != null)) {
return typeof (_base = this.onLayerCreated(this.scope, this.gObject)) === "function" ? _base(this.gObject) : void 0;
}
};
return LayerParentModel;
})(BaseObject);
return LayerParentModel;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypeParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', function(BaseObject, Logger) {
var MapTypeParentModel;
MapTypeParentModel = (function(_super) {
__extends(MapTypeParentModel, _super);
function MapTypeParentModel(scope, element, attrs, gMap, $log) {
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.$log = $log != null ? $log : Logger;
this.hideOverlay = __bind(this.hideOverlay, this);
this.showOverlay = __bind(this.showOverlay, this);
this.refreshMapType = __bind(this.refreshMapType, this);
this.createMapType = __bind(this.createMapType, this);
if (this.attrs.options == null) {
this.$log.info('options attribute for the map-type directive is mandatory. Map type creation aborted!!');
return;
}
this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0;
this.doShow = true;
this.createMapType();
if (angular.isDefined(this.attrs.show)) {
this.doShow = this.scope.show;
}
if (this.doShow && (this.gMap != null)) {
this.showOverlay();
}
this.scope.$watch('show', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
_this.doShow = newValue;
if (newValue) {
return _this.showOverlay();
} else {
return _this.hideOverlay();
}
}
};
})(this), true);
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.refreshMapType();
}
};
})(this), true);
if (angular.isDefined(this.attrs.refresh)) {
this.scope.$watch('refresh', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
return _this.refreshMapType();
}
};
})(this), true);
}
this.scope.$on('$destroy', (function(_this) {
return function() {
_this.hideOverlay();
return _this.mapType = null;
};
})(this));
}
MapTypeParentModel.prototype.createMapType = function() {
if (this.scope.options.getTile != null) {
this.mapType = this.scope.options;
} else if (this.scope.options.getTileUrl != null) {
this.mapType = new google.maps.ImageMapType(this.scope.options);
} else {
this.$log.info('options should provide either getTile or getTileUrl methods. Map type creation aborted!!');
return;
}
if (this.attrs.id && this.scope.id) {
this.gMap.mapTypes.set(this.scope.id, this.mapType);
if (!angular.isDefined(this.attrs.show)) {
this.doShow = false;
}
}
return this.mapType.layerId = this.id;
};
MapTypeParentModel.prototype.refreshMapType = function() {
this.hideOverlay();
this.mapType = null;
this.createMapType();
if (this.doShow && (this.gMap != null)) {
return this.showOverlay();
}
};
MapTypeParentModel.prototype.showOverlay = function() {
return this.gMap.overlayMapTypes.push(this.mapType);
};
MapTypeParentModel.prototype.hideOverlay = function() {
var found;
found = false;
return this.gMap.overlayMapTypes.forEach((function(_this) {
return function(mapType, index) {
if (!found && mapType.layerId === _this.id) {
found = true;
_this.gMap.overlayMapTypes.removeAt(index);
}
};
})(this));
};
return MapTypeParentModel;
})(BaseObject);
return MapTypeParentModel;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [
"uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", "uiGmapLogger", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil, $log) {
var MarkersParentModel;
MarkersParentModel = (function(_super) {
__extends(MarkersParentModel, _super);
MarkersParentModel.include(GmapUtil);
MarkersParentModel.include(ModelsWatcher);
function MarkersParentModel(scope, element, attrs, map) {
this.onDestroy = __bind(this.onDestroy, this);
this.newChildMarker = __bind(this.newChildMarker, this);
this.pieceMeal = __bind(this.pieceMeal, this);
this.rebuildAll = __bind(this.rebuildAll, this);
this.createAllNew = __bind(this.createAllNew, this);
this.createChildScopes = __bind(this.createChildScopes, this);
this.validateScope = __bind(this.validateScope, this);
this.onWatch = __bind(this.onWatch, this);
var self;
MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map);
this["interface"] = IMarker;
self = this;
this.plurals = new PropMap();
this.scope.plurals = this.plurals;
this.scope.pluralsUpdate = {
updateCtr: 0
};
this.$log.info(this);
this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;
this.setIdKey(scope);
this.scope.$watch('doRebuildAll', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.doRebuildAll = newValue;
}
};
})(this));
if ((scope.models == null) || scope.models.length === 0) {
this.modelsRendered = false;
}
this.scope.$watch('models', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue) || !_this.modelsRendered) {
if (newValue.length === 0 && oldValue.length === 0) {
return;
}
_this.modelsRendered = true;
return _this.onWatch('models', scope, newValue, oldValue);
}
};
})(this), !this.isTrue(attrs.modelsbyref));
this.watch('doCluster', scope);
this.watch('clusterOptions', scope);
this.watch('clusterEvents', scope);
this.watch('fit', scope);
this.watch('idKey', scope);
this.gManager = void 0;
this.createAllNew(scope);
}
MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {
if (propNameToWatch === "idKey" && newValue !== oldValue) {
this.idKey = newValue;
}
if (this.doRebuildAll || propNameToWatch === 'doCluster') {
return this.rebuildAll(scope);
} else {
return this.pieceMeal(scope);
}
};
MarkersParentModel.prototype.validateScope = function(scope) {
var modelsNotDefined;
modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0;
if (modelsNotDefined) {
this.$log.error(this.constructor.name + ": no valid models attribute found");
}
return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined;
};
/*
Not used internally by this parent
created for consistency for external control in the API
*/
MarkersParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if ((this.gMap == null) || (this.scope.models == null)) {
return;
}
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
};
MarkersParentModel.prototype.createAllNew = function(scope) {
var maybeCanceled, self, _ref, _ref1, _ref2;
if (this.gManager != null) {
this.gManager.clear();
delete this.gManager;
}
if (scope.doCluster) {
if (scope.clusterEvents) {
self = this;
if (!this.origClusterEvents) {
this.origClusterEvents = {
click: (_ref = scope.clusterEvents) != null ? _ref.click : void 0,
mouseout: (_ref1 = scope.clusterEvents) != null ? _ref1.mouseout : void 0,
mouseover: (_ref2 = scope.clusterEvents) != null ? _ref2.mouseover : void 0
};
} else {
angular.extend(scope.clusterEvents, this.origClusterEvents);
}
angular.extend(scope.clusterEvents, {
click: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'click');
},
mouseout: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'mouseout');
},
mouseover: function(cluster) {
return self.maybeExecMappedEvent(cluster, 'mouseover');
}
});
}
this.gManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, scope.clusterEvents);
} else {
this.gManager = new MarkerManager(this.map);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
_this.newChildMarker(model, scope);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
_this.modelsRendered = true;
if (scope.fit) {
_this.gManager.fit();
}
_this.gManager.draw();
return _this.scope.pluralsUpdate.updateCtr += 1;
}, _async.chunkSizeFrom(scope.chunk));
};
})(this));
};
MarkersParentModel.prototype.rebuildAll = function(scope) {
var _ref;
if (!scope.doRebuild && scope.doRebuild !== void 0) {
return;
}
if ((_ref = this.scope.plurals) != null ? _ref.length : void 0) {
return this.onDestroy(scope).then((function(_this) {
return function() {
return _this.createAllNew(scope);
};
})(this));
} else {
return this.createAllNew(scope);
}
};
MarkersParentModel.prototype.pieceMeal = function(scope) {
var maybeCanceled, payload;
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
if ((this.scope.models != null) && this.scope.models.length > 0 && this.scope.plurals.length > 0) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise((function() {
return _this.figureOutState(_this.idKey, scope, _this.scope.plurals, _this.modelKeyComparison);
})).then(function(state) {
payload = state;
return _async.each(payload.removals, function(child) {
if (child != null) {
if (child.destroy != null) {
child.destroy();
}
_this.scope.plurals.remove(child.id);
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
_this.newChildMarker(modelToAdd, scope);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.updates, function(update) {
_this.updateChild(update.child, update.model);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) {
scope.plurals = _this.scope.plurals;
if (scope.fit) {
_this.gManager.fit();
}
_this.gManager.draw();
}
return _this.scope.pluralsUpdate.updateCtr += 1;
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(scope);
}
};
MarkersParentModel.prototype.newChildMarker = function(model, scope) {
var child, childScope, doDrawSelf, keys;
if (model[this.idKey] == null) {
this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.");
return;
}
this.$log.info('child', child, 'markers', this.scope.plurals);
childScope = scope.$new(true);
childScope.events = scope.events;
keys = {};
IMarker.scopeKeys.forEach(function(k) {
return keys[k] = scope[k];
});
child = new MarkerChildModel(childScope, model, keys, this.map, this.DEFAULTS, this.doClick, this.gManager, doDrawSelf = false);
this.scope.plurals.put(model[this.idKey], child);
return child;
};
MarkersParentModel.prototype.onDestroy = function(scope) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.scope.plurals.values(), function(model) {
if (model != null) {
return model.destroy(false);
}
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
delete _this.scope.plurals;
if (_this.gManager != null) {
_this.gManager.clear();
}
_this.scope.plurals = new PropMap();
return _this.scope.pluralsUpdate.updateCtr += 1;
});
};
})(this));
};
MarkersParentModel.prototype.maybeExecMappedEvent = function(cluster, fnName) {
var pair, _ref;
if (_.isFunction((_ref = this.scope.clusterEvents) != null ? _ref[fnName] : void 0)) {
pair = this.mapClusterToPlurals(cluster);
if (this.origClusterEvents[fnName]) {
return this.origClusterEvents[fnName](pair.cluster, pair.mapped);
}
}
};
MarkersParentModel.prototype.mapClusterToPlurals = function(cluster) {
var mapped;
mapped = cluster.getMarkers().map((function(_this) {
return function(g) {
return _this.scope.plurals.get(g.key).model;
};
})(this));
return {
cluster: cluster,
mapped: mapped
};
};
MarkersParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) {
if (modelsPropToIterate === 'models') {
return scope[modelsPropToIterate][index];
}
return scope[modelsPropToIterate].get(index);
};
return MarkersParentModel;
})(IMarkerParentModel);
return MarkersParentModel;
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapPolygonsParentModel', [
'$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapPolygonChildModel', 'uiGmap_async', 'uiGmapPromise', 'uiGmapIPolygon', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, PolygonChildModel, _async, uiGmapPromise, IPolygon) {
var PolygonsParentModel;
return PolygonsParentModel = (function(_super) {
__extends(PolygonsParentModel, _super);
PolygonsParentModel.include(ModelsWatcher);
function PolygonsParentModel(scope, element, attrs, gMap, defaults) {
var self;
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.defaults = defaults;
this.createChild = __bind(this.createChild, this);
this.pieceMeal = __bind(this.pieceMeal, this);
this.createAllNew = __bind(this.createAllNew, this);
this.watchIdKey = __bind(this.watchIdKey, this);
this.createChildScopes = __bind(this.createChildScopes, this);
this.watchOurScope = __bind(this.watchOurScope, this);
this.watchDestroy = __bind(this.watchDestroy, this);
this.onDestroy = __bind(this.onDestroy, this);
this.rebuildAll = __bind(this.rebuildAll, this);
this.doINeedToWipe = __bind(this.doINeedToWipe, this);
this.watchModels = __bind(this.watchModels, this);
this.watch = __bind(this.watch, this);
PolygonsParentModel.__super__.constructor.call(this, scope);
this["interface"] = IPolygon;
self = this;
this.$log = $log;
this.plurals = new PropMap();
_.each(IPolygon.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.models = void 0;
this.firstTime = true;
this.$log.info(this);
this.watchOurScope(scope);
this.createChildScopes();
}
PolygonsParentModel.prototype.watch = function(scope, name, nameKey) {
return scope.$watch(name, (function(_this) {
return function(newValue, oldValue) {
var maybeCanceled;
if (newValue !== oldValue) {
maybeCanceled = null;
_this[nameKey] = _.isFunction(newValue) ? newValue() : newValue;
return _async.promiseLock(_this, uiGmapPromise.promiseTypes.update, "watch " + name + " " + nameKey, (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), function() {
return _async.each(_this.plurals.values(), function(model) {
model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]];
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
});
}
};
})(this));
};
PolygonsParentModel.prototype.watchModels = function(scope) {
return scope.$watchCollection('models', (function(_this) {
return function(newValue, oldValue) {
if (!(_.isEqual(newValue, oldValue) && (_this.lastNewValue !== newValue || _this.lastOldValue !== oldValue))) {
_this.lastNewValue = newValue;
_this.lastOldValue = oldValue;
if (_this.doINeedToWipe(newValue)) {
return _this.rebuildAll(scope, true, true);
} else {
return _this.createChildScopes(false);
}
}
};
})(this));
};
PolygonsParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
PolygonsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
PolygonsParentModel.prototype.onDestroy = function(doDelete) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy(true);
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
if (doDelete) {
delete _this.plurals;
}
return _this.plurals = new PropMap();
});
};
})(this));
};
PolygonsParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
return _this.rebuildAll(scope, false, true);
};
})(this));
};
PolygonsParentModel.prototype.watchOurScope = function(scope) {
return _.each(IPolygon.scopeKeys, (function(_this) {
return function(name) {
var nameKey;
nameKey = name + 'Key';
_this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name];
return _this.watch(scope, name, nameKey);
};
})(this));
};
PolygonsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
if (angular.isUndefined(this.scope.models)) {
this.$log.error('No models to create Polygons from! I Need direct models!');
return;
}
if ((this.gMap == null) || (this.scope.models == null)) {
return;
}
this.watchIdKey(this.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
};
PolygonsParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
PolygonsParentModel.prototype.createAllNew = function(scope, isArray) {
var maybeCanceled;
if (isArray == null) {
isArray = false;
}
this.models = scope.models;
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
var child;
child = _this.createChild(model, _this.gMap);
if (maybeCanceled) {
$log.debug('createNew should fall through safely');
child.isEnabled = false;
}
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
PolygonsParentModel.prototype.pieceMeal = function(scope, isArray) {
var maybeCanceled, payload;
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
this.models = scope.models;
if ((scope != null) && (scope.models != null) && scope.models.length > 0 && this.plurals.length > 0) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise(function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
}).then(function(state) {
payload = state;
return _async.each(payload.removals, function(id) {
var child;
child = _this.plurals.get(id);
if (child != null) {
child.destroy();
_this.plurals.remove(id);
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
if (maybeCanceled) {
$log.debug('pieceMeal should fall through safely');
}
_this.createChild(modelToAdd, _this.gMap);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(this.scope, true, true);
}
};
PolygonsParentModel.prototype.createChild = function(model, gMap) {
var child, childScope;
childScope = this.scope.$new(false);
this.setChildScope(IPolygon.scopeKeys, childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
childScope["static"] = this.scope["static"];
child = new PolygonChildModel(childScope, this.attrs, gMap, this.defaults, model);
if (model[this.idKey] == null) {
this.$log.error("Polygon model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key.");
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
return PolygonsParentModel;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapPolylinesParentModel', [
'$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapPolylineChildModel', 'uiGmap_async', 'uiGmapPromise', 'uiGmapIPolyline', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, PolylineChildModel, _async, uiGmapPromise, IPolyline) {
var PolylinesParentModel;
return PolylinesParentModel = (function(_super) {
__extends(PolylinesParentModel, _super);
PolylinesParentModel.include(ModelsWatcher);
function PolylinesParentModel(scope, element, attrs, gMap, defaults) {
var self;
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.defaults = defaults;
this.setChildScope = __bind(this.setChildScope, this);
this.createChild = __bind(this.createChild, this);
this.pieceMeal = __bind(this.pieceMeal, this);
this.createAllNew = __bind(this.createAllNew, this);
this.watchIdKey = __bind(this.watchIdKey, this);
this.createChildScopes = __bind(this.createChildScopes, this);
this.watchOurScope = __bind(this.watchOurScope, this);
this.watchDestroy = __bind(this.watchDestroy, this);
this.onDestroy = __bind(this.onDestroy, this);
this.rebuildAll = __bind(this.rebuildAll, this);
this.doINeedToWipe = __bind(this.doINeedToWipe, this);
this.watchModels = __bind(this.watchModels, this);
this.watch = __bind(this.watch, this);
PolylinesParentModel.__super__.constructor.call(this, scope);
this["interface"] = IPolyline;
self = this;
this.$log = $log;
this.plurals = new PropMap();
_.each(IPolyline.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.models = void 0;
this.firstTime = true;
this.$log.info(this);
this.watchOurScope(scope);
this.createChildScopes();
}
PolylinesParentModel.prototype.watch = function(scope, name, nameKey) {
return scope.$watch(name, (function(_this) {
return function(newValue, oldValue) {
var maybeCanceled;
if (newValue !== oldValue) {
maybeCanceled = null;
_this[nameKey] = _.isFunction(newValue) ? newValue() : newValue;
return _async.promiseLock(_this, uiGmapPromise.promiseTypes.update, "watch " + name + " " + nameKey, (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), function() {
return _async.each(_this.plurals.values(), function(model) {
model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]];
return maybeCanceled;
}, false);
});
}
};
})(this));
};
PolylinesParentModel.prototype.watchModels = function(scope) {
return scope.$watchCollection('models', (function(_this) {
return function(newValue, oldValue) {
if (!(_.isEqual(newValue, oldValue) && (_this.lastNewValue !== newValue || _this.lastOldValue !== oldValue))) {
_this.lastNewValue = newValue;
_this.lastOldValue = oldValue;
if (_this.doINeedToWipe(newValue)) {
return _this.rebuildAll(scope, true, true);
} else {
return _this.createChildScopes(false);
}
}
};
})(this));
};
PolylinesParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
PolylinesParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
PolylinesParentModel.prototype.onDestroy = function(doDelete) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy(true);
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
if (doDelete) {
delete _this.plurals;
}
return _this.plurals = new PropMap();
});
};
})(this));
};
PolylinesParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
return _this.rebuildAll(scope, false, true);
};
})(this));
};
PolylinesParentModel.prototype.watchOurScope = function(scope) {
return _.each(IPolyline.scopeKeys, (function(_this) {
return function(name) {
var nameKey;
nameKey = name + 'Key';
_this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name];
return _this.watch(scope, name, nameKey);
};
})(this));
};
PolylinesParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
if (angular.isUndefined(this.scope.models)) {
this.$log.error('No models to create Polylines from! I Need direct models!');
return;
}
if (this.gMap != null) {
if (this.scope.models != null) {
this.watchIdKey(this.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.scope, false);
} else {
return this.pieceMeal(this.scope, false);
}
}
}
};
PolylinesParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
PolylinesParentModel.prototype.createAllNew = function(scope, isArray) {
var maybeCanceled;
if (isArray == null) {
isArray = false;
}
this.models = scope.models;
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
_this.createChild(model, _this.gMap);
if (maybeCanceled) {
$log.debug('createNew should fall through safely');
}
return maybeCanceled;
}).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
PolylinesParentModel.prototype.pieceMeal = function(scope, isArray) {
var maybeCanceled, payload;
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
this.models = scope.models;
if ((scope != null) && (scope.models != null) && scope.models.length > 0 && this.plurals.length > 0) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise(function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
}).then(function(state) {
payload = state;
return _async.each(payload.removals, function(id) {
var child;
child = _this.plurals.get(id);
if (child != null) {
child.destroy();
_this.plurals.remove(id);
return maybeCanceled;
}
});
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
if (maybeCanceled) {
$log.debug('pieceMeal should fall through safely');
}
_this.createChild(modelToAdd, _this.gMap);
return maybeCanceled;
});
});
};
})(this));
} else {
this.inProgress = false;
return this.rebuildAll(this.scope, true, true);
}
};
PolylinesParentModel.prototype.createChild = function(model, gMap) {
var child, childScope;
childScope = this.scope.$new(false);
this.setChildScope(childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
childScope["static"] = this.scope["static"];
child = new PolylineChildModel(childScope, this.attrs, gMap, this.defaults, model);
if (model[this.idKey] == null) {
this.$log.error("Polyline model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key.");
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
PolylinesParentModel.prototype.setChildScope = function(childScope, model) {
IPolyline.scopeKeys.forEach((function(_this) {
return function(name) {
var nameKey, newValue;
nameKey = name + 'Key';
newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]];
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
};
})(this));
return childScope.model = model;
};
return PolylinesParentModel;
})(ModelKey);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapRectangleParentModel', [
'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapRectangleOptionsBuilder', function($log, GmapUtil, EventsHelper, Builder) {
var RectangleParentModel;
return RectangleParentModel = (function(_super) {
__extends(RectangleParentModel, _super);
RectangleParentModel.include(GmapUtil);
RectangleParentModel.include(EventsHelper);
function RectangleParentModel(scope, element, attrs, map, DEFAULTS) {
var bounds, clear, createBounds, dragging, fit, gObject, init, listeners, myListeners, settingBoundsFromScope, updateBounds;
this.scope = scope;
this.attrs = attrs;
this.map = map;
this.DEFAULTS = DEFAULTS;
bounds = void 0;
dragging = false;
myListeners = [];
listeners = void 0;
fit = (function(_this) {
return function() {
if (_this.isTrue(attrs.fit)) {
return _this.fitMapBounds(_this.map, bounds);
}
};
})(this);
createBounds = (function(_this) {
return function() {
var _ref, _ref1;
if ((scope.bounds != null) && (((_ref = scope.bounds) != null ? _ref.sw : void 0) != null) && (((_ref1 = scope.bounds) != null ? _ref1.ne : void 0) != null) && _this.validateBoundPoints(scope.bounds)) {
bounds = _this.convertBoundPoints(scope.bounds);
return $log.info("new new bounds created: " + rectangle);
} else if ((scope.bounds.getNorthEast != null) && (scope.bounds.getSouthWest != null)) {
return bounds = scope.bounds;
} else {
if (scope.bounds != null) {
return $log.error("Invalid bounds for newValue: " + (JSON.stringify(scope.bounds)));
}
}
};
})(this);
createBounds();
gObject = new google.maps.Rectangle(this.buildOpts(bounds));
$log.info("gObject (rectangle) created: " + gObject);
settingBoundsFromScope = false;
updateBounds = (function(_this) {
return function() {
var b, ne, sw;
b = gObject.getBounds();
ne = b.getNorthEast();
sw = b.getSouthWest();
if (settingBoundsFromScope) {
return;
}
return scope.$evalAsync(function(s) {
if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) {
s.bounds.ne = {
latitude: ne.lat(),
longitude: ne.lng()
};
s.bounds.sw = {
latitude: sw.lat(),
longitude: sw.lng()
};
}
if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) {
return s.bounds = b;
}
});
};
})(this);
init = (function(_this) {
return function() {
fit();
_this.removeEvents(myListeners);
myListeners.push(google.maps.event.addListener(gObject, 'dragstart', function() {
return dragging = true;
}));
myListeners.push(google.maps.event.addListener(gObject, 'dragend', function() {
dragging = false;
return updateBounds();
}));
return myListeners.push(google.maps.event.addListener(gObject, 'bounds_changed', function() {
if (dragging) {
return;
}
return updateBounds();
}));
};
})(this);
clear = (function(_this) {
return function() {
_this.removeEvents(myListeners);
if (listeners != null) {
_this.removeEvents(listeners);
}
return gObject.setMap(null);
};
})(this);
if (bounds != null) {
init();
}
scope.$watch('bounds', (function(newValue, oldValue) {
var isNew;
if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) {
return;
}
settingBoundsFromScope = true;
if (newValue == null) {
clear();
return;
}
if (bounds == null) {
isNew = true;
} else {
fit();
}
createBounds();
gObject.setBounds(bounds);
settingBoundsFromScope = false;
if (isNew && (bounds != null)) {
return init();
}
}), true);
this.setMyOptions = (function(_this) {
return function(newVals, oldVals) {
if (!_.isEqual(newVals, oldVals)) {
if ((bounds != null) && (newVals != null)) {
return gObject.setOptions(_this.buildOpts(bounds));
}
}
};
})(this);
this.props.push('bounds');
this.watchProps(this.props);
if (attrs.events != null) {
listeners = this.setEvents(gObject, scope, scope);
scope.$watch('events', (function(_this) {
return function(newValue, oldValue) {
if (!_.isEqual(newValue, oldValue)) {
if (listeners != null) {
_this.removeEvents(listeners);
}
return listeners = _this.setEvents(gObject, scope, scope);
}
};
})(this));
}
scope.$on('$destroy', (function(_this) {
return function() {
return clear();
};
})(this));
$log.info(this);
}
return RectangleParentModel;
})(Builder);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapSearchBoxParentModel', [
'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapEventsHelper', '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) {
var SearchBoxParentModel;
SearchBoxParentModel = (function(_super) {
__extends(SearchBoxParentModel, _super);
SearchBoxParentModel.include(EventsHelper);
function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) {
var controlDiv;
this.scope = scope;
this.element = element;
this.attrs = attrs;
this.gMap = gMap;
this.ctrlPosition = ctrlPosition;
this.template = template;
this.$log = $log != null ? $log : Logger;
this.setVisibility = __bind(this.setVisibility, this);
this.getBounds = __bind(this.getBounds, this);
this.setBounds = __bind(this.setBounds, this);
this.createSearchBox = __bind(this.createSearchBox, this);
this.addToParentDiv = __bind(this.addToParentDiv, this);
this.addAsMapControl = __bind(this.addAsMapControl, this);
this.init = __bind(this.init, this);
if (this.attrs.template == null) {
this.$log.error('template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!');
return;
}
if (angular.isUndefined(this.scope.options)) {
this.scope.options = {};
this.scope.options.visible = true;
}
if (angular.isUndefined(this.scope.options.visible)) {
this.scope.options.visible = true;
}
if (angular.isUndefined(this.scope.options.autocomplete)) {
this.scope.options.autocomplete = false;
}
this.visible = scope.options.visible;
this.autocomplete = scope.options.autocomplete;
controlDiv = angular.element('<div></div>');
controlDiv.append(this.template);
this.input = controlDiv.find('input')[0];
this.init();
}
SearchBoxParentModel.prototype.init = function() {
this.createSearchBox();
this.scope.$watch('options', (function(_this) {
return function(newValue, oldValue) {
if (angular.isObject(newValue)) {
if (newValue.bounds != null) {
_this.setBounds(newValue.bounds);
}
if (newValue.visible != null) {
if (_this.visible !== newValue.visible) {
return _this.setVisibility(newValue.visible);
}
}
}
};
})(this), true);
if (this.attrs.parentdiv != null) {
this.addToParentDiv();
} else {
this.addAsMapControl();
}
if (this.autocomplete) {
this.listener = google.maps.event.addListener(this.gObject, 'place_changed', (function(_this) {
return function() {
return _this.places = _this.gObject.getPlace();
};
})(this));
} else {
this.listener = google.maps.event.addListener(this.gObject, 'places_changed', (function(_this) {
return function() {
return _this.places = _this.gObject.getPlaces();
};
})(this));
}
this.listeners = this.setEvents(this.gObject, this.scope, this.scope);
this.$log.info(this);
return this.scope.$on('$destroy', (function(_this) {
return function() {
return _this.gObject = null;
};
})(this));
};
SearchBoxParentModel.prototype.addAsMapControl = function() {
return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);
};
SearchBoxParentModel.prototype.addToParentDiv = function() {
this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv));
return this.parentDiv.append(this.input);
};
SearchBoxParentModel.prototype.createSearchBox = function() {
if (this.autocomplete) {
return this.gObject = new google.maps.places.Autocomplete(this.input, this.scope.options);
} else {
return this.gObject = new google.maps.places.SearchBox(this.input, this.scope.options);
}
};
SearchBoxParentModel.prototype.setBounds = function(bounds) {
if (angular.isUndefined(bounds.isEmpty)) {
this.$log.error('Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds.');
} else {
if (bounds.isEmpty() === false) {
if (this.gObject != null) {
return this.gObject.setBounds(bounds);
}
}
}
};
SearchBoxParentModel.prototype.getBounds = function() {
return this.gObject.getBounds();
};
SearchBoxParentModel.prototype.setVisibility = function(val) {
if (this.attrs.parentdiv != null) {
if (val === false) {
this.parentDiv.addClass("ng-hide");
} else {
this.parentDiv.removeClass("ng-hide");
}
} else {
if (val === false) {
this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].clear();
} else {
this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input);
}
}
return this.visible = val;
};
return SearchBoxParentModel;
})(BaseObject);
return SearchBoxParentModel;
}
]);
}).call(this);
;
/*
WindowsChildModel generator where there are many ChildModels to a parent.
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapWindowsParentModel', [
'uiGmapIWindowParentModel', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapWindowChildModel', 'uiGmapLinked', 'uiGmap_async', 'uiGmapLogger', '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', 'uiGmapIWindow', 'uiGmapGmapUtil', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise, IWindow, GmapUtil) {
var WindowsParentModel;
WindowsParentModel = (function(_super) {
__extends(WindowsParentModel, _super);
WindowsParentModel.include(ModelsWatcher);
function WindowsParentModel(scope, element, attrs, ctrls, gMap, markersScope) {
this.gMap = gMap;
this.markersScope = markersScope;
this.modelKeyComparison = __bind(this.modelKeyComparison, this);
this.interpolateContent = __bind(this.interpolateContent, this);
this.setChildScope = __bind(this.setChildScope, this);
this.createWindow = __bind(this.createWindow, this);
this.setContentKeys = __bind(this.setContentKeys, this);
this.pieceMeal = __bind(this.pieceMeal, this);
this.createAllNew = __bind(this.createAllNew, this);
this.watchIdKey = __bind(this.watchIdKey, this);
this.createChildScopes = __bind(this.createChildScopes, this);
this.watchOurScope = __bind(this.watchOurScope, this);
this.watchDestroy = __bind(this.watchDestroy, this);
this.onDestroy = __bind(this.onDestroy, this);
this.rebuildAll = __bind(this.rebuildAll, this);
this.doINeedToWipe = __bind(this.doINeedToWipe, this);
this.watchModels = __bind(this.watchModels, this);
this.go = __bind(this.go, this);
WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache);
this["interface"] = IWindow;
this.plurals = new PropMap();
_.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
return _this[name + 'Key'] = void 0;
};
})(this));
this.linked = new Linked(scope, element, attrs, ctrls);
this.models = void 0;
this.contentKeys = void 0;
this.isIconVisibleOnClick = void 0;
this.firstTime = true;
this.firstWatchModels = true;
this.$log.info(self);
this.parentScope = void 0;
this.go(scope);
}
WindowsParentModel.prototype.go = function(scope) {
this.watchOurScope(scope);
this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false;
scope.$watch('doRebuildAll', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.doRebuildAll = newValue;
}
};
})(this));
return this.createChildScopes();
};
WindowsParentModel.prototype.watchModels = function(scope) {
var itemToWatch;
itemToWatch = this.markersScope != null ? 'pluralsUpdate' : 'models';
return scope.$watch(itemToWatch, (function(_this) {
return function(newValue, oldValue) {
var doScratch;
if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) {
_this.firstWatchModels = false;
if (_this.doRebuildAll || _this.doINeedToWipe(scope.models)) {
return _this.rebuildAll(scope, true, true);
} else {
doScratch = _this.plurals.length === 0;
if (_this.existingPieces != null) {
return _.last(_this.existingPieces._content).then(function() {
return _this.createChildScopes(doScratch);
});
} else {
return _this.createChildScopes(doScratch);
}
}
}
};
})(this), true);
};
WindowsParentModel.prototype.doINeedToWipe = function(newValue) {
var newValueIsEmpty;
newValueIsEmpty = newValue != null ? newValue.length === 0 : true;
return this.plurals.length > 0 && newValueIsEmpty;
};
WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) {
return this.onDestroy(doDelete).then((function(_this) {
return function() {
if (doCreate) {
return _this.createChildScopes();
}
};
})(this));
};
WindowsParentModel.prototype.onDestroy = function(doDelete) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) {
return function() {
return _async.each(_this.plurals.values(), function(child) {
return child.destroy();
}, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() {
if (doDelete) {
delete _this.plurals;
}
return _this.plurals = new PropMap();
});
};
})(this));
};
WindowsParentModel.prototype.watchDestroy = function(scope) {
return scope.$on('$destroy', (function(_this) {
return function() {
_this.firstWatchModels = true;
_this.firstTime = true;
return _this.rebuildAll(scope, false, true);
};
})(this));
};
WindowsParentModel.prototype.watchOurScope = function(scope) {
return _.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
var nameKey;
nameKey = name + 'Key';
return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name];
};
})(this));
};
WindowsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) {
var modelsNotDefined, _ref, _ref1;
if (isCreatingFromScratch == null) {
isCreatingFromScratch = true;
}
/*
being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl)
we will assume that all scope values are string expressions either pointing to a key (propName) or using
'self' to point the model as container/object of interest.
This may force redundant information into the model, but this appears to be the most flexible approach.
*/
this.isIconVisibleOnClick = true;
if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) {
this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick;
}
modelsNotDefined = angular.isUndefined(this.linked.scope.models);
if (modelsNotDefined && (this.markersScope === void 0 || (((_ref = this.markersScope) != null ? _ref.plurals : void 0) === void 0 || ((_ref1 = this.markersScope) != null ? _ref1.models : void 0) === void 0))) {
this.$log.error('No models to create windows from! Need direct models or models derived from markers!');
return;
}
if (this.gMap != null) {
if (this.linked.scope.models != null) {
this.watchIdKey(this.linked.scope);
if (isCreatingFromScratch) {
return this.createAllNew(this.linked.scope, false);
} else {
return this.pieceMeal(this.linked.scope, false);
}
} else {
this.parentScope = this.markersScope;
this.watchIdKey(this.parentScope);
if (isCreatingFromScratch) {
return this.createAllNew(this.markersScope, true, 'plurals', false);
} else {
return this.pieceMeal(this.markersScope, true, 'plurals', false);
}
}
}
};
WindowsParentModel.prototype.watchIdKey = function(scope) {
this.setIdKey(scope);
return scope.$watch('idKey', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue && (newValue == null)) {
_this.idKey = newValue;
return _this.rebuildAll(scope, true, true);
}
};
})(this));
};
WindowsParentModel.prototype.createAllNew = function(scope, hasGMarker, modelsPropToIterate, isArray) {
var maybeCanceled;
if (modelsPropToIterate == null) {
modelsPropToIterate = 'models';
}
if (isArray == null) {
isArray = false;
}
this.models = scope.models;
if (this.firstTime) {
this.watchModels(scope);
this.watchDestroy(scope);
}
this.setContentKeys(scope.models);
if (this.didQueueInitPromise(this, scope)) {
return;
}
maybeCanceled = null;
return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return _async.each(scope.models, function(model) {
var gMarker, _ref;
gMarker = hasGMarker ? (_ref = _this.getItem(scope, modelsPropToIterate, model[_this.idKey])) != null ? _ref.gObject : void 0 : void 0;
if (!maybeCanceled) {
if (!gMarker && _this.markersScope) {
$log.error('Unable to get gMarker from markersScope!');
}
_this.createWindow(model, gMarker, _this.gMap);
}
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk)).then(function() {
return _this.firstTime = false;
});
};
})(this));
};
WindowsParentModel.prototype.pieceMeal = function(scope, hasGMarker, modelsPropToIterate, isArray) {
var maybeCanceled, payload;
if (modelsPropToIterate == null) {
modelsPropToIterate = 'models';
}
if (isArray == null) {
isArray = true;
}
if (scope.$$destroyed) {
return;
}
maybeCanceled = null;
payload = null;
this.models = scope.models;
if ((scope != null) && (scope.models != null) && scope.models.length > 0 && this.plurals.length > 0) {
return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) {
return maybeCanceled = canceledMsg;
}), (function(_this) {
return function() {
return uiGmapPromise.promise((function() {
return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison);
})).then(function(state) {
payload = state;
return _async.each(payload.removals, function(child) {
if (child != null) {
_this.plurals.remove(child.id);
if (child.destroy != null) {
child.destroy(true);
}
return maybeCanceled;
}
}, _async.chunkSizeFrom(scope.chunk));
}).then(function() {
return _async.each(payload.adds, function(modelToAdd) {
var gMarker, _ref;
gMarker = (_ref = _this.getItem(scope, modelsPropToIterate, modelToAdd[_this.idKey])) != null ? _ref.gObject : void 0;
if (!gMarker) {
throw 'Gmarker undefined';
}
_this.createWindow(modelToAdd, gMarker, _this.gMap);
return maybeCanceled;
});
}).then(function() {
return _async.each(payload.updates, function(update) {
_this.updateChild(update.child, update.model);
return maybeCanceled;
}, _async.chunkSizeFrom(scope.chunk));
});
};
})(this));
} else {
$log.debug('pieceMeal: rebuildAll');
return this.rebuildAll(this.scope, true, true);
}
};
WindowsParentModel.prototype.setContentKeys = function(models) {
if (models.length > 0) {
return this.contentKeys = Object.keys(models[0]);
}
};
WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) {
var child, childScope, fakeElement, opts, _ref, _ref1;
childScope = this.linked.scope.$new(false);
this.setChildScope(childScope, model);
childScope.$watch('model', (function(_this) {
return function(newValue, oldValue) {
if (newValue !== oldValue) {
return _this.setChildScope(childScope, newValue);
}
};
})(this), true);
fakeElement = {
html: (function(_this) {
return function() {
return _this.interpolateContent(_this.linked.element.html(), model);
};
})(this)
};
this.DEFAULTS = this.scopeOrModelVal(this.optionsKey, this.scope, model) || {};
opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS);
child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, (_ref = this.markersScope) != null ? (_ref1 = _ref.plurals.get(model[this.idKey])) != null ? _ref1.scope : void 0 : void 0, fakeElement, false, true);
if (model[this.idKey] == null) {
this.$log.error('Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.');
return;
}
this.plurals.put(model[this.idKey], child);
return child;
};
WindowsParentModel.prototype.setChildScope = function(childScope, model) {
_.each(IWindow.scopeKeys, (function(_this) {
return function(name) {
var nameKey, newValue;
nameKey = name + 'Key';
newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]];
if (newValue !== childScope[name]) {
return childScope[name] = newValue;
}
};
})(this));
return childScope.model = model;
};
WindowsParentModel.prototype.interpolateContent = function(content, model) {
var exp, interpModel, key, _i, _len, _ref;
if (this.contentKeys === void 0 || this.contentKeys.length === 0) {
return;
}
exp = $interpolate(content);
interpModel = {};
_ref = this.contentKeys;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
interpModel[key] = model[key];
}
return exp(interpModel);
};
WindowsParentModel.prototype.modelKeyComparison = function(model1, model2) {
var isEqual, scope;
scope = this.scope.coords != null ? this.scope : this.parentScope;
if (scope == null) {
throw 'No scope or parentScope set!';
}
isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords));
if (!isEqual) {
return isEqual;
}
isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) {
return function(k) {
return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]);
};
})(this));
return isEqual;
};
return WindowsParentModel;
})(IWindowParentModel);
return WindowsParentModel;
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapCircle", [
"uiGmapICircle", "uiGmapCircleParentModel", function(ICircle, CircleParentModel) {
return _.extend(ICircle, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new CircleParentModel(scope, element, attrs, map);
};
})(this));
}
});
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [
"uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) {
var Control;
return Control = (function(_super) {
__extends(Control, _super);
function Control() {
this.link = __bind(this.link, this);
Control.__super__.constructor.call(this);
}
Control.prototype.link = function(scope, element, attrs, ctrl) {
return GoogleMapApi.then((function(_this) {
return function(maps) {
var index, position;
if (angular.isUndefined(scope.template)) {
_this.$log.error('mapControl: could not find a valid template property');
return;
}
index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0;
position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER';
if (!maps.ControlPosition[position]) {
_this.$log.error('mapControl: invalid position property');
return;
}
return IControl.mapPromise(scope, ctrl).then(function(map) {
var control, controlDiv;
control = void 0;
controlDiv = angular.element('<div></div>');
return $http.get(scope.template, {
cache: $templateCache
}).success(function(template) {
var templateCtrl, templateScope;
templateScope = scope.$new();
controlDiv.append(template);
if (angular.isDefined(scope.controller)) {
templateCtrl = $controller(scope.controller, {
$scope: templateScope
});
controlDiv.children().data('$ngControllerController', templateCtrl);
}
control = $compile(controlDiv.children())(templateScope);
if (index) {
return control[0].index = index;
}
}).error(function(error) {
return _this.$log.error('mapControl: template could not be found');
}).then(function() {
return map.controls[google.maps.ControlPosition[position]].push(control[0]);
});
});
};
})(this));
};
return Control;
})(IControl);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapDragZoom', [
'uiGmapCtrlHandle', 'uiGmapPropertyAction', function(CtrlHandle, PropertyAction) {
return {
restrict: 'EMA',
transclude: true,
template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>',
require: '^' + 'uiGmapGoogleMap',
scope: {
keyboardkey: '=',
options: '=',
spec: '='
},
controller: [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'uiGmapDragZoom';
return _.extend(this, CtrlHandle.handle($scope, $element));
}
],
link: function(scope, element, attrs, ctrl) {
return CtrlHandle.mapPromise(scope, ctrl).then(function(map) {
var enableKeyDragZoom, setKeyAction, setOptionsAction;
enableKeyDragZoom = function(opts) {
map.enableKeyDragZoom(opts);
if (scope.spec) {
return scope.spec.enableKeyDragZoom(opts);
}
};
setKeyAction = new PropertyAction(function(key, newVal) {
if (newVal) {
return enableKeyDragZoom({
key: newVal
});
} else {
return enableKeyDragZoom();
}
});
setOptionsAction = new PropertyAction(function(key, newVal) {
if (newVal) {
return enableKeyDragZoom(newVal);
}
});
scope.$watch('keyboardkey', setKeyAction.sic);
setKeyAction.sic(scope.keyboardkey);
scope.$watch('options', setOptionsAction.sic);
return setOptionsAction.sic(scope.options);
});
}
};
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapDrawingManager", [
"uiGmapIDrawingManager", "uiGmapDrawingManagerParentModel", function(IDrawingManager, DrawingManagerParentModel) {
return _.extend(IDrawingManager, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then(function(map) {
return new DrawingManagerParentModel(scope, element, attrs, map);
});
}
});
}
]);
}).call(this);
;
/*
- Link up Polygons to be sent back to a controller
- inject the draw function into a controllers scope so that controller can call the directive to draw on demand
- draw function creates the DrawFreeHandChildModel which manages itself
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapApiFreeDrawPolygons', [
'uiGmapLogger', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapDrawFreeHandChildModel', 'uiGmapLodash', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel, uiGmapLodash) {
var FreeDrawPolygons;
return FreeDrawPolygons = (function(_super) {
__extends(FreeDrawPolygons, _super);
function FreeDrawPolygons() {
this.link = __bind(this.link, this);
return FreeDrawPolygons.__super__.constructor.apply(this, arguments);
}
FreeDrawPolygons.include(CtrlHandle);
FreeDrawPolygons.prototype.restrict = 'EMA';
FreeDrawPolygons.prototype.replace = true;
FreeDrawPolygons.prototype.require = '^' + 'uiGmapGoogleMap';
FreeDrawPolygons.prototype.scope = {
polygons: '=',
draw: '=',
revertmapoptions: '='
};
FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) {
return this.mapPromise(scope, ctrl).then((function(_this) {
return function(map) {
var freeHand, listener;
if (!scope.polygons) {
return $log.error('No polygons to bind to!');
}
if (!_.isArray(scope.polygons)) {
return $log.error('Free Draw Polygons must be of type Array!');
}
freeHand = new DrawFreeHandChildModel(map, scope.revertmapoptions);
listener = void 0;
return scope.draw = function() {
if (typeof listener === "function") {
listener();
}
return freeHand.engage(scope.polygons).then(function() {
var firstTime;
firstTime = true;
return listener = scope.$watchCollection('polygons', function(newValue, oldValue) {
var removals;
if (firstTime || newValue === oldValue) {
firstTime = false;
return;
}
removals = uiGmapLodash.differenceObjects(oldValue, newValue);
return removals.forEach(function(p) {
return p.setMap(null);
});
});
});
};
};
})(this));
};
return FreeDrawPolygons;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module("uiGmapgoogle-maps.directives.api").service("uiGmapICircle", [
function() {
var DEFAULTS;
DEFAULTS = {};
return {
restrict: "EA",
replace: true,
require: '^' + 'uiGmapGoogleMap',
scope: {
center: "=center",
radius: "=radius",
stroke: "=stroke",
fill: "=fill",
clickable: "=",
draggable: "=",
editable: "=",
geodesic: "=",
icons: "=icons",
visible: "=",
events: "="
}
};
}
]);
}).call(this);
;
/*
- interface for all controls to derive from
- to enforce a minimum set of requirements
- attributes
- template
- position
- controller
- index
*/
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapIControl", [
"uiGmapBaseObject", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, Logger, CtrlHandle) {
var IControl;
return IControl = (function(_super) {
__extends(IControl, _super);
IControl.extend(CtrlHandle);
function IControl() {
this.restrict = 'EA';
this.replace = true;
this.require = '^' + 'uiGmapGoogleMap';
this.scope = {
template: '@template',
position: '@position',
controller: '@controller',
index: '@index'
};
this.$log = Logger;
}
IControl.prototype.link = function(scope, element, attrs, ctrl) {
throw new Exception("Not implemented!!");
};
return IControl;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIDrawingManager', [
function() {
return {
restrict: 'EA',
replace: true,
require: '^' + 'uiGmapGoogleMap',
scope: {
"static": '@',
control: '=',
options: '=',
events: '='
}
};
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIMarker', [
'uiGmapBaseObject', 'uiGmapCtrlHandle', function(BaseObject, CtrlHandle) {
var IMarker;
return IMarker = (function(_super) {
__extends(IMarker, _super);
IMarker.scope = {
coords: '=coords',
icon: '=icon',
click: '&click',
options: '=options',
events: '=events',
fit: '=fit',
idKey: '=idkey',
control: '=control'
};
IMarker.scopeKeys = _.keys(IMarker.scope);
IMarker.keys = IMarker.scopeKeys;
IMarker.extend(CtrlHandle);
function IMarker() {
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.replace = true;
this.scope = _.extend(this.scope || {}, IMarker.scope);
}
return IMarker;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolygon', [
'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {
var IPolygon;
return IPolygon = (function(_super) {
__extends(IPolygon, _super);
IPolygon.scope = {
path: '=path',
stroke: '=stroke',
clickable: '=',
draggable: '=',
editable: '=',
geodesic: '=',
fill: '=',
icons: '=icons',
visible: '=',
"static": '=',
events: '=',
zIndex: '=zindex',
fit: '=',
control: '=control'
};
IPolygon.scopeKeys = _.keys(IPolygon.scope);
IPolygon.include(GmapUtil);
IPolygon.extend(CtrlHandle);
function IPolygon() {}
IPolygon.prototype.restrict = 'EMA';
IPolygon.prototype.replace = true;
IPolygon.prototype.require = '^' + 'uiGmapGoogleMap';
IPolygon.prototype.scope = IPolygon.scope;
IPolygon.prototype.DEFAULTS = {};
IPolygon.prototype.$log = Logger;
return IPolygon;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolyline', [
'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) {
var IPolyline;
return IPolyline = (function(_super) {
__extends(IPolyline, _super);
IPolyline.scope = {
path: '=',
stroke: '=',
clickable: '=',
draggable: '=',
editable: '=',
geodesic: '=',
icons: '=',
visible: '=',
"static": '=',
fit: '=',
events: '='
};
IPolyline.scopeKeys = _.keys(IPolyline.scope);
IPolyline.include(GmapUtil);
IPolyline.extend(CtrlHandle);
function IPolyline() {}
IPolyline.prototype.restrict = 'EMA';
IPolyline.prototype.replace = true;
IPolyline.prototype.require = '^' + 'uiGmapGoogleMap';
IPolyline.prototype.scope = IPolyline.scope;
IPolyline.prototype.DEFAULTS = {};
IPolyline.prototype.$log = Logger;
return IPolyline;
})(BaseObject);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIRectangle', [
function() {
'use strict';
var DEFAULTS;
DEFAULTS = {};
return {
restrict: 'EMA',
require: '^' + 'uiGmapGoogleMap',
replace: true,
scope: {
bounds: '=',
stroke: '=',
clickable: '=',
draggable: '=',
editable: '=',
fill: '=',
visible: '=',
events: '='
}
};
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIWindow', [
'uiGmapBaseObject', 'uiGmapChildEvents', 'uiGmapCtrlHandle', function(BaseObject, ChildEvents, CtrlHandle) {
var IWindow;
return IWindow = (function(_super) {
__extends(IWindow, _super);
IWindow.scope = {
coords: '=coords',
template: '=template',
templateUrl: '=templateurl',
templateParameter: '=templateparameter',
isIconVisibleOnClick: '=isiconvisibleonclick',
closeClick: '&closeclick',
options: '=options',
control: '=control',
show: '=show'
};
IWindow.scopeKeys = _.keys(IWindow.scope);
IWindow.include(ChildEvents);
IWindow.extend(CtrlHandle);
function IWindow() {
this.restrict = 'EMA';
this.template = void 0;
this.transclude = true;
this.priority = -100;
this.require = '^' + 'uiGmapGoogleMap';
this.replace = true;
this.scope = _.extend(this.scope || {}, IWindow.scope);
}
return IWindow;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapMap', [
'$timeout', '$q', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapIsReady', 'uiGmapuuid', 'uiGmapExtendGWin', 'uiGmapExtendMarkerClusterer', 'uiGmapGoogleMapsUtilV3', 'uiGmapGoogleMapApi', 'uiGmapEventsHelper', function($timeout, $q, $log, GmapUtil, BaseObject, CtrlHandle, IsReady, uuid, ExtendGWin, ExtendMarkerClusterer, GoogleMapsUtilV3, GoogleMapApi, EventsHelper) {
'use strict';
var DEFAULTS, Map, initializeItems;
DEFAULTS = void 0;
initializeItems = [GoogleMapsUtilV3, ExtendGWin, ExtendMarkerClusterer];
return Map = (function(_super) {
__extends(Map, _super);
Map.include(GmapUtil);
function Map() {
this.link = __bind(this.link, this);
var ctrlFn, self;
ctrlFn = function($scope) {
var ctrlObj, retCtrl;
retCtrl = void 0;
$scope.$on('$destroy', function() {
return IsReady.reset();
});
ctrlObj = CtrlHandle.handle($scope);
$scope.ctrlType = 'Map';
$scope.deferred.promise.then(function() {
return initializeItems.forEach(function(i) {
return i.init();
});
});
ctrlObj.getMap = function() {
return $scope.map;
};
retCtrl = _.extend(this, ctrlObj);
return retCtrl;
};
this.controller = ['$scope', ctrlFn];
self = this;
}
Map.prototype.restrict = 'EMA';
Map.prototype.transclude = true;
Map.prototype.replace = false;
Map.prototype.template = '<div class="angular-google-map"><div class="angular-google-map-container"></div><div ng-transclude style="display: none"></div></div>';
Map.prototype.scope = {
center: '=',
zoom: '=',
dragging: '=',
control: '=',
options: '=',
events: '=',
eventOpts: '=',
styles: '=',
bounds: '=',
update: '='
};
Map.prototype.link = function(scope, element, attrs) {
var listeners, unbindCenterWatch;
listeners = [];
scope.$on('$destroy', function() {
return EventsHelper.removeEvents(listeners);
});
scope.idleAndZoomChanged = false;
if (scope.center == null) {
unbindCenterWatch = scope.$watch('center', (function(_this) {
return function() {
if (!scope.center) {
return;
}
unbindCenterWatch();
return _this.link(scope, element, attrs);
};
})(this));
return;
}
return GoogleMapApi.then((function(_this) {
return function(maps) {
var customListeners, disabledEvents, dragging, el, eventName, getEventHandler, mapOptions, maybeHookToEvent, opts, resolveSpawned, settingFromDirective, spawned, type, updateCenter, zoomPromise, _gMap, _ref;
DEFAULTS = {
mapTypeId: maps.MapTypeId.ROADMAP
};
spawned = IsReady.spawn();
resolveSpawned = function() {
return spawned.deferred.resolve({
instance: spawned.instance,
map: _gMap
});
};
if (!_this.validateCoords(scope.center)) {
$log.error('angular-google-maps: could not find a valid center property');
return;
}
if (!angular.isDefined(scope.zoom)) {
$log.error('angular-google-maps: map zoom property not set');
return;
}
el = angular.element(element);
el.addClass('angular-google-map');
opts = {
options: {}
};
if (attrs.options) {
opts.options = scope.options;
}
if (attrs.styles) {
opts.styles = scope.styles;
}
if (attrs.type) {
type = attrs.type.toUpperCase();
if (google.maps.MapTypeId.hasOwnProperty(type)) {
opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()];
} else {
$log.error("angular-google-maps: invalid map type '" + attrs.type + "'");
}
}
mapOptions = angular.extend({}, DEFAULTS, opts, {
center: _this.getCoords(scope.center),
zoom: scope.zoom,
bounds: scope.bounds
});
_gMap = new google.maps.Map(el.find('div')[1], mapOptions);
_gMap['uiGmap_id'] = uuid.generate();
dragging = false;
listeners.push(google.maps.event.addListenerOnce(_gMap, 'idle', function() {
scope.deferred.resolve(_gMap);
return resolveSpawned();
}));
disabledEvents = attrs.events && (((_ref = scope.events) != null ? _ref.blacklist : void 0) != null) ? scope.events.blacklist : [];
if (_.isString(disabledEvents)) {
disabledEvents = [disabledEvents];
}
maybeHookToEvent = function(eventName, fn, prefn) {
if (!_.contains(disabledEvents, eventName)) {
if (prefn) {
prefn();
}
return listeners.push(google.maps.event.addListener(_gMap, eventName, function() {
var _ref1;
if (!((_ref1 = scope.update) != null ? _ref1.lazy : void 0)) {
return fn();
}
}));
}
};
if (!_.contains(disabledEvents, 'all')) {
maybeHookToEvent('dragstart', function() {
dragging = true;
return scope.$evalAsync(function(s) {
if (s.dragging != null) {
return s.dragging = dragging;
}
});
});
maybeHookToEvent('dragend', function() {
dragging = false;
return scope.$evalAsync(function(s) {
if (s.dragging != null) {
return s.dragging = dragging;
}
});
});
updateCenter = function(c, s) {
if (c == null) {
c = _gMap.center;
}
if (s == null) {
s = scope;
}
if (_.contains(disabledEvents, 'center')) {
return;
}
if (angular.isDefined(s.center.type)) {
if (s.center.coordinates[1] !== c.lat()) {
s.center.coordinates[1] = c.lat();
}
if (s.center.coordinates[0] !== c.lng()) {
return s.center.coordinates[0] = c.lng();
}
} else {
if (s.center.latitude !== c.lat()) {
s.center.latitude = c.lat();
}
if (s.center.longitude !== c.lng()) {
return s.center.longitude = c.lng();
}
}
};
settingFromDirective = false;
maybeHookToEvent('idle', function() {
var b, ne, sw;
b = _gMap.getBounds();
ne = b.getNorthEast();
sw = b.getSouthWest();
settingFromDirective = true;
return scope.$evalAsync(function(s) {
updateCenter();
if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0 && !_.contains(disabledEvents, 'bounds')) {
s.bounds.northeast = {
latitude: ne.lat(),
longitude: ne.lng()
};
s.bounds.southwest = {
latitude: sw.lat(),
longitude: sw.lng()
};
}
if (!_.contains(disabledEvents, 'zoom')) {
s.zoom = _gMap.zoom;
scope.idleAndZoomChanged = !scope.idleAndZoomChanged;
}
return settingFromDirective = false;
});
});
}
if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) {
getEventHandler = function(eventName) {
return function() {
return scope.events[eventName].apply(scope, [_gMap, eventName, arguments]);
};
};
customListeners = [];
for (eventName in scope.events) {
if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) {
customListeners.push(google.maps.event.addListener(_gMap, eventName, getEventHandler(eventName)));
}
}
listeners.concat(customListeners);
}
_gMap.getOptions = function() {
return mapOptions;
};
scope.map = _gMap;
if ((attrs.control != null) && (scope.control != null)) {
scope.control.refresh = function(maybeCoords) {
var coords, _ref1, _ref2;
if (_gMap == null) {
return;
}
if (((typeof google !== "undefined" && google !== null ? (_ref1 = google.maps) != null ? (_ref2 = _ref1.event) != null ? _ref2.trigger : void 0 : void 0 : void 0) != null) && (_gMap != null)) {
google.maps.event.trigger(_gMap, 'resize');
}
if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.longitude : void 0) != null)) {
coords = _this.getCoords(maybeCoords);
if (_this.isTrue(attrs.pan)) {
return _gMap.panTo(coords);
} else {
return _gMap.setCenter(coords);
}
}
};
scope.control.getGMap = function() {
return _gMap;
};
scope.control.getMapOptions = function() {
return mapOptions;
};
scope.control.getCustomEventListeners = function() {
return customListeners;
};
scope.control.removeEvents = function(yourListeners) {
return EventsHelper.removeEvents(yourListeners);
};
}
scope.$watch('center', function(newValue, oldValue) {
var coords, settingCenterFromScope;
if (newValue === oldValue || settingFromDirective) {
return;
}
coords = _this.getCoords(scope.center);
if (coords.lat() === _gMap.center.lat() && coords.lng() === _gMap.center.lng()) {
return;
}
settingCenterFromScope = true;
if (!dragging) {
if (!_this.validateCoords(newValue)) {
$log.error("Invalid center for newValue: " + (JSON.stringify(newValue)));
}
if (_this.isTrue(attrs.pan) && scope.zoom === _gMap.zoom) {
_gMap.panTo(coords);
} else {
_gMap.setCenter(coords);
}
}
return settingCenterFromScope = false;
}, true);
zoomPromise = null;
scope.$watch('zoom', function(newValue, oldValue) {
var settingZoomFromScope, _ref1, _ref2;
if (newValue == null) {
return;
}
if (_.isEqual(newValue, oldValue) || (_gMap != null ? _gMap.getZoom() : void 0) === (scope != null ? scope.zoom : void 0) || settingFromDirective) {
return;
}
settingZoomFromScope = true;
if (zoomPromise != null) {
$timeout.cancel(zoomPromise);
}
return zoomPromise = $timeout(function() {
_gMap.setZoom(newValue);
return settingZoomFromScope = false;
}, ((_ref1 = scope.eventOpts) != null ? (_ref2 = _ref1.debounce) != null ? _ref2.zoomMs : void 0 : void 0) + 20, false);
});
scope.$watch('bounds', function(newValue, oldValue) {
var bounds, ne, sw, _ref1, _ref2, _ref3, _ref4;
if (newValue === oldValue) {
return;
}
if (((newValue != null ? (_ref1 = newValue.northeast) != null ? _ref1.latitude : void 0 : void 0) == null) || ((newValue != null ? (_ref2 = newValue.northeast) != null ? _ref2.longitude : void 0 : void 0) == null) || ((newValue != null ? (_ref3 = newValue.southwest) != null ? _ref3.latitude : void 0 : void 0) == null) || ((newValue != null ? (_ref4 = newValue.southwest) != null ? _ref4.longitude : void 0 : void 0) == null)) {
$log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue)));
return;
}
ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude);
sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude);
bounds = new google.maps.LatLngBounds(sw, ne);
return _gMap.fitBounds(bounds);
});
return ['options', 'styles'].forEach(function(toWatch) {
return scope.$watch(toWatch, function(newValue, oldValue) {
var watchItem;
watchItem = this.exp;
if (_.isEqual(newValue, oldValue)) {
return;
}
if (watchItem === 'options') {
opts.options = newValue;
} else {
opts.options[watchItem] = newValue;
}
if (_gMap != null) {
return _gMap.setOptions(opts);
}
}, true);
});
};
})(this));
};
return Map;
})(BaseObject);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [
"uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", "uiGmapLogger", function(IMarker, MarkerChildModel, MarkerManager, $log) {
var Marker;
return Marker = (function(_super) {
__extends(Marker, _super);
function Marker() {
this.link = __bind(this.link, this);
Marker.__super__.constructor.call(this);
this.template = '<span class="angular-google-map-marker" ng-transclude></span>';
$log.info(this);
}
Marker.prototype.controller = [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'Marker';
return _.extend(this, IMarker.handle($scope, $element));
}
];
Marker.prototype.link = function(scope, element, attrs, ctrl) {
var mapPromise;
mapPromise = IMarker.mapPromise(scope, ctrl);
mapPromise.then((function(_this) {
return function(map) {
var doClick, doDrawSelf, gManager, keys, m, trackModel;
gManager = new MarkerManager(map);
keys = _.object(IMarker.keys, IMarker.keys);
m = new MarkerChildModel(scope, scope, keys, map, {}, doClick = true, gManager, doDrawSelf = false, trackModel = false);
m.deferred.promise.then(function(gMarker) {
return scope.deferred.resolve(gMarker);
});
if (scope.control != null) {
return scope.control.getGMarkers = gManager.getGMarkers;
}
};
})(this));
return scope.$on('$destroy', (function(_this) {
return function() {
var gManager;
if (typeof gManager !== "undefined" && gManager !== null) {
gManager.clear();
}
return gManager = null;
};
})(this));
};
return Marker;
})(IMarker);
}
]);
}).call(this);
;(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [
"uiGmapIMarker", "uiGmapPlural", "uiGmapMarkersParentModel", "uiGmap_sync", "uiGmapLogger", function(IMarker, Plural, MarkersParentModel, _sync, $log) {
var Markers;
return Markers = (function(_super) {
__extends(Markers, _super);
function Markers() {
Markers.__super__.constructor.call(this);
this.template = '<span class="angular-google-map-markers" ng-transclude></span>';
Plural.extend(this, {
doCluster: '=docluster',
clusterOptions: '=clusteroptions',
clusterEvents: '=clusterevents',
modelsByRef: '=modelsbyref'
});
$log.info(this);
}
Markers.prototype.controller = [
'$scope', '$element', function($scope, $element) {
$scope.ctrlType = 'Markers';
return _.extend(this, IMarker.handle($scope, $element));
}
];
Markers.prototype.link = function(scope, element, attrs, ctrl) {
var parentModel, ready;
parentModel = void 0;
ready = function() {
return scope.deferred.resolve();
};
return IMarker.mapPromise(scope, ctrl).then(function(map) {
var mapScope;
mapScope = ctrl.getScope();
mapScope.$watch('idleAndZoomChanged', function() {
return _.defer(parentModel.gManager.draw);
});
parentModel = new MarkersParentModel(scope, element, attrs, map);
Plural.link(scope, parentModel);
if (scope.control != null) {
scope.control.getGMarkers = function() {
var _ref;
return (_ref = parentModel.gManager) != null ? _ref.getGMarkers() : void 0;
};
scope.control.getChildMarkers = function() {
return parentModel.plurals;
};
}
return _.last(parentModel.existingPieces._content).then(function() {
return ready();
});
});
};
return Markers;
})(IMarker);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapPlural', [
function() {
var _initControl;
_initControl = function(scope, parent) {
if (scope.control == null) {
return;
}
scope.control.updateModels = function(models) {
scope.models = models;
return parent.createChildScopes(false);
};
scope.control.newModels = function(models) {
scope.models = models;
return parent.rebuildAll(scope, true, true);
};
scope.control.clean = function() {
return parent.rebuildAll(scope, false, true);
};
scope.control.getPlurals = function() {
return parent.plurals;
};
scope.control.getManager = function() {
return parent.gManager;
};
scope.control.hasManager = function() {
return (parent.gManager != null) === true;
};
return scope.control.managerDraw = function() {
var _ref;
if (scope.control.hasManager()) {
return (_ref = scope.control.getManager()) != null ? _ref.draw() : void 0;
}
};
};
return {
extend: function(obj, obj2) {
return _.extend(obj.scope || {}, obj2 || {}, {
idKey: '=idkey',
doRebuildAll: '=dorebuildall',
models: '=models',
chunk: '=chunk',
cleanchunk: '=cleanchunk',
control: '=control'
});
},
link: function(scope, parent) {
return _initControl(scope, parent);
}
};
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygon', [
'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonChildModel', function(IPolygon, $timeout, arraySync, PolygonChild) {
var Polygon;
return Polygon = (function(_super) {
__extends(Polygon, _super);
function Polygon() {
this.link = __bind(this.link, this);
return Polygon.__super__.constructor.apply(this, arguments);
}
Polygon.prototype.link = function(scope, element, attrs, mapCtrl) {
var children, promise;
children = [];
promise = IPolygon.mapPromise(scope, mapCtrl);
if (scope.control != null) {
scope.control.getInstance = this;
scope.control.polygons = children;
scope.control.promise = promise;
}
return promise.then((function(_this) {
return function(map) {
return children.push(new PolygonChild(scope, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polygon;
})(IPolygon);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygons', [
'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonsParentModel', 'uiGmapPlural', function(Interface, $timeout, arraySync, ParentModel, Plural) {
var Polygons;
return Polygons = (function(_super) {
__extends(Polygons, _super);
function Polygons() {
this.link = __bind(this.link, this);
Polygons.__super__.constructor.call(this);
Plural.extend(this);
this.$log.info(this);
}
Polygons.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null) {
_this.$log.warn('polygons: no valid path attribute found');
}
if (!scope.models) {
_this.$log.warn('polygons: no models found to create from');
}
return Plural.link(scope, new ParentModel(scope, element, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polygons;
})(Interface);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolyline', [
'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylineChildModel', function(IPolyline, $timeout, arraySync, PolylineChildModel) {
var Polyline;
return Polyline = (function(_super) {
__extends(Polyline, _super);
function Polyline() {
this.link = __bind(this.link, this);
return Polyline.__super__.constructor.apply(this, arguments);
}
Polyline.prototype.link = function(scope, element, attrs, mapCtrl) {
return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null || !_this.validatePath(scope.path)) {
_this.$log.warn('polyline: no valid path attribute found');
}
return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS);
};
})(this));
};
return Polyline;
})(IPolyline);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylines', [
'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylinesParentModel', 'uiGmapPlural', function(IPolyline, $timeout, arraySync, PolylinesParentModel, Plural) {
var Polylines;
return Polylines = (function(_super) {
__extends(Polylines, _super);
function Polylines() {
this.link = __bind(this.link, this);
Polylines.__super__.constructor.call(this);
Plural.extend(this);
this.$log.info(this);
}
Polylines.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (angular.isUndefined(scope.path) || scope.path === null) {
_this.$log.warn('polylines: no valid path attribute found');
}
if (!scope.models) {
_this.$log.warn('polylines: no models found to create from');
}
return Plural.link(scope, new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS));
};
})(this));
};
return Polylines;
})(IPolyline);
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapRectangle', [
'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapIRectangle', 'uiGmapRectangleParentModel', function($log, GmapUtil, IRectangle, RectangleParentModel) {
return _.extend(IRectangle, {
link: function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new RectangleParentModel(scope, element, attrs, map);
};
})(this));
}
});
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindow', [
'uiGmapIWindow', 'uiGmapGmapUtil', 'uiGmapWindowChildModel', 'uiGmapLodash', 'uiGmapLogger', function(IWindow, GmapUtil, WindowChildModel, uiGmapLodash, $log) {
var Window;
return Window = (function(_super) {
__extends(Window, _super);
Window.include(GmapUtil);
function Window() {
this.link = __bind(this.link, this);
Window.__super__.constructor.call(this);
this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker'];
this.template = '<span class="angular-google-maps-window" ng-transclude></span>';
$log.debug(this);
this.childWindows = [];
}
Window.prototype.link = function(scope, element, attrs, ctrls) {
var markerCtrl, markerScope;
markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;
markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;
this.mapPromise = IWindow.mapPromise(scope, ctrls[0]);
return this.mapPromise.then((function(_this) {
return function(mapCtrl) {
var isIconVisibleOnClick;
isIconVisibleOnClick = true;
if (angular.isDefined(attrs.isiconvisibleonclick)) {
isIconVisibleOnClick = scope.isIconVisibleOnClick;
}
if (!markerCtrl) {
_this.init(scope, element, isIconVisibleOnClick, mapCtrl);
return;
}
return markerScope.deferred.promise.then(function(gMarker) {
return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope);
});
};
})(this));
};
Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) {
var childWindow, defaults, gMarker, hasScopeCoords, opts;
defaults = scope.options != null ? scope.options : {};
hasScopeCoords = (scope != null) && this.validateCoords(scope.coords);
if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) {
gMarker = markerScope.getGMarker();
}
opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults;
if (mapCtrl != null) {
childWindow = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element);
this.childWindows.push(childWindow);
scope.$on('$destroy', (function(_this) {
return function() {
_this.childWindows = uiGmapLodash.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) {
return child1.scope.$id === child2.scope.$id;
});
return _this.childWindows.length = 0;
};
})(this));
}
if (scope.control != null) {
scope.control.getGWindows = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.gObject;
});
};
})(this);
scope.control.getChildWindows = (function(_this) {
return function() {
return _this.childWindows;
};
})(this);
scope.control.getPlurals = scope.control.getChildWindows;
scope.control.showWindow = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.showWindow();
});
};
})(this);
scope.control.hideWindow = (function(_this) {
return function() {
return _this.childWindows.map(function(child) {
return child.hideWindow();
});
};
})(this);
}
if ((this.onChildCreation != null) && (childWindow != null)) {
return this.onChildCreation(childWindow);
}
};
return Window;
})(IWindow);
}
]);
}).call(this);
;(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindows', [
'uiGmapIWindow', 'uiGmapPlural', 'uiGmapWindowsParentModel', 'uiGmapPromise', 'uiGmapLogger', function(IWindow, Plural, WindowsParentModel, uiGmapPromise, $log) {
/*
Windows directive where many windows map to the models property
*/
var Windows;
return Windows = (function(_super) {
__extends(Windows, _super);
function Windows() {
this.init = __bind(this.init, this);
this.link = __bind(this.link, this);
Windows.__super__.constructor.call(this);
this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers'];
this.template = '<span class="angular-google-maps-windows" ng-transclude></span>';
Plural.extend(this);
$log.debug(this);
}
Windows.prototype.link = function(scope, element, attrs, ctrls) {
var mapScope, markerCtrl, markerScope;
mapScope = ctrls[0].getScope();
markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0;
markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0;
return mapScope.deferred.promise.then((function(_this) {
return function(map) {
var promise, _ref;
promise = (markerScope != null ? (_ref = markerScope.deferred) != null ? _ref.promise : void 0 : void 0) || uiGmapPromise.resolve();
return promise.then(function() {
var pieces, _ref1;
pieces = (_ref1 = _this.parentModel) != null ? _ref1.existingPieces : void 0;
if (pieces) {
return pieces.then(function() {
return _this.init(scope, element, attrs, ctrls, map, markerScope);
});
} else {
return _this.init(scope, element, attrs, ctrls, map, markerScope);
}
});
};
})(this));
};
Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) {
var parentModel;
parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope);
Plural.link(scope, parentModel);
if (scope.control != null) {
scope.control.getGWindows = (function(_this) {
return function() {
return parentModel.plurals.map(function(child) {
return child.gObject;
});
};
})(this);
return scope.control.getChildWindows = (function(_this) {
return function() {
return parentModel.plurals;
};
})(this);
}
};
return Windows;
})(IWindow);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Nick Baugh - https://github.com/niftylettuce
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapGoogleMap", [
"uiGmapMap", function(Map) {
return new Map();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map marker directive
This directive is used to create a marker on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute icon optional} string url to image used for marker icon
{attribute animate optional} if set to false, the marker won't be animated (on by default)
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapMarker', [
'$timeout', 'uiGmapMarker', function($timeout, Marker) {
return new Marker($timeout);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map marker directive
This directive is used to create a marker on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute icon optional} string url to image used for marker icon
{attribute animate optional} if set to false, the marker won't be animated (on by default)
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapMarkers', [
'$timeout', 'uiGmapMarkers', function($timeout, Markers) {
return new Markers($timeout);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolygon', [
'uiGmapPolygon', function(Polygon) {
return new Polygon();
}
]);
}).call(this);
;
/*
@authors
Julian Popescu - https://github.com/jpopesculian
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive("uiGmapCircle", [
"uiGmapCircle", function(Circle) {
return Circle;
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapPolyline", [
"uiGmapPolyline", function(Polyline) {
return new Polyline();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolylines', [
'uiGmapPolylines', function(Polylines) {
return new Polylines();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Chentsu Lin - https://github.com/ChenTsuLin
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapRectangle", [
"uiGmapLogger", "uiGmapRectangle", function($log, Rectangle) {
return Rectangle;
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapWindow", [
"$timeout", "$compile", "$http", "$templateCache", "uiGmapWindow", function($timeout, $compile, $http, $templateCache, Window) {
return new Window($timeout, $compile, $http, $templateCache);
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapWindows", [
"$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) {
return new Windows($timeout, $compile, $http, $templateCache, $interpolate);
}
]);
}).call(this);
;
/*
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
*/
/*
Map Layer directive
This directive is used to create any type of Layer from the google maps sdk.
This directive creates a new scope.
{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps').directive('uiGmapLayer', [
'$timeout', 'uiGmapLogger', 'uiGmapLayerParentModel', function($timeout, Logger, LayerParentModel) {
var Layer;
Layer = (function() {
function Layer() {
this.link = __bind(this.link, this);
this.$log = Logger;
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\'angular-google-map-layer\' ng-transclude></span>';
this.replace = true;
this.scope = {
show: '=show',
type: '=type',
namespace: '=namespace',
options: '=options',
onCreated: '&oncreated'
};
}
Layer.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
if (scope.onCreated != null) {
return new LayerParentModel(scope, element, attrs, map, scope.onCreated);
} else {
return new LayerParentModel(scope, element, attrs, map);
}
};
})(this));
};
return Layer;
})();
return new Layer();
}
]);
}).call(this);
;
/*
@authors
Adam Kreitals, kreitals@hotmail.com
*/
/*
mapControl directive
This directive is used to create a custom control element on an existing map.
This directive creates a new scope.
{attribute template required} string url of the template to be used for the control
{attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER
{attribute controller optional} string controller to be applied to the template
{attribute index optional} number index for controlling the order of similarly positioned mapControl elements
*/
(function() {
angular.module("uiGmapgoogle-maps").directive("uiGmapMapControl", [
"uiGmapControl", function(Control) {
return new Control();
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapDragZoom', [
'uiGmapDragZoom', function(DragZoom) {
return DragZoom;
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').directive("uiGmapDrawingManager", [
"uiGmapDrawingManager", function(DrawingManager) {
return DrawingManager;
}
]);
}).call(this);
;
/*
@authors
Nicholas McCready - https://twitter.com/nmccready
* Brunt of the work is in DrawFreeHandChildModel
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapFreeDrawPolygons', [
'uiGmapApiFreeDrawPolygons', function(FreeDrawPolygons) {
return new FreeDrawPolygons();
}
]);
}).call(this);
;
/*
Map Layer directive
This directive is used to create any type of Layer from the google maps sdk.
This directive creates a new scope.
{attribute show optional} true (default) shows the trafficlayer otherwise it is hidden
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module("uiGmapgoogle-maps").directive("uiGmapMapType", [
"$timeout", "uiGmapLogger", "uiGmapMapTypeParentModel", function($timeout, Logger, MapTypeParentModel) {
var MapType;
MapType = (function() {
function MapType() {
this.link = __bind(this.link, this);
this.$log = Logger;
this.restrict = "EMA";
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>';
this.replace = true;
this.scope = {
show: "=show",
options: '=options',
refresh: '=refresh',
id: '@'
};
}
MapType.prototype.link = function(scope, element, attrs, mapCtrl) {
return mapCtrl.getScope().deferred.promise.then((function(_this) {
return function(map) {
return new MapTypeParentModel(scope, element, attrs, map);
};
})(this));
};
return MapType;
})();
return new MapType();
}
]);
}).call(this);
;
/*
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
*/
(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapPolygons', [
'uiGmapPolygons', function(Polygons) {
return new Polygons();
}
]);
}).call(this);
;
/*
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
- Carrie Kengle - http://about.me/carrie
*/
/*
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
angular.module('uiGmapgoogle-maps').directive('uiGmapSearchBox', [
'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) {
var SearchBox;
SearchBox = (function() {
SearchBox.prototype.require = 'ngModel';
function SearchBox() {
this.link = __bind(this.link, this);
this.$log = Logger;
this.restrict = 'EMA';
this.require = '^' + 'uiGmapGoogleMap';
this.priority = -1;
this.transclude = true;
this.template = '<span class=\'angular-google-map-search\' ng-transclude></span>';
this.replace = true;
this.scope = {
template: '=template',
events: '=events',
position: '=?position',
options: '=?options',
parentdiv: '=?parentdiv',
ngModel: "=?"
};
}
SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) {
return GoogleMapApi.then((function(_this) {
return function(maps) {
return $http.get(scope.template, {
cache: $templateCache
}).success(function(template) {
if (angular.isUndefined(scope.events)) {
_this.$log.error('searchBox: the events property is required');
return;
}
return mapCtrl.getScope().deferred.promise.then(function(map) {
var ctrlPosition;
ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT';
if (!maps.ControlPosition[ctrlPosition]) {
_this.$log.error('searchBox: invalid position property');
return;
}
return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope));
});
});
};
})(this));
};
return SearchBox;
})();
return new SearchBox();
}
]);
}).call(this);
;(function() {
angular.module('uiGmapgoogle-maps').directive('uiGmapShow', [
'$animate', 'uiGmapLogger', function($animate, $log) {
return {
scope: {
'uiGmapShow': '=',
'uiGmapAfterShow': '&',
'uiGmapAfterHide': '&'
},
link: function(scope, element) {
var angular_post_1_3_handle, angular_pre_1_3_handle, handle;
angular_post_1_3_handle = function(animateAction, cb) {
return $animate[animateAction](element, 'ng-hide').then(function() {
return cb();
});
};
angular_pre_1_3_handle = function(animateAction, cb) {
return $animate[animateAction](element, 'ng-hide', cb);
};
handle = function(animateAction, cb) {
if (angular.version.major > 1) {
return $log.error("uiGmapShow is not supported for Angular Major greater than 1.\nYour Major is " + angular.version.major + "\"");
}
if (angular.version.major === 1 && angular.version.minor < 3) {
return angular_pre_1_3_handle(animateAction, cb);
}
return angular_post_1_3_handle(animateAction, cb);
};
return scope.$watch('uiGmapShow', function(show) {
if (show) {
handle('removeClass', scope.uiGmapAfterShow);
}
if (!show) {
return handle('addClass', scope.uiGmapAfterHide);
}
});
}
};
}
]);
}).call(this);
;angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapuuid', function() {
//BEGIN REPLACE
/*
Version: core-1.0
The MIT License: Copyright (c) 2012 LiosK.
*/
function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c};
//END REPLACE
return UUID;
});
;// wrap the utility libraries needed in ./lib
// http://google-maps-utility-library-v3.googlecode.com/svn/
angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapGoogleMapsUtilV3', function () {
return {
init: _.once(function () {
//BEGIN REPLACE
/**
* @name InfoBox
* @version 1.1.13 [March 19, 2014]
* @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google)
* @copyright Copyright 2010 Gary Little [gary at luxcentral.com]
* @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class.
* <p>
* An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several
* additional properties for advanced styling. An InfoBox can also be used as a map label.
* <p>
* An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>.
*/
/*!
*
* 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.
*/
/*jslint browser:true */
/*global google */
/**
* @name InfoBoxOptions
* @class This class represents the optional parameter passed to the {@link InfoBox} constructor.
* @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node).
* @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>.
* @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum.
* @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox
* (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>)
* to the map pixel corresponding to <tt>position</tt>.
* @property {LatLng} position The geographic location at which to display the InfoBox.
* @property {number} zIndex The CSS z-index style value for the InfoBox.
* Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property.
* @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container.
* @property {Object} [boxStyle] An object literal whose properties define specific CSS
* style values to be applied to the InfoBox. Style values defined here override those that may
* be defined in the <code>boxClass</code> style sheet. If this property is changed after the
* InfoBox has been created, all previously set styles (except those defined in the style sheet)
* are removed from the InfoBox before the new style values are applied.
* @property {string} closeBoxMargin The CSS margin style value for the close box.
* The default is "2px" (a 2-pixel margin on all sides).
* @property {string} closeBoxURL The URL of the image representing the close box.
* Note: The default is the URL for Google's standard close box.
* Set this property to "" if no close box is required.
* @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the
* map edge after an auto-pan.
* @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>.
* [Deprecated in favor of the <tt>visible</tt> property.]
* @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>.
* @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code>
* location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned).
* @property {string} pane The pane where the InfoBox is to appear (default is "floatPane").
* Set the pane to "mapPane" if the InfoBox is being used as a map label.
* Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object.
* @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout,
* mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox
* (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set
* this property to <tt>true</tt> if the InfoBox is being used as a map label.
*/
/**
* Creates an InfoBox with the options specified in {@link InfoBoxOptions}.
* Call <tt>InfoBox.open</tt> to add the box to the map.
* @constructor
* @param {InfoBoxOptions} [opt_opts]
*/
function InfoBox(opt_opts) {
opt_opts = opt_opts || {};
google.maps.OverlayView.apply(this, arguments);
// Standard options (in common with google.maps.InfoWindow):
//
this.content_ = opt_opts.content || "";
this.disableAutoPan_ = opt_opts.disableAutoPan || false;
this.maxWidth_ = opt_opts.maxWidth || 0;
this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0);
this.position_ = opt_opts.position || new google.maps.LatLng(0, 0);
this.zIndex_ = opt_opts.zIndex || null;
// Additional options (unique to InfoBox):
//
this.boxClass_ = opt_opts.boxClass || "infoBox";
this.boxStyle_ = opt_opts.boxStyle || {};
this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px";
this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif";
if (opt_opts.closeBoxURL === "") {
this.closeBoxURL_ = "";
}
this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1);
if (typeof opt_opts.visible === "undefined") {
if (typeof opt_opts.isHidden === "undefined") {
opt_opts.visible = true;
} else {
opt_opts.visible = !opt_opts.isHidden;
}
}
this.isHidden_ = !opt_opts.visible;
this.alignBottom_ = opt_opts.alignBottom || false;
this.pane_ = opt_opts.pane || "floatPane";
this.enableEventPropagation_ = opt_opts.enableEventPropagation || false;
this.div_ = null;
this.closeListener_ = null;
this.moveListener_ = null;
this.contextListener_ = null;
this.eventListeners_ = null;
this.fixedWidthSet_ = null;
}
/* InfoBox extends OverlayView in the Google Maps API v3.
*/
InfoBox.prototype = new google.maps.OverlayView();
/**
* Creates the DIV representing the InfoBox.
* @private
*/
InfoBox.prototype.createInfoBoxDiv_ = function () {
var i;
var events;
var bw;
var me = this;
// This handler prevents an event in the InfoBox from being passed on to the map.
//
var cancelHandler = function (e) {
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
// This handler ignores the current event in the InfoBox and conditionally prevents
// the event from being passed on to the map. It is used for the contextmenu event.
//
var ignoreHandler = function (e) {
e.returnValue = false;
if (e.preventDefault) {
e.preventDefault();
}
if (!me.enableEventPropagation_) {
cancelHandler(e);
}
};
if (!this.div_) {
this.div_ = document.createElement("div");
this.setBoxStyle_();
if (typeof this.content_.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + this.content_;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(this.content_);
}
// Add the InfoBox DIV to the DOM
this.getPanes()[this.pane_].appendChild(this.div_);
this.addClickHandler_();
if (this.div_.style.width) {
this.fixedWidthSet_ = true;
} else {
if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) {
this.div_.style.width = this.maxWidth_;
this.div_.style.overflow = "auto";
this.fixedWidthSet_ = true;
} else { // The following code is needed to overcome problems with MSIE
bw = this.getBoxWidths_();
this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px";
this.fixedWidthSet_ = false;
}
}
this.panBox_(this.disableAutoPan_);
if (!this.enableEventPropagation_) {
this.eventListeners_ = [];
// Cancel event propagation.
//
// Note: mousemove not included (to resolve Issue 152)
events = ["mousedown", "mouseover", "mouseout", "mouseup",
"click", "dblclick", "touchstart", "touchend", "touchmove"];
for (i = 0; i < events.length; i++) {
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler));
}
// Workaround for Google bug that causes the cursor to change to a pointer
// when the mouse moves over a marker underneath InfoBox.
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) {
this.style.cursor = "default";
}));
}
this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler);
/**
* This event is fired when the DIV containing the InfoBox's content is attached to the DOM.
* @name InfoBox#domready
* @event
*/
google.maps.event.trigger(this, "domready");
}
};
/**
* Returns the HTML <IMG> tag for the close box.
* @private
*/
InfoBox.prototype.getCloseBoxImg_ = function () {
var img = "";
if (this.closeBoxURL_ !== "") {
img = "<img";
img += " src='" + this.closeBoxURL_ + "'";
img += " align=right"; // Do this because Opera chokes on style='float: right;'
img += " style='";
img += " position: relative;"; // Required by MSIE
img += " cursor: pointer;";
img += " margin: " + this.closeBoxMargin_ + ";";
img += "'>";
}
return img;
};
/**
* Adds the click handler to the InfoBox close box.
* @private
*/
InfoBox.prototype.addClickHandler_ = function () {
var closeBox;
if (this.closeBoxURL_ !== "") {
closeBox = this.div_.firstChild;
this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_());
} else {
this.closeListener_ = null;
}
};
/**
* Returns the function to call when the user clicks the close box of an InfoBox.
* @private
*/
InfoBox.prototype.getCloseClickHandler_ = function () {
var me = this;
return function (e) {
// 1.0.3 fix: Always prevent propagation of a close box click to the map:
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
/**
* This event is fired when the InfoBox's close box is clicked.
* @name InfoBox#closeclick
* @event
*/
google.maps.event.trigger(me, "closeclick");
me.close();
};
};
/**
* Pans the map so that the InfoBox appears entirely within the map's visible area.
* @private
*/
InfoBox.prototype.panBox_ = function (disablePan) {
var map;
var bounds;
var xOffset = 0, yOffset = 0;
if (!disablePan) {
map = this.getMap();
if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama
if (!map.getBounds().contains(this.position_)) {
// Marker not in visible area of map, so set center
// of map to the marker position first.
map.setCenter(this.position_);
}
bounds = map.getBounds();
var mapDiv = map.getDiv();
var mapWidth = mapDiv.offsetWidth;
var mapHeight = mapDiv.offsetHeight;
var iwOffsetX = this.pixelOffset_.width;
var iwOffsetY = this.pixelOffset_.height;
var iwWidth = this.div_.offsetWidth;
var iwHeight = this.div_.offsetHeight;
var padX = this.infoBoxClearance_.width;
var padY = this.infoBoxClearance_.height;
var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_);
if (pixPosition.x < (-iwOffsetX + padX)) {
xOffset = pixPosition.x + iwOffsetX - padX;
} else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) {
xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth;
}
if (this.alignBottom_) {
if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) {
yOffset = pixPosition.y + iwOffsetY - padY - iwHeight;
} else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwOffsetY + padY - mapHeight;
}
} else {
if (pixPosition.y < (-iwOffsetY + padY)) {
yOffset = pixPosition.y + iwOffsetY - padY;
} else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight;
}
}
if (!(xOffset === 0 && yOffset === 0)) {
// Move the map to the shifted center.
//
var c = map.getCenter();
map.panBy(xOffset, yOffset);
}
}
}
};
/**
* Sets the style of the InfoBox by setting the style sheet and applying
* other specific styles requested.
* @private
*/
InfoBox.prototype.setBoxStyle_ = function () {
var i, boxStyle;
if (this.div_) {
// Apply style values from the style sheet defined in the boxClass parameter:
this.div_.className = this.boxClass_;
// Clear existing inline style values:
this.div_.style.cssText = "";
// Apply style values defined in the boxStyle parameter:
boxStyle = this.boxStyle_;
for (i in boxStyle) {
if (boxStyle.hasOwnProperty(i)) {
this.div_.style[i] = boxStyle[i];
}
}
// Fix for iOS disappearing InfoBox problem.
// See http://stackoverflow.com/questions/9229535/google-maps-markers-disappear-at-certain-zoom-level-only-on-iphone-ipad
this.div_.style.WebkitTransform = "translateZ(0)";
// Fix up opacity style for benefit of MSIE:
//
if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") {
// See http://www.quirksmode.org/css/opacity.html
this.div_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (this.div_.style.opacity * 100) + ")\"";
this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")";
}
// Apply required styles:
//
this.div_.style.position = "absolute";
this.div_.style.visibility = 'hidden';
if (this.zIndex_ !== null) {
this.div_.style.zIndex = this.zIndex_;
}
}
};
/**
* Get the widths of the borders of the InfoBox.
* @private
* @return {Object} widths object (top, bottom left, right)
*/
InfoBox.prototype.getBoxWidths_ = function () {
var computedStyle;
var bw = {top: 0, bottom: 0, left: 0, right: 0};
var box = this.div_;
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
}
} else if (document.documentElement.currentStyle) { // MSIE
if (box.currentStyle) {
// The current styles may not be in pixel units, but assume they are (bad!)
bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0;
}
}
return bw;
};
/**
* Invoked when <tt>close</tt> is called. Do not call it directly.
*/
InfoBox.prototype.onRemove = function () {
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Draws the InfoBox based on the current map projection and zoom level.
*/
InfoBox.prototype.draw = function () {
this.createInfoBoxDiv_();
var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_);
this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px";
if (this.alignBottom_) {
this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px";
} else {
this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px";
}
if (this.isHidden_) {
this.div_.style.visibility = "hidden";
} else {
this.div_.style.visibility = "visible";
}
};
/**
* Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>,
* <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt>
* properties have no affect until the current InfoBox is <tt>close</tt>d and a new one
* is <tt>open</tt>ed.
* @param {InfoBoxOptions} opt_opts
*/
InfoBox.prototype.setOptions = function (opt_opts) {
if (typeof opt_opts.boxClass !== "undefined") { // Must be first
this.boxClass_ = opt_opts.boxClass;
this.setBoxStyle_();
}
if (typeof opt_opts.boxStyle !== "undefined") { // Must be second
this.boxStyle_ = opt_opts.boxStyle;
this.setBoxStyle_();
}
if (typeof opt_opts.content !== "undefined") {
this.setContent(opt_opts.content);
}
if (typeof opt_opts.disableAutoPan !== "undefined") {
this.disableAutoPan_ = opt_opts.disableAutoPan;
}
if (typeof opt_opts.maxWidth !== "undefined") {
this.maxWidth_ = opt_opts.maxWidth;
}
if (typeof opt_opts.pixelOffset !== "undefined") {
this.pixelOffset_ = opt_opts.pixelOffset;
}
if (typeof opt_opts.alignBottom !== "undefined") {
this.alignBottom_ = opt_opts.alignBottom;
}
if (typeof opt_opts.position !== "undefined") {
this.setPosition(opt_opts.position);
}
if (typeof opt_opts.zIndex !== "undefined") {
this.setZIndex(opt_opts.zIndex);
}
if (typeof opt_opts.closeBoxMargin !== "undefined") {
this.closeBoxMargin_ = opt_opts.closeBoxMargin;
}
if (typeof opt_opts.closeBoxURL !== "undefined") {
this.closeBoxURL_ = opt_opts.closeBoxURL;
}
if (typeof opt_opts.infoBoxClearance !== "undefined") {
this.infoBoxClearance_ = opt_opts.infoBoxClearance;
}
if (typeof opt_opts.isHidden !== "undefined") {
this.isHidden_ = opt_opts.isHidden;
}
if (typeof opt_opts.visible !== "undefined") {
this.isHidden_ = !opt_opts.visible;
}
if (typeof opt_opts.enableEventPropagation !== "undefined") {
this.enableEventPropagation_ = opt_opts.enableEventPropagation;
}
if (this.div_) {
this.draw();
}
};
/**
* Sets the content of the InfoBox.
* The content can be plain text or an HTML DOM node.
* @param {string|Node} content
*/
InfoBox.prototype.setContent = function (content) {
this.content_ = content;
if (this.div_) {
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
// Odd code required to make things work with MSIE.
//
if (!this.fixedWidthSet_) {
this.div_.style.width = "";
}
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
// Perverse code required to make things work with MSIE.
// (Ensures the close box does, in fact, float to the right.)
//
if (!this.fixedWidthSet_) {
this.div_.style.width = this.div_.offsetWidth + "px";
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
}
this.addClickHandler_();
}
/**
* This event is fired when the content of the InfoBox changes.
* @name InfoBox#content_changed
* @event
*/
google.maps.event.trigger(this, "content_changed");
};
/**
* Sets the geographic location of the InfoBox.
* @param {LatLng} latlng
*/
InfoBox.prototype.setPosition = function (latlng) {
this.position_ = latlng;
if (this.div_) {
this.draw();
}
/**
* This event is fired when the position of the InfoBox changes.
* @name InfoBox#position_changed
* @event
*/
google.maps.event.trigger(this, "position_changed");
};
/**
* Sets the zIndex style for the InfoBox.
* @param {number} index
*/
InfoBox.prototype.setZIndex = function (index) {
this.zIndex_ = index;
if (this.div_) {
this.div_.style.zIndex = index;
}
/**
* This event is fired when the zIndex of the InfoBox changes.
* @name InfoBox#zindex_changed
* @event
*/
google.maps.event.trigger(this, "zindex_changed");
};
/**
* Sets the visibility of the InfoBox.
* @param {boolean} isVisible
*/
InfoBox.prototype.setVisible = function (isVisible) {
this.isHidden_ = !isVisible;
if (this.div_) {
this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible");
}
};
/**
* Returns the content of the InfoBox.
* @returns {string}
*/
InfoBox.prototype.getContent = function () {
return this.content_;
};
/**
* Returns the geographic location of the InfoBox.
* @returns {LatLng}
*/
InfoBox.prototype.getPosition = function () {
return this.position_;
};
/**
* Returns the zIndex for the InfoBox.
* @returns {number}
*/
InfoBox.prototype.getZIndex = function () {
return this.zIndex_;
};
/**
* Returns a flag indicating whether the InfoBox is visible.
* @returns {boolean}
*/
InfoBox.prototype.getVisible = function () {
var isVisible;
if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) {
isVisible = false;
} else {
isVisible = !this.isHidden_;
}
return isVisible;
};
/**
* Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.show = function () {
this.isHidden_ = false;
if (this.div_) {
this.div_.style.visibility = "visible";
}
};
/**
* Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.hide = function () {
this.isHidden_ = true;
if (this.div_) {
this.div_.style.visibility = "hidden";
}
};
/**
* Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt>
* (usually a <tt>google.maps.Marker</tt>) is specified, the position
* of the InfoBox is set to the position of the <tt>anchor</tt>. If the
* anchor is dragged to a new location, the InfoBox moves as well.
* @param {Map|StreetViewPanorama} map
* @param {MVCObject} [anchor]
*/
InfoBox.prototype.open = function (map, anchor) {
var me = this;
if (anchor) {
this.position_ = anchor.getPosition();
this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () {
me.setPosition(this.getPosition());
});
}
this.setMap(map);
if (this.div_) {
this.panBox_();
}
};
/**
* Removes the InfoBox from the map.
*/
InfoBox.prototype.close = function () {
var i;
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
if (this.eventListeners_) {
for (i = 0; i < this.eventListeners_.length; i++) {
google.maps.event.removeListener(this.eventListeners_[i]);
}
this.eventListeners_ = null;
}
if (this.moveListener_) {
google.maps.event.removeListener(this.moveListener_);
this.moveListener_ = null;
}
if (this.contextListener_) {
google.maps.event.removeListener(this.contextListener_);
this.contextListener_ = null;
}
this.setMap(null);
};
/**
* @name KeyDragZoom for V3
* @version 2.0.9 [December 17, 2012] NOT YET RELEASED
* @author: Nianwei Liu [nianwei at gmail dot com] & Gary Little [gary at luxcentral dot com]
* @fileoverview This library adds a drag zoom capability to a V3 Google map.
* When drag zoom is enabled, holding down a designated hot key <code>(shift | ctrl | alt)</code>
* while dragging a box around an area of interest will zoom the map in to that area when
* the mouse button is released. Optionally, a visual control can also be supplied for turning
* a drag zoom operation on and off.
* Only one line of code is needed: <code>google.maps.Map.enableKeyDragZoom();</code>
* <p>
* NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,
* it causes a context menu to appear when running on the Macintosh.
* <p>
* Note that if the map's container has a border around it, the border widths must be specified
* in pixel units (or as thin, medium, or thick). This is required because of an MSIE limitation.
* <p>NL: 2009-05-28: initial port to core API V3.
* <br>NL: 2009-11-02: added a temp fix for -moz-transform for FF3.5.x using code from Paul Kulchenko (http://notebook.kulchenko.com/maps/gridmove).
* <br>NL: 2010-02-02: added a fix for IE flickering on divs onmousemove, caused by scroll value when get mouse position.
* <br>GL: 2010-06-15: added a visual control option.
*/
/*!
*
* 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 () {
/*jslint browser:true */
/*global window,google */
/* Utility functions use "var funName=function()" syntax to allow use of the */
/* Dean Edwards Packer compression tool (with Shrink variables, without Base62 encode). */
/**
* Converts "thin", "medium", and "thick" to pixel widths
* in an MSIE environment. Not called for other browsers
* because getComputedStyle() returns pixel widths automatically.
* @param {string} widthValue The value of the border width parameter.
*/
var toPixels = function (widthValue) {
var px;
switch (widthValue) {
case "thin":
px = "2px";
break;
case "medium":
px = "4px";
break;
case "thick":
px = "6px";
break;
default:
px = widthValue;
}
return px;
};
/**
* Get the widths of the borders of an HTML element.
*
* @param {Node} h The HTML element.
* @return {Object} The width object {top, bottom left, right}.
*/
var getBorderWidths = function (h) {
var computedStyle;
var bw = {};
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
return bw;
}
} else if (document.documentElement.currentStyle) { // MSIE
if (h.currentStyle) {
// The current styles may not be in pixel units so try to convert (bad!)
bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0;
bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0;
bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0;
bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0;
return bw;
}
}
// Shouldn't get this far for any modern browser
bw.top = parseInt(h.style["border-top-width"], 10) || 0;
bw.bottom = parseInt(h.style["border-bottom-width"], 10) || 0;
bw.left = parseInt(h.style["border-left-width"], 10) || 0;
bw.right = parseInt(h.style["border-right-width"], 10) || 0;
return bw;
};
// Page scroll values for use by getMousePosition. To prevent flickering on MSIE
// they are calculated only when the document actually scrolls, not every time the
// mouse moves (as they would be if they were calculated inside getMousePosition).
var scroll = {
x: 0,
y: 0
};
var getScrollValue = function (e) {
scroll.x = (typeof document.documentElement.scrollLeft !== "undefined" ? document.documentElement.scrollLeft : document.body.scrollLeft);
scroll.y = (typeof document.documentElement.scrollTop !== "undefined" ? document.documentElement.scrollTop : document.body.scrollTop);
};
getScrollValue();
/**
* Get the position of the mouse relative to the document.
* @param {Event} e The mouse event.
* @return {Object} The position object {left, top}.
*/
var getMousePosition = function (e) {
var posX = 0, posY = 0;
e = e || window.event;
if (typeof e.pageX !== "undefined") {
posX = e.pageX;
posY = e.pageY;
} else if (typeof e.clientX !== "undefined") { // MSIE
posX = e.clientX + scroll.x;
posY = e.clientY + scroll.y;
}
return {
left: posX,
top: posY
};
};
/**
* Get the position of an HTML element relative to the document.
* @param {Node} h The HTML element.
* @return {Object} The position object {left, top}.
*/
var getElementPosition = function (h) {
var posX = h.offsetLeft;
var posY = h.offsetTop;
var parent = h.offsetParent;
// Add offsets for all ancestors in the hierarchy
while (parent !== null) {
// Adjust for scrolling elements which may affect the map position.
//
// See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific
//
// "...make sure that every element [on a Web page] with an overflow
// of anything other than visible also has a position style set to
// something other than the default static..."
if (parent !== document.body && parent !== document.documentElement) {
posX -= parent.scrollLeft;
posY -= parent.scrollTop;
}
// See http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/4cb86c0c1037a5e5
// Example: http://notebook.kulchenko.com/maps/gridmove
var m = parent;
// This is the "normal" way to get offset information:
var moffx = m.offsetLeft;
var moffy = m.offsetTop;
// This covers those cases where a transform is used:
if (!moffx && !moffy && window.getComputedStyle) {
var matrix = document.defaultView.getComputedStyle(m, null).MozTransform ||
document.defaultView.getComputedStyle(m, null).WebkitTransform;
if (matrix) {
if (typeof matrix === "string") {
var parms = matrix.split(",");
moffx += parseInt(parms[4], 10) || 0;
moffy += parseInt(parms[5], 10) || 0;
}
}
}
posX += moffx;
posY += moffy;
parent = parent.offsetParent;
}
return {
left: posX,
top: posY
};
};
/**
* Set the properties of an object to those from another object.
* @param {Object} obj The target object.
* @param {Object} vals The source object.
*/
var setVals = function (obj, vals) {
if (obj && vals) {
for (var x in vals) {
if (vals.hasOwnProperty(x)) {
obj[x] = vals[x];
}
}
}
return obj;
};
/**
* Set the opacity. If op is not passed in, this function just performs an MSIE fix.
* @param {Node} h The HTML element.
* @param {number} op The opacity value (0-1).
*/
var setOpacity = function (h, op) {
if (typeof op !== "undefined") {
h.style.opacity = op;
}
if (typeof h.style.opacity !== "undefined" && h.style.opacity !== "") {
h.style.filter = "alpha(opacity=" + (h.style.opacity * 100) + ")";
}
};
/**
* @name KeyDragZoomOptions
* @class This class represents the optional parameter passed into <code>google.maps.Map.enableKeyDragZoom</code>.
* @property {string} [key="shift"] The hot key to hold down to activate a drag zoom, <code>shift | ctrl | alt</code>.
* NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2,
* it causes a context menu to appear when running on the Macintosh. Also note that the
* <code>alt</code> hot key refers to the Option key on a Macintosh.
* @property {Object} [boxStyle={border: "4px solid #736AFF"}]
* An object literal defining the CSS styles of the zoom box.
* Border widths must be specified in pixel units (or as thin, medium, or thick).
* @property {Object} [veilStyle={backgroundColor: "gray", opacity: 0.25, cursor: "crosshair"}]
* An object literal defining the CSS styles of the veil pane which covers the map when a drag
* zoom is activated. The previous name for this property was <code>paneStyle</code> but the use
* of this name is now deprecated.
* @property {boolean} [noZoom=false] A flag indicating whether to disable zooming after an area is
* selected. Set this to <code>true</code> to allow KeyDragZoom to be used as a simple area
* selection tool.
* @property {boolean} [visualEnabled=false] A flag indicating whether a visual control is to be used.
* @property {string} [visualClass=""] The name of the CSS class defining the styles for the visual
* control. To prevent the visual control from being printed, set this property to the name of
* a class, defined inside a <code>@media print</code> rule, which sets the CSS
* <code>display</code> style to <code>none</code>.
* @property {ControlPosition} [visualPosition=google.maps.ControlPosition.LEFT_TOP]
* The position of the visual control.
* @property {Size} [visualPositionOffset=google.maps.Size(35, 0)] The width and height values
* provided by this property are the offsets (in pixels) from the location at which the control
* would normally be drawn to the desired drawing location.
* @property {number} [visualPositionIndex=null] The index of the visual control.
* The index is for controlling the placement of the control relative to other controls at the
* position given by <code>visualPosition</code>; controls with a lower index are placed first.
* Use a negative value to place the control <i>before</i> any default controls. No index is
* generally required.
* @property {String} [visualSprite="http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"]
* The URL of the sprite image used for showing the visual control in the on, off, and hot
* (i.e., when the mouse is over the control) states. The three images within the sprite must
* be the same size and arranged in on-hot-off order in a single row with no spaces between images.
* @property {Size} [visualSize=google.maps.Size(20, 20)] The width and height values provided by
* this property are the size (in pixels) of each of the images within <code>visualSprite</code>.
* @property {Object} [visualTips={off: "Turn on drag zoom mode", on: "Turn off drag zoom mode"}]
* An object literal defining the help tips that appear when
* the mouse moves over the visual control. The <code>off</code> property is the tip to be shown
* when the control is off and the <code>on</code> property is the tip to be shown when the
* control is on.
*/
/**
* @name DragZoom
* @class This class represents a drag zoom object for a map. The object is activated by holding down the hot key
* or by turning on the visual control.
* This object is created when <code>google.maps.Map.enableKeyDragZoom</code> is called; it cannot be created directly.
* Use <code>google.maps.Map.getDragZoomObject</code> to gain access to this object in order to attach event listeners.
* @param {Map} map The map to which the DragZoom object is to be attached.
* @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.
*/
function DragZoom(map, opt_zoomOpts) {
var me = this;
var ov = new google.maps.OverlayView();
ov.onAdd = function () {
me.init_(map, opt_zoomOpts);
};
ov.draw = function () {
};
ov.onRemove = function () {
};
ov.setMap(map);
this.prjov_ = ov;
}
/**
* Initialize the tool.
* @param {Map} map The map to which the DragZoom object is to be attached.
* @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters.
*/
DragZoom.prototype.init_ = function (map, opt_zoomOpts) {
var i;
var me = this;
this.map_ = map;
opt_zoomOpts = opt_zoomOpts || {};
this.key_ = opt_zoomOpts.key || "shift";
this.key_ = this.key_.toLowerCase();
this.borderWidths_ = getBorderWidths(this.map_.getDiv());
this.veilDiv_ = [];
for (i = 0; i < 4; i++) {
this.veilDiv_[i] = document.createElement("div");
// Prevents selection of other elements on the webpage
// when a drag zoom operation is in progress:
this.veilDiv_[i].onselectstart = function () {
return false;
};
// Apply default style values for the veil:
setVals(this.veilDiv_[i].style, {
backgroundColor: "gray",
opacity: 0.25,
cursor: "crosshair"
});
// Apply style values specified in veilStyle parameter:
setVals(this.veilDiv_[i].style, opt_zoomOpts.paneStyle); // Old option name was "paneStyle"
setVals(this.veilDiv_[i].style, opt_zoomOpts.veilStyle); // New name is "veilStyle"
// Apply mandatory style values:
setVals(this.veilDiv_[i].style, {
position: "absolute",
overflow: "hidden",
display: "none"
});
// Workaround for Firefox Shift-Click problem:
if (this.key_ === "shift") {
this.veilDiv_[i].style.MozUserSelect = "none";
}
setOpacity(this.veilDiv_[i]);
// An IE fix: If the background is transparent it cannot capture mousedown
// events, so if it is, change the background to white with 0 opacity.
if (this.veilDiv_[i].style.backgroundColor === "transparent") {
this.veilDiv_[i].style.backgroundColor = "white";
setOpacity(this.veilDiv_[i], 0);
}
this.map_.getDiv().appendChild(this.veilDiv_[i]);
}
this.noZoom_ = opt_zoomOpts.noZoom || false;
this.visualEnabled_ = opt_zoomOpts.visualEnabled || false;
this.visualClass_ = opt_zoomOpts.visualClass || "";
this.visualPosition_ = opt_zoomOpts.visualPosition || google.maps.ControlPosition.LEFT_TOP;
this.visualPositionOffset_ = opt_zoomOpts.visualPositionOffset || new google.maps.Size(35, 0);
this.visualPositionIndex_ = opt_zoomOpts.visualPositionIndex || null;
this.visualSprite_ = opt_zoomOpts.visualSprite || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png";
this.visualSize_ = opt_zoomOpts.visualSize || new google.maps.Size(20, 20);
this.visualTips_ = opt_zoomOpts.visualTips || {};
this.visualTips_.off = this.visualTips_.off || "Turn on drag zoom mode";
this.visualTips_.on = this.visualTips_.on || "Turn off drag zoom mode";
this.boxDiv_ = document.createElement("div");
// Apply default style values for the zoom box:
setVals(this.boxDiv_.style, {
border: "4px solid #736AFF"
});
// Apply style values specified in boxStyle parameter:
setVals(this.boxDiv_.style, opt_zoomOpts.boxStyle);
// Apply mandatory style values:
setVals(this.boxDiv_.style, {
position: "absolute",
display: "none"
});
setOpacity(this.boxDiv_);
this.map_.getDiv().appendChild(this.boxDiv_);
this.boxBorderWidths_ = getBorderWidths(this.boxDiv_);
this.listeners_ = [
google.maps.event.addDomListener(document, "keydown", function (e) {
me.onKeyDown_(e);
}),
google.maps.event.addDomListener(document, "keyup", function (e) {
me.onKeyUp_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[0], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[1], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[2], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(this.veilDiv_[3], "mousedown", function (e) {
me.onMouseDown_(e);
}),
google.maps.event.addDomListener(document, "mousedown", function (e) {
me.onMouseDownDocument_(e);
}),
google.maps.event.addDomListener(document, "mousemove", function (e) {
me.onMouseMove_(e);
}),
google.maps.event.addDomListener(document, "mouseup", function (e) {
me.onMouseUp_(e);
}),
google.maps.event.addDomListener(window, "scroll", getScrollValue)
];
this.hotKeyDown_ = false;
this.mouseDown_ = false;
this.dragging_ = false;
this.startPt_ = null;
this.endPt_ = null;
this.mapWidth_ = null;
this.mapHeight_ = null;
this.mousePosn_ = null;
this.mapPosn_ = null;
if (this.visualEnabled_) {
this.buttonDiv_ = this.initControl_(this.visualPositionOffset_);
if (this.visualPositionIndex_ !== null) {
this.buttonDiv_.index = this.visualPositionIndex_;
}
this.map_.controls[this.visualPosition_].push(this.buttonDiv_);
this.controlIndex_ = this.map_.controls[this.visualPosition_].length - 1;
}
};
/**
* Initializes the visual control and returns its DOM element.
* @param {Size} offset The offset of the control from its normal position.
* @return {Node} The DOM element containing the visual control.
*/
DragZoom.prototype.initControl_ = function (offset) {
var control;
var image;
var me = this;
control = document.createElement("div");
control.className = this.visualClass_;
control.style.position = "relative";
control.style.overflow = "hidden";
control.style.height = this.visualSize_.height + "px";
control.style.width = this.visualSize_.width + "px";
control.title = this.visualTips_.off;
image = document.createElement("img");
image.src = this.visualSprite_;
image.style.position = "absolute";
image.style.left = -(this.visualSize_.width * 2) + "px";
image.style.top = 0 + "px";
control.appendChild(image);
control.onclick = function (e) {
me.hotKeyDown_ = !me.hotKeyDown_;
if (me.hotKeyDown_) {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px";
me.buttonDiv_.title = me.visualTips_.on;
me.activatedByControl_ = true;
google.maps.event.trigger(me, "activate");
} else {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px";
me.buttonDiv_.title = me.visualTips_.off;
google.maps.event.trigger(me, "deactivate");
}
me.onMouseMove_(e); // Updates the veil
};
control.onmouseover = function () {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 1) + "px";
};
control.onmouseout = function () {
if (me.hotKeyDown_) {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px";
me.buttonDiv_.title = me.visualTips_.on;
} else {
me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px";
me.buttonDiv_.title = me.visualTips_.off;
}
};
control.ondragstart = function () {
return false;
};
setVals(control.style, {
cursor: "pointer",
marginTop: offset.height + "px",
marginLeft: offset.width + "px"
});
return control;
};
/**
* Returns <code>true</code> if the hot key is being pressed when an event occurs.
* @param {Event} e The keyboard event.
* @return {boolean} Flag indicating whether the hot key is down.
*/
DragZoom.prototype.isHotKeyDown_ = function (e) {
var isHot;
e = e || window.event;
isHot = (e.shiftKey && this.key_ === "shift") || (e.altKey && this.key_ === "alt") || (e.ctrlKey && this.key_ === "ctrl");
if (!isHot) {
// Need to look at keyCode for Opera because it
// doesn't set the shiftKey, altKey, ctrlKey properties
// unless a non-modifier event is being reported.
//
// See http://cross-browser.com/x/examples/shift_mode.php
// Also see http://unixpapa.com/js/key.html
switch (e.keyCode) {
case 16:
if (this.key_ === "shift") {
isHot = true;
}
break;
case 17:
if (this.key_ === "ctrl") {
isHot = true;
}
break;
case 18:
if (this.key_ === "alt") {
isHot = true;
}
break;
}
}
return isHot;
};
/**
* Returns <code>true</code> if the mouse is on top of the map div.
* The position is captured in onMouseMove_.
* @return {boolean}
*/
DragZoom.prototype.isMouseOnMap_ = function () {
var mousePosn = this.mousePosn_;
if (mousePosn) {
var mapPosn = this.mapPosn_;
var mapDiv = this.map_.getDiv();
return mousePosn.left > mapPosn.left && mousePosn.left < (mapPosn.left + mapDiv.offsetWidth) &&
mousePosn.top > mapPosn.top && mousePosn.top < (mapPosn.top + mapDiv.offsetHeight);
} else {
// if user never moved mouse
return false;
}
};
/**
* Show the veil if the hot key is down and the mouse is over the map,
* otherwise hide the veil.
*/
DragZoom.prototype.setVeilVisibility_ = function () {
var i;
if (this.map_ && this.hotKeyDown_ && this.isMouseOnMap_()) {
var mapDiv = this.map_.getDiv();
this.mapWidth_ = mapDiv.offsetWidth - (this.borderWidths_.left + this.borderWidths_.right);
this.mapHeight_ = mapDiv.offsetHeight - (this.borderWidths_.top + this.borderWidths_.bottom);
if (this.activatedByControl_) { // Veil covers entire map (except control)
var left = parseInt(this.buttonDiv_.style.left, 10) + this.visualPositionOffset_.width;
var top = parseInt(this.buttonDiv_.style.top, 10) + this.visualPositionOffset_.height;
var width = this.visualSize_.width;
var height = this.visualSize_.height;
// Left veil rectangle:
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.width = left + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
// Right veil rectangle:
this.veilDiv_[1].style.top = "0px";
this.veilDiv_[1].style.left = (left + width) + "px";
this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px";
this.veilDiv_[1].style.height = this.mapHeight_ + "px";
// Top veil rectangle:
this.veilDiv_[2].style.top = "0px";
this.veilDiv_[2].style.left = left + "px";
this.veilDiv_[2].style.width = width + "px";
this.veilDiv_[2].style.height = top + "px";
// Bottom veil rectangle:
this.veilDiv_[3].style.top = (top + height) + "px";
this.veilDiv_[3].style.left = left + "px";
this.veilDiv_[3].style.width = width + "px";
this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px";
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "block";
}
} else {
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.width = this.mapWidth_ + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
for (i = 1; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.width = "0px";
this.veilDiv_[i].style.height = "0px";
}
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "block";
}
}
} else {
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "none";
}
}
};
/**
* Handle key down. Show the veil if the hot key has been pressed.
* @param {Event} e The keyboard event.
*/
DragZoom.prototype.onKeyDown_ = function (e) {
if (this.map_ && !this.hotKeyDown_ && this.isHotKeyDown_(e)) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.hotKeyDown_ = true;
this.activatedByControl_ = false;
this.setVeilVisibility_();
/**
* This event is fired when the hot key is pressed.
* @name DragZoom#activate
* @event
*/
google.maps.event.trigger(this, "activate");
}
};
/**
* Get the <code>google.maps.Point</code> of the mouse position.
* @param {Event} e The mouse event.
* @return {Point} The mouse position.
*/
DragZoom.prototype.getMousePoint_ = function (e) {
var mousePosn = getMousePosition(e);
var p = new google.maps.Point();
p.x = mousePosn.left - this.mapPosn_.left - this.borderWidths_.left;
p.y = mousePosn.top - this.mapPosn_.top - this.borderWidths_.top;
p.x = Math.min(p.x, this.mapWidth_);
p.y = Math.min(p.y, this.mapHeight_);
p.x = Math.max(p.x, 0);
p.y = Math.max(p.y, 0);
return p;
};
/**
* Handle mouse down.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseDown_ = function (e) {
if (this.map_ && this.hotKeyDown_) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.dragging_ = true;
this.startPt_ = this.endPt_ = this.getMousePoint_(e);
this.boxDiv_.style.width = this.boxDiv_.style.height = "0px";
var prj = this.prjov_.getProjection();
var latlng = prj.fromContainerPixelToLatLng(this.startPt_);
/**
* This event is fired when the drag operation begins.
* The parameter passed is the geographic position of the starting point.
* @name DragZoom#dragstart
* @param {LatLng} latlng The geographic position of the starting point.
* @event
*/
google.maps.event.trigger(this, "dragstart", latlng);
}
};
/**
* Handle mouse down at the document level.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseDownDocument_ = function (e) {
this.mouseDown_ = true;
};
/**
* Handle mouse move.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseMove_ = function (e) {
this.mousePosn_ = getMousePosition(e);
if (this.dragging_) {
this.endPt_ = this.getMousePoint_(e);
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
// For benefit of MSIE 7/8 ensure following values are not negative:
var boxWidth = Math.max(0, width - (this.boxBorderWidths_.left + this.boxBorderWidths_.right));
var boxHeight = Math.max(0, height - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom));
// Left veil rectangle:
this.veilDiv_[0].style.top = "0px";
this.veilDiv_[0].style.left = "0px";
this.veilDiv_[0].style.width = left + "px";
this.veilDiv_[0].style.height = this.mapHeight_ + "px";
// Right veil rectangle:
this.veilDiv_[1].style.top = "0px";
this.veilDiv_[1].style.left = (left + width) + "px";
this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px";
this.veilDiv_[1].style.height = this.mapHeight_ + "px";
// Top veil rectangle:
this.veilDiv_[2].style.top = "0px";
this.veilDiv_[2].style.left = left + "px";
this.veilDiv_[2].style.width = width + "px";
this.veilDiv_[2].style.height = top + "px";
// Bottom veil rectangle:
this.veilDiv_[3].style.top = (top + height) + "px";
this.veilDiv_[3].style.left = left + "px";
this.veilDiv_[3].style.width = width + "px";
this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px";
// Selection rectangle:
this.boxDiv_.style.top = top + "px";
this.boxDiv_.style.left = left + "px";
this.boxDiv_.style.width = boxWidth + "px";
this.boxDiv_.style.height = boxHeight + "px";
this.boxDiv_.style.display = "block";
/**
* This event is fired repeatedly while the user drags a box across the area of interest.
* The southwest and northeast point are passed as parameters of type <code>google.maps.Point</code>
* (for performance reasons), relative to the map container. Also passed is the projection object
* so that the event listener, if necessary, can convert the pixel positions to geographic
* coordinates using <code>google.maps.MapCanvasProjection.fromContainerPixelToLatLng</code>.
* @name DragZoom#drag
* @param {Point} southwestPixel The southwest point of the selection area.
* @param {Point} northeastPixel The northeast point of the selection area.
* @param {MapCanvasProjection} prj The projection object.
* @event
*/
google.maps.event.trigger(this, "drag", new google.maps.Point(left, top + height), new google.maps.Point(left + width, top), this.prjov_.getProjection());
} else if (!this.mouseDown_) {
this.mapPosn_ = getElementPosition(this.map_.getDiv());
this.setVeilVisibility_();
}
};
/**
* Handle mouse up.
* @param {Event} e The mouse event.
*/
DragZoom.prototype.onMouseUp_ = function (e) {
var z;
var me = this;
this.mouseDown_ = false;
if (this.dragging_) {
if ((this.getMousePoint_(e).x === this.startPt_.x) && (this.getMousePoint_(e).y === this.startPt_.y)) {
this.onKeyUp_(e); // Cancel event
return;
}
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
// Google Maps API bug: setCenter() doesn't work as expected if the map has a
// border on the left or top. The code here includes a workaround for this problem.
var kGoogleCenteringBug = true;
if (kGoogleCenteringBug) {
left += this.borderWidths_.left;
top += this.borderWidths_.top;
}
var prj = this.prjov_.getProjection();
var sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));
var ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));
var bnds = new google.maps.LatLngBounds(sw, ne);
if (this.noZoom_) {
this.boxDiv_.style.display = "none";
} else {
// Sometimes fitBounds causes a zoom OUT, so restore original zoom level if this happens.
z = this.map_.getZoom();
this.map_.fitBounds(bnds);
if (this.map_.getZoom() < z) {
this.map_.setZoom(z);
}
// Redraw box after zoom:
var swPt = prj.fromLatLngToContainerPixel(sw);
var nePt = prj.fromLatLngToContainerPixel(ne);
if (kGoogleCenteringBug) {
swPt.x -= this.borderWidths_.left;
swPt.y -= this.borderWidths_.top;
nePt.x -= this.borderWidths_.left;
nePt.y -= this.borderWidths_.top;
}
this.boxDiv_.style.left = swPt.x + "px";
this.boxDiv_.style.top = nePt.y + "px";
this.boxDiv_.style.width = (Math.abs(nePt.x - swPt.x) - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)) + "px";
this.boxDiv_.style.height = (Math.abs(nePt.y - swPt.y) - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)) + "px";
// Hide box asynchronously after 1 second:
setTimeout(function () {
me.boxDiv_.style.display = "none";
}, 1000);
}
this.dragging_ = false;
this.onMouseMove_(e); // Updates the veil
/**
* This event is fired when the drag operation ends.
* The parameter passed is the geographic bounds of the selected area.
* Note that this event is <i>not</i> fired if the hot key is released before the drag operation ends.
* @name DragZoom#dragend
* @param {LatLngBounds} bnds The geographic bounds of the selected area.
* @event
*/
google.maps.event.trigger(this, "dragend", bnds);
// if the hot key isn't down, the drag zoom must have been activated by turning
// on the visual control. In this case, finish up by simulating a key up event.
if (!this.isHotKeyDown_(e)) {
this.onKeyUp_(e);
}
}
};
/**
* Handle key up.
* @param {Event} e The keyboard event.
*/
DragZoom.prototype.onKeyUp_ = function (e) {
var i;
var left, top, width, height, prj, sw, ne;
var bnds = null;
if (this.map_ && this.hotKeyDown_) {
this.hotKeyDown_ = false;
if (this.dragging_) {
this.boxDiv_.style.display = "none";
this.dragging_ = false;
// Calculate the bounds when drag zoom was cancelled
left = Math.min(this.startPt_.x, this.endPt_.x);
top = Math.min(this.startPt_.y, this.endPt_.y);
width = Math.abs(this.startPt_.x - this.endPt_.x);
height = Math.abs(this.startPt_.y - this.endPt_.y);
prj = this.prjov_.getProjection();
sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height));
ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top));
bnds = new google.maps.LatLngBounds(sw, ne);
}
for (i = 0; i < this.veilDiv_.length; i++) {
this.veilDiv_[i].style.display = "none";
}
if (this.visualEnabled_) {
this.buttonDiv_.firstChild.style.left = -(this.visualSize_.width * 2) + "px";
this.buttonDiv_.title = this.visualTips_.off;
this.buttonDiv_.style.display = "";
}
/**
* This event is fired when the hot key is released.
* The parameter passed is the geographic bounds of the selected area immediately
* before the hot key was released.
* @name DragZoom#deactivate
* @param {LatLngBounds} bnds The geographic bounds of the selected area immediately
* before the hot key was released.
* @event
*/
google.maps.event.trigger(this, "deactivate", bnds);
}
};
/**
* @name google.maps.Map
* @class These are new methods added to the Google Maps JavaScript API V3's
* <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#Map">Map</a>
* class.
*/
/**
* Enables drag zoom. The user can zoom to an area of interest by holding down the hot key
* <code>(shift | ctrl | alt )</code> while dragging a box around the area or by turning
* on the visual control then dragging a box around the area.
* @param {KeyDragZoomOptions} opt_zoomOpts The optional parameters.
*/
google.maps.Map.prototype.enableKeyDragZoom = function (opt_zoomOpts) {
this.dragZoom_ = new DragZoom(this, opt_zoomOpts);
};
/**
* Disables drag zoom.
*/
google.maps.Map.prototype.disableKeyDragZoom = function () {
var i;
var d = this.dragZoom_;
if (d) {
for (i = 0; i < d.listeners_.length; ++i) {
google.maps.event.removeListener(d.listeners_[i]);
}
this.getDiv().removeChild(d.boxDiv_);
for (i = 0; i < d.veilDiv_.length; i++) {
this.getDiv().removeChild(d.veilDiv_[i]);
}
if (d.visualEnabled_) {
// Remove the custom control:
this.controls[d.visualPosition_].removeAt(d.controlIndex_);
}
d.prjov_.setMap(null);
this.dragZoom_ = null;
}
};
/**
* Returns <code>true</code> if the drag zoom feature has been enabled.
* @return {boolean}
*/
google.maps.Map.prototype.keyDragZoomEnabled = function () {
return this.dragZoom_ !== null;
};
/**
* Returns the DragZoom object which is created when <code>google.maps.Map.enableKeyDragZoom</code> is called.
* With this object you can use <code>google.maps.event.addListener</code> to attach event listeners
* for the "activate", "deactivate", "dragstart", "drag", and "dragend" events.
* @return {DragZoom}
*/
google.maps.Map.prototype.getDragZoomObject = function () {
return this.dragZoom_;
};
})();
/**
* @name MarkerClustererPlus for Google Maps V3
* @version 2.1.1 [November 4, 2013]
* @author Gary Little
* @fileoverview
* The library creates and manages per-zoom-level clusters for large amounts of markers.
* <p>
* This is an enhanced V3 implementation of the
* <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/"
* >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the
* <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/"
* >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little.
* <p>
* v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It
* adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>,
* and <code>calculator</code> properties as well as support for four more events. It also allows
* greater control over the styling of the text that appears on the cluster marker. The
* documentation has been significantly improved and the overall code has been simplified and
* polished. Very large numbers of markers can now be managed without causing Javascript timeout
* errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been
* deprecated. The new name is <code>click</code>, so please change your application code now.
*/
/**
* 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.
*/
/**
* @name ClusterIconStyle
* @class This class represents the object for values in the <code>styles</code> array passed
* to the {@link MarkerClusterer} constructor. The element in this array that is used to
* style the cluster icon is determined by calling the <code>calculator</code> function.
*
* @property {string} url The URL of the cluster icon image file. Required.
* @property {number} height The display height (in pixels) of the cluster icon. Required.
* @property {number} width The display width (in pixels) of the cluster icon. Required.
* @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to
* where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code>
* where <code>yoffset</code> increases as you go down from center and <code>xoffset</code>
* increases to the right of center. The default is <code>[0, 0]</code>.
* @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the
* spot on the cluster icon that is to be aligned with the cluster position. The format is
* <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and
* <code>xoffset</code> increases to the right of the top-left corner of the icon. The default
* anchor position is the center of the cluster icon.
* @property {string} [textColor="black"] The color of the label text shown on the
* cluster icon.
* @property {number} [textSize=11] The size (in pixels) of the label text shown on the
* cluster icon.
* @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code>
* property for the label text shown on the cluster icon.
* @property {string} [backgroundPosition="0 0"] The position of the cluster icon image
* within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code>
* (the same format as for the CSS <code>background-position</code> property). You must set
* this property appropriately when the image defined by <code>url</code> represents a sprite
* containing multiple images. Note that the position <i>must</i> be specified in px units.
*/
/**
* @name ClusterIconInfo
* @class This class is an object containing general information about a cluster icon. This is
* the object that a <code>calculator</code> function returns.
*
* @property {string} text The text of the label to be shown on the cluster icon.
* @property {number} index The index plus 1 of the element in the <code>styles</code>
* array to be used to style the cluster icon.
* @property {string} title The tooltip to display when the mouse moves over the cluster icon.
* If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the
* value of the <code>title</code> property passed to the MarkerClusterer.
*/
/**
* A cluster icon.
*
* @constructor
* @extends google.maps.OverlayView
* @param {Cluster} cluster The cluster with which the icon is to be associated.
* @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons
* to use for various cluster sizes.
* @private
*/
function ClusterIcon(cluster, styles) {
cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);
this.cluster_ = cluster;
this.className_ = cluster.getMarkerClusterer().getClusterClass();
this.styles_ = styles;
this.center_ = null;
this.div_ = null;
this.sums_ = null;
this.visible_ = false;
this.setMap(cluster.getMap()); // Note: this causes onAdd to be called
}
/**
* Adds the icon to the DOM.
*/
ClusterIcon.prototype.onAdd = function () {
var cClusterIcon = this;
var cMouseDownInCluster;
var cDraggingMapByCluster;
this.div_ = document.createElement("div");
this.div_.className = this.className_;
if (this.visible_) {
this.show();
}
this.getPanes().overlayMouseTarget.appendChild(this.div_);
// Fix for Issue 157
this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () {
cDraggingMapByCluster = cMouseDownInCluster;
});
google.maps.event.addDomListener(this.div_, "mousedown", function () {
cMouseDownInCluster = true;
cDraggingMapByCluster = false;
});
google.maps.event.addDomListener(this.div_, "click", function (e) {
cMouseDownInCluster = false;
if (!cDraggingMapByCluster) {
var theBounds;
var mz;
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when a cluster marker is clicked.
* @name MarkerClusterer#click
* @param {Cluster} c The cluster that was clicked.
* @event
*/
google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
// The default click handler follows. Disable it by setting
// the zoomOnClick property to false.
if (mc.getZoomOnClick()) {
// Zoom into the cluster.
mz = mc.getMaxZoom();
theBounds = cClusterIcon.cluster_.getBounds();
mc.getMap().fitBounds(theBounds);
// There is a fix for Issue 170 here:
setTimeout(function () {
mc.getMap().fitBounds(theBounds);
// Don't zoom beyond the max zoom level
if (mz !== null && (mc.getMap().getZoom() > mz)) {
mc.getMap().setZoom(mz + 1);
}
}, 100);
}
// Prevent event propagation to the map:
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
}
});
google.maps.event.addDomListener(this.div_, "mouseover", function () {
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when the mouse moves over a cluster marker.
* @name MarkerClusterer#mouseover
* @param {Cluster} c The cluster that the mouse moved over.
* @event
*/
google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_);
});
google.maps.event.addDomListener(this.div_, "mouseout", function () {
var mc = cClusterIcon.cluster_.getMarkerClusterer();
/**
* This event is fired when the mouse moves out of a cluster marker.
* @name MarkerClusterer#mouseout
* @param {Cluster} c The cluster that the mouse moved out of.
* @event
*/
google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_);
});
};
/**
* Removes the icon from the DOM.
*/
ClusterIcon.prototype.onRemove = function () {
if (this.div_ && this.div_.parentNode) {
this.hide();
google.maps.event.removeListener(this.boundsChangedListener_);
google.maps.event.clearInstanceListeners(this.div_);
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Draws the icon.
*/
ClusterIcon.prototype.draw = function () {
if (this.visible_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.top = pos.y + "px";
this.div_.style.left = pos.x + "px";
}
};
/**
* Hides the icon.
*/
ClusterIcon.prototype.hide = function () {
if (this.div_) {
this.div_.style.display = "none";
}
this.visible_ = false;
};
/**
* Positions and shows the icon.
*/
ClusterIcon.prototype.show = function () {
if (this.div_) {
var img = "";
// NOTE: values must be specified in px units
var bp = this.backgroundPosition_.split(" ");
var spriteH = parseInt(bp[0].trim(), 10);
var spriteV = parseInt(bp[1].trim(), 10);
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
}
img += "'>";
this.div_.innerHTML = img + "<div style='" +
"position: absolute;" +
"top: " + this.anchorText_[0] + "px;" +
"left: " + this.anchorText_[1] + "px;" +
"color: " + this.textColor_ + ";" +
"font-size: " + this.textSize_ + "px;" +
"font-family: " + this.fontFamily_ + ";" +
"font-weight: " + this.fontWeight_ + ";" +
"font-style: " + this.fontStyle_ + ";" +
"text-decoration: " + this.textDecoration_ + ";" +
"text-align: center;" +
"width: " + this.width_ + "px;" +
"line-height:" + this.height_ + "px;" +
"'>" + this.sums_.text + "</div>";
if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
} else {
this.div_.title = this.sums_.title;
}
this.div_.style.display = "";
}
this.visible_ = true;
};
/**
* Sets the icon styles to the appropriate element in the styles array.
*
* @param {ClusterIconInfo} sums The icon label text and styles index.
*/
ClusterIcon.prototype.useStyle = function (sums) {
this.sums_ = sums;
var index = Math.max(0, sums.index - 1);
index = Math.min(this.styles_.length - 1, index);
var style = this.styles_[index];
this.url_ = style.url;
this.height_ = style.height;
this.width_ = style.width;
this.anchorText_ = style.anchorText || [0, 0];
this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)];
this.textColor_ = style.textColor || "black";
this.textSize_ = style.textSize || 11;
this.textDecoration_ = style.textDecoration || "none";
this.fontWeight_ = style.fontWeight || "bold";
this.fontStyle_ = style.fontStyle || "normal";
this.fontFamily_ = style.fontFamily || "Arial,sans-serif";
this.backgroundPosition_ = style.backgroundPosition || "0 0";
};
/**
* Sets the position at which to center the icon.
*
* @param {google.maps.LatLng} center The latlng to set as the center.
*/
ClusterIcon.prototype.setCenter = function (center) {
this.center_ = center;
};
/**
* Creates the cssText style parameter based on the position of the icon.
*
* @param {google.maps.Point} pos The position of the icon.
* @return {string} The CSS style text.
*/
ClusterIcon.prototype.createCss = function (pos) {
var style = [];
style.push("cursor: pointer;");
style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;");
style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;");
return style.join("");
};
/**
* Returns the position at which to place the DIV depending on the latlng.
*
* @param {google.maps.LatLng} latlng The position in latlng.
* @return {google.maps.Point} The position in pixels.
*/
ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {
var pos = this.getProjection().fromLatLngToDivPixel(latlng);
pos.x -= this.anchorIcon_[1];
pos.y -= this.anchorIcon_[0];
pos.x = parseInt(pos.x, 10);
pos.y = parseInt(pos.y, 10);
return pos;
};
/**
* Creates a single cluster that manages a group of proximate markers.
* Used internally, do not call this constructor directly.
* @constructor
* @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this
* cluster is associated.
*/
function Cluster(mc) {
this.markerClusterer_ = mc;
this.map_ = mc.getMap();
this.gridSize_ = mc.getGridSize();
this.minClusterSize_ = mc.getMinimumClusterSize();
this.averageCenter_ = mc.getAverageCenter();
this.markers_ = [];
this.center_ = null;
this.bounds_ = null;
this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());
}
/**
* Returns the number of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {number} The number of markers in the cluster.
*/
Cluster.prototype.getSize = function () {
return this.markers_.length;
};
/**
* Returns the array of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {Array} The array of markers in the cluster.
*/
Cluster.prototype.getMarkers = function () {
return this.markers_;
};
/**
* Returns the center of the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {google.maps.LatLng} The center of the cluster.
*/
Cluster.prototype.getCenter = function () {
return this.center_;
};
/**
* Returns the map with which the cluster is associated.
*
* @return {google.maps.Map} The map.
* @ignore
*/
Cluster.prototype.getMap = function () {
return this.map_;
};
/**
* Returns the <code>MarkerClusterer</code> object with which the cluster is associated.
*
* @return {MarkerClusterer} The associated marker clusterer.
* @ignore
*/
Cluster.prototype.getMarkerClusterer = function () {
return this.markerClusterer_;
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
* @ignore
*/
Cluster.prototype.getBounds = function () {
var i;
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
for (i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
return bounds;
};
/**
* Removes the cluster from the map.
*
* @ignore
*/
Cluster.prototype.remove = function () {
this.clusterIcon_.setMap(null);
this.markers_ = [];
delete this.markers_;
};
/**
* Adds a marker to the cluster.
*
* @param {google.maps.Marker} marker The marker to be added.
* @return {boolean} True if the marker was added.
* @ignore
*/
Cluster.prototype.addMarker = function (marker) {
var i;
var mCount;
var mz;
if (this.isMarkerAlreadyAdded_(marker)) {
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
mCount = this.markers_.length;
mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
// Zoomed in past max zoom, so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount < this.minClusterSize_) {
// Min cluster size not reached so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount === this.minClusterSize_) {
// Hide the markers that were showing.
for (i = 0; i < mCount; i++) {
this.markers_[i].setMap(null);
}
} else {
marker.setMap(null);
}
this.updateIcon_();
return true;
};
/**
* Determines if a marker lies within the cluster's bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker lies in the bounds.
* @ignore
*/
Cluster.prototype.isMarkerInClusterBounds = function (marker) {
return this.bounds_.contains(marker.getPosition());
};
/**
* Calculates the extended bounds of the cluster with the grid.
*/
Cluster.prototype.calculateBounds_ = function () {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
};
/**
* Updates the cluster icon.
*/
Cluster.prototype.updateIcon_ = function () {
var mCount = this.markers_.length;
var mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
this.clusterIcon_.hide();
return;
}
if (mCount < this.minClusterSize_) {
// Min cluster size not yet reached.
this.clusterIcon_.hide();
return;
}
var numStyles = this.markerClusterer_.getStyles().length;
var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
this.clusterIcon_.setCenter(this.center_);
this.clusterIcon_.useStyle(sums);
this.clusterIcon_.show();
};
/**
* Determines if a marker has already been added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker has already been added.
*/
Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) {
var i;
if (this.markers_.indexOf) {
return this.markers_.indexOf(marker) !== -1;
} else {
for (i = 0; i < this.markers_.length; i++) {
if (marker === this.markers_[i]) {
return true;
}
}
}
return false;
};
/**
* @name MarkerClustererOptions
* @class This class represents the optional parameter passed to
* the {@link MarkerClusterer} constructor.
* @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.
* @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or
* <code>null</code> if clustering is to be enabled at all zoom levels.
* @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is
* clicked. You may want to set this to <code>false</code> if you have installed a handler
* for the <code>click</code> event and it deals with zooming on its own.
* @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be
* the average position of all markers in the cluster. If set to <code>false</code>, the
* cluster marker is positioned at the location of the first marker added to the cluster.
* @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster
* before the markers are hidden and a cluster marker appears.
* @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You
* may want to set this to <code>true</code> to ensure that hidden markers are not included
* in the marker count that appears on a cluster marker (this count is the value of the
* <code>text</code> property of the result returned by the default <code>calculator</code>).
* If set to <code>true</code> and you change the visibility of a marker being clustered, be
* sure to also call <code>MarkerClusterer.repaint()</code>.
* @property {string} [title=""] The tooltip to display when the mouse moves over a cluster
* marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a
* different tooltip for each cluster marker.)
* @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine
* the text to be displayed on a cluster marker and the index indicating which style to use
* for the cluster marker. The input parameters for the function are (1) the array of markers
* represented by a cluster marker and (2) the number of cluster icon styles. It returns a
* {@link ClusterIconInfo} object. The default <code>calculator</code> returns a
* <code>text</code> property which is the number of markers in the cluster and an
* <code>index</code> property which is one higher than the lowest integer such that
* <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles
* array, whichever is less. The <code>styles</code> array element used has an index of
* <code>index</code> minus 1. For example, the default <code>calculator</code> returns a
* <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code>
* for a cluster icon representing 125 markers so the element used in the <code>styles</code>
* array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code>
* property that contains the text of the tooltip to be used for the cluster marker. If
* <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code>
* property for the MarkerClusterer.
* @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles
* for the cluster markers. Use this class to define CSS styles that are not set up by the code
* that processes the <code>styles</code> array.
* @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles
* of the cluster markers to be used. The element to be used to style a given cluster marker
* is determined by the function defined by the <code>calculator</code> property.
* The default is an array of {@link ClusterIconStyle} elements whose properties are derived
* from the values for <code>imagePath</code>, <code>imageExtension</code>, and
* <code>imageSizes</code>.
* @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that
* have sizes that are some multiple (typically double) of their actual display size. Icons such
* as these look better when viewed on high-resolution monitors such as Apple's Retina displays.
* Note: if this property is <code>true</code>, sprites cannot be used as cluster icons.
* @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the
* number of markers to be processed in a single batch when using a browser other than
* Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).
* @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is
* being used, markers are processed in several batches with a small delay inserted between
* each batch in an attempt to avoid Javascript timeout errors. Set this property to the
* number of markers to be processed in a single batch; select as high a number as you can
* without causing a timeout error in the browser. This number might need to be as low as 100
* if 15,000 markers are being managed, for example.
* @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]
* The full URL of the root name of the group of image files to use for cluster icons.
* The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code>
* where n is the image file number (1, 2, etc.).
* @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]
* The extension name for the cluster icon image files (e.g., <code>"png"</code> or
* <code>"jpg"</code>).
* @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]
* An array of numbers containing the widths of the group of
* <code>imagePath</code>n.<code>imageExtension</code> image files.
* (The images are assumed to be square.)
*/
/**
* Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.
* @constructor
* @extends google.maps.OverlayView
* @param {google.maps.Map} map The Google map to attach to.
* @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster.
* @param {MarkerClustererOptions} [opt_options] The optional parameters.
*/
function MarkerClusterer(map, opt_markers, opt_options) {
// MarkerClusterer implements google.maps.OverlayView interface. We use the
// extend function to extend MarkerClusterer with google.maps.OverlayView
// because it might not always be available when the code is defined so we
// look for it at the last possible moment. If it doesn't exist now then
// there is no point going ahead :)
this.extend(MarkerClusterer, google.maps.OverlayView);
opt_markers = opt_markers || [];
opt_options = opt_options || {};
this.markers_ = [];
this.clusters_ = [];
this.listeners_ = [];
this.activeMap_ = null;
this.ready_ = false;
this.gridSize_ = opt_options.gridSize || 60;
this.minClusterSize_ = opt_options.minimumClusterSize || 2;
this.maxZoom_ = opt_options.maxZoom || null;
this.styles_ = opt_options.styles || [];
this.title_ = opt_options.title || "";
this.zoomOnClick_ = true;
if (opt_options.zoomOnClick !== undefined) {
this.zoomOnClick_ = opt_options.zoomOnClick;
}
this.averageCenter_ = false;
if (opt_options.averageCenter !== undefined) {
this.averageCenter_ = opt_options.averageCenter;
}
this.ignoreHidden_ = false;
if (opt_options.ignoreHidden !== undefined) {
this.ignoreHidden_ = opt_options.ignoreHidden;
}
this.enableRetinaIcons_ = false;
if (opt_options.enableRetinaIcons !== undefined) {
this.enableRetinaIcons_ = opt_options.enableRetinaIcons;
}
this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;
this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;
this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;
this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;
this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE;
this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;
this.clusterClass_ = opt_options.clusterClass || "cluster";
if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
// Try to avoid IE timeout when processing a huge number of markers:
this.batchSize_ = this.batchSizeIE_;
}
this.setupStyles_();
this.addMarkers(opt_markers, true);
this.setMap(map); // Note: this causes onAdd to be called
}
/**
* Implementation of the onAdd interface method.
* @ignore
*/
MarkerClusterer.prototype.onAdd = function () {
var cMarkerClusterer = this;
this.activeMap_ = this.getMap();
this.ready_ = true;
this.repaint();
// Add the map event listeners
this.listeners_ = [
google.maps.event.addListener(this.getMap(), "zoom_changed", function () {
cMarkerClusterer.resetViewport_(false);
// Workaround for this Google bug: when map is at level 0 and "-" of
// zoom slider is clicked, a "zoom_changed" event is fired even though
// the map doesn't zoom out any further. In this situation, no "idle"
// event is triggered so the cluster markers that have been removed
// do not get redrawn. Same goes for a zoom in at maxZoom.
if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) {
google.maps.event.trigger(this, "idle");
}
}),
google.maps.event.addListener(this.getMap(), "idle", function () {
cMarkerClusterer.redraw_();
})
];
};
/**
* Implementation of the onRemove interface method.
* Removes map event listeners and all cluster icons from the DOM.
* All managed markers are also put back on the map.
* @ignore
*/
MarkerClusterer.prototype.onRemove = function () {
var i;
// Put all the managed markers back on the map:
for (i = 0; i < this.markers_.length; i++) {
if (this.markers_[i].getMap() !== this.activeMap_) {
this.markers_[i].setMap(this.activeMap_);
}
}
// Remove all clusters:
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Remove map event listeners:
for (i = 0; i < this.listeners_.length; i++) {
google.maps.event.removeListener(this.listeners_[i]);
}
this.listeners_ = [];
this.activeMap_ = null;
this.ready_ = false;
};
/**
* Implementation of the draw interface method.
* @ignore
*/
MarkerClusterer.prototype.draw = function () {};
/**
* Sets up the styles object.
*/
MarkerClusterer.prototype.setupStyles_ = function () {
var i, size;
if (this.styles_.length > 0) {
return;
}
for (i = 0; i < this.imageSizes_.length; i++) {
size = this.imageSizes_[i];
this.styles_.push({
url: this.imagePath_ + (i + 1) + "." + this.imageExtension_,
height: size,
width: size
});
}
};
/**
* Fits the map to the bounds of the markers managed by the clusterer.
*/
MarkerClusterer.prototype.fitMapToMarkers = function () {
var i;
var markers = this.getMarkers();
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
this.getMap().fitBounds(bounds);
};
/**
* Returns the value of the <code>gridSize</code> property.
*
* @return {number} The grid size.
*/
MarkerClusterer.prototype.getGridSize = function () {
return this.gridSize_;
};
/**
* Sets the value of the <code>gridSize</code> property.
*
* @param {number} gridSize The grid size.
*/
MarkerClusterer.prototype.setGridSize = function (gridSize) {
this.gridSize_ = gridSize;
};
/**
* Returns the value of the <code>minimumClusterSize</code> property.
*
* @return {number} The minimum cluster size.
*/
MarkerClusterer.prototype.getMinimumClusterSize = function () {
return this.minClusterSize_;
};
/**
* Sets the value of the <code>minimumClusterSize</code> property.
*
* @param {number} minimumClusterSize The minimum cluster size.
*/
MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {
this.minClusterSize_ = minimumClusterSize;
};
/**
* Returns the value of the <code>maxZoom</code> property.
*
* @return {number} The maximum zoom level.
*/
MarkerClusterer.prototype.getMaxZoom = function () {
return this.maxZoom_;
};
/**
* Sets the value of the <code>maxZoom</code> property.
*
* @param {number} maxZoom The maximum zoom level.
*/
MarkerClusterer.prototype.setMaxZoom = function (maxZoom) {
this.maxZoom_ = maxZoom;
};
/**
* Returns the value of the <code>styles</code> property.
*
* @return {Array} The array of styles defining the cluster markers to be used.
*/
MarkerClusterer.prototype.getStyles = function () {
return this.styles_;
};
/**
* Sets the value of the <code>styles</code> property.
*
* @param {Array.<ClusterIconStyle>} styles The array of styles to use.
*/
MarkerClusterer.prototype.setStyles = function (styles) {
this.styles_ = styles;
};
/**
* Returns the value of the <code>title</code> property.
*
* @return {string} The content of the title text.
*/
MarkerClusterer.prototype.getTitle = function () {
return this.title_;
};
/**
* Sets the value of the <code>title</code> property.
*
* @param {string} title The value of the title property.
*/
MarkerClusterer.prototype.setTitle = function (title) {
this.title_ = title;
};
/**
* Returns the value of the <code>zoomOnClick</code> property.
*
* @return {boolean} True if zoomOnClick property is set.
*/
MarkerClusterer.prototype.getZoomOnClick = function () {
return this.zoomOnClick_;
};
/**
* Sets the value of the <code>zoomOnClick</code> property.
*
* @param {boolean} zoomOnClick The value of the zoomOnClick property.
*/
MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) {
this.zoomOnClick_ = zoomOnClick;
};
/**
* Returns the value of the <code>averageCenter</code> property.
*
* @return {boolean} True if averageCenter property is set.
*/
MarkerClusterer.prototype.getAverageCenter = function () {
return this.averageCenter_;
};
/**
* Sets the value of the <code>averageCenter</code> property.
*
* @param {boolean} averageCenter The value of the averageCenter property.
*/
MarkerClusterer.prototype.setAverageCenter = function (averageCenter) {
this.averageCenter_ = averageCenter;
};
/**
* Returns the value of the <code>ignoreHidden</code> property.
*
* @return {boolean} True if ignoreHidden property is set.
*/
MarkerClusterer.prototype.getIgnoreHidden = function () {
return this.ignoreHidden_;
};
/**
* Sets the value of the <code>ignoreHidden</code> property.
*
* @param {boolean} ignoreHidden The value of the ignoreHidden property.
*/
MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) {
this.ignoreHidden_ = ignoreHidden;
};
/**
* Returns the value of the <code>enableRetinaIcons</code> property.
*
* @return {boolean} True if enableRetinaIcons property is set.
*/
MarkerClusterer.prototype.getEnableRetinaIcons = function () {
return this.enableRetinaIcons_;
};
/**
* Sets the value of the <code>enableRetinaIcons</code> property.
*
* @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.
*/
MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) {
this.enableRetinaIcons_ = enableRetinaIcons;
};
/**
* Returns the value of the <code>imageExtension</code> property.
*
* @return {string} The value of the imageExtension property.
*/
MarkerClusterer.prototype.getImageExtension = function () {
return this.imageExtension_;
};
/**
* Sets the value of the <code>imageExtension</code> property.
*
* @param {string} imageExtension The value of the imageExtension property.
*/
MarkerClusterer.prototype.setImageExtension = function (imageExtension) {
this.imageExtension_ = imageExtension;
};
/**
* Returns the value of the <code>imagePath</code> property.
*
* @return {string} The value of the imagePath property.
*/
MarkerClusterer.prototype.getImagePath = function () {
return this.imagePath_;
};
/**
* Sets the value of the <code>imagePath</code> property.
*
* @param {string} imagePath The value of the imagePath property.
*/
MarkerClusterer.prototype.setImagePath = function (imagePath) {
this.imagePath_ = imagePath;
};
/**
* Returns the value of the <code>imageSizes</code> property.
*
* @return {Array} The value of the imageSizes property.
*/
MarkerClusterer.prototype.getImageSizes = function () {
return this.imageSizes_;
};
/**
* Sets the value of the <code>imageSizes</code> property.
*
* @param {Array} imageSizes The value of the imageSizes property.
*/
MarkerClusterer.prototype.setImageSizes = function (imageSizes) {
this.imageSizes_ = imageSizes;
};
/**
* Returns the value of the <code>calculator</code> property.
*
* @return {function} the value of the calculator property.
*/
MarkerClusterer.prototype.getCalculator = function () {
return this.calculator_;
};
/**
* Sets the value of the <code>calculator</code> property.
*
* @param {function(Array.<google.maps.Marker>, number)} calculator The value
* of the calculator property.
*/
MarkerClusterer.prototype.setCalculator = function (calculator) {
this.calculator_ = calculator;
};
/**
* Returns the value of the <code>batchSizeIE</code> property.
*
* @return {number} the value of the batchSizeIE property.
*/
MarkerClusterer.prototype.getBatchSizeIE = function () {
return this.batchSizeIE_;
};
/**
* Sets the value of the <code>batchSizeIE</code> property.
*
* @param {number} batchSizeIE The value of the batchSizeIE property.
*/
MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) {
this.batchSizeIE_ = batchSizeIE;
};
/**
* Returns the value of the <code>clusterClass</code> property.
*
* @return {string} the value of the clusterClass property.
*/
MarkerClusterer.prototype.getClusterClass = function () {
return this.clusterClass_;
};
/**
* Sets the value of the <code>clusterClass</code> property.
*
* @param {string} clusterClass The value of the clusterClass property.
*/
MarkerClusterer.prototype.setClusterClass = function (clusterClass) {
this.clusterClass_ = clusterClass;
};
/**
* Returns the array of markers managed by the clusterer.
*
* @return {Array} The array of markers managed by the clusterer.
*/
MarkerClusterer.prototype.getMarkers = function () {
return this.markers_;
};
/**
* Returns the number of markers managed by the clusterer.
*
* @return {number} The number of markers.
*/
MarkerClusterer.prototype.getTotalMarkers = function () {
return this.markers_.length;
};
/**
* Returns the current array of clusters formed by the clusterer.
*
* @return {Array} The array of clusters formed by the clusterer.
*/
MarkerClusterer.prototype.getClusters = function () {
return this.clusters_;
};
/**
* Returns the number of clusters formed by the clusterer.
*
* @return {number} The number of clusters formed by the clusterer.
*/
MarkerClusterer.prototype.getTotalClusters = function () {
return this.clusters_.length;
};
/**
* Adds a marker to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {google.maps.Marker} marker The marker to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) {
this.pushMarkerTo_(marker);
if (!opt_nodraw) {
this.redraw_();
}
};
/**
* Adds an array of markers to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {Array.<google.maps.Marker>} markers The markers to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) {
var key;
for (key in markers) {
if (markers.hasOwnProperty(key)) {
this.pushMarkerTo_(markers[key]);
}
}
if (!opt_nodraw) {
this.redraw_();
}
};
/**
* Pushes a marker to the clusterer.
*
* @param {google.maps.Marker} marker The marker to add.
*/
MarkerClusterer.prototype.pushMarkerTo_ = function (marker) {
// If the marker is draggable add a listener so we can update the clusters on the dragend:
if (marker.getDraggable()) {
var cMarkerClusterer = this;
google.maps.event.addListener(marker, "dragend", function () {
if (cMarkerClusterer.ready_) {
this.isAdded = false;
cMarkerClusterer.repaint();
}
});
}
marker.isAdded = false;
this.markers_.push(marker);
};
/**
* Removes a marker from the cluster. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the
* marker was removed from the clusterer.
*
* @param {google.maps.Marker} marker The marker to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @return {boolean} True if the marker was removed from the clusterer.
*/
MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) {
var removed = this.removeMarker_(marker);
if (!opt_nodraw && removed) {
this.repaint();
}
return removed;
};
/**
* Removes an array of markers from the cluster. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers
* were removed from the clusterer.
*
* @param {Array.<google.maps.Marker>} markers The markers to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @return {boolean} True if markers were removed from the clusterer.
*/
MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) {
var i, r;
var removed = false;
for (i = 0; i < markers.length; i++) {
r = this.removeMarker_(markers[i]);
removed = removed || r;
}
if (!opt_nodraw && removed) {
this.repaint();
}
return removed;
};
/**
* Removes a marker and returns true if removed, false if not.
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
*/
MarkerClusterer.prototype.removeMarker_ = function (marker) {
var i;
var index = -1;
if (this.markers_.indexOf) {
index = this.markers_.indexOf(marker);
} else {
for (i = 0; i < this.markers_.length; i++) {
if (marker === this.markers_[i]) {
index = i;
break;
}
}
}
if (index === -1) {
// Marker is not in our list of markers, so do nothing:
return false;
}
marker.setMap(null);
this.markers_.splice(index, 1); // Remove the marker from the list of managed markers
return true;
};
/**
* Removes all clusters and markers from the map and also removes all markers
* managed by the clusterer.
*/
MarkerClusterer.prototype.clearMarkers = function () {
this.resetViewport_(true);
this.markers_ = [];
};
/**
* Recalculates and redraws all the marker clusters from scratch.
* Call this after changing any properties.
*/
MarkerClusterer.prototype.repaint = function () {
var oldClusters = this.clusters_.slice();
this.clusters_ = [];
this.resetViewport_(false);
this.redraw_();
// Remove the old clusters.
// Do it in a timeout to prevent blinking effect.
setTimeout(function () {
var i;
for (i = 0; i < oldClusters.length; i++) {
oldClusters[i].remove();
}
}, 0);
};
/**
* Returns the current bounds extended by the grid size.
*
* @param {google.maps.LatLngBounds} bounds The bounds to extend.
* @return {google.maps.LatLngBounds} The extended bounds.
* @ignore
*/
MarkerClusterer.prototype.getExtendedBounds = function (bounds) {
var projection = this.getProjection();
// Turn the bounds into latlng.
var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
bounds.getNorthEast().lng());
var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
bounds.getSouthWest().lng());
// Convert the points to pixels and the extend out by the grid size.
var trPix = projection.fromLatLngToDivPixel(tr);
trPix.x += this.gridSize_;
trPix.y -= this.gridSize_;
var blPix = projection.fromLatLngToDivPixel(bl);
blPix.x -= this.gridSize_;
blPix.y += this.gridSize_;
// Convert the pixel points back to LatLng
var ne = projection.fromDivPixelToLatLng(trPix);
var sw = projection.fromDivPixelToLatLng(blPix);
// Extend the bounds to contain the new bounds.
bounds.extend(ne);
bounds.extend(sw);
return bounds;
};
/**
* Redraws all the clusters.
*/
MarkerClusterer.prototype.redraw_ = function () {
this.createClusters_(0);
};
/**
* Removes all clusters from the map. The markers are also removed from the map
* if <code>opt_hide</code> is set to <code>true</code>.
*
* @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
* from the map.
*/
MarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
var i, marker;
// Remove all the clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Reset the markers to not be added and to be removed from the map.
for (i = 0; i < this.markers_.length; i++) {
marker = this.markers_[i];
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
}
};
/**
* Calculates the distance between two latlng locations in km.
*
* @param {google.maps.LatLng} p1 The first lat lng point.
* @param {google.maps.LatLng} p2 The second lat lng point.
* @return {number} The distance between the two points in km.
* @see http://www.movable-type.co.uk/scripts/latlong.html
*/
MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) {
var R = 6371; // Radius of the Earth in km
var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
};
/**
* Determines if a marker is contained in a bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @param {google.maps.LatLngBounds} bounds The bounds to check against.
* @return {boolean} True if the marker is in the bounds.
*/
MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) {
return bounds.contains(marker.getPosition());
};
/**
* Adds a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
*/
MarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
var i, d, cluster, center;
var distance = 40000; // Some large number
var clusterToAddTo = null;
for (i = 0; i < this.clusters_.length; i++) {
cluster = this.clusters_[i];
center = cluster.getCenter();
if (center) {
d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
cluster = new Cluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
MarkerClusterer.prototype.createClusters_ = function (iFirst) {
var i, marker;
var mapBounds;
var cMarkerClusterer = this;
if (!this.ready_) {
return;
}
// Cancel previous batch processing if we're working on the first batch:
if (iFirst === 0) {
/**
* This event is fired when the <code>MarkerClusterer</code> begins
* clustering markers.
* @name MarkerClusterer#clusteringbegin
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, "clusteringbegin", this);
if (typeof this.timerRefStatic !== "undefined") {
clearTimeout(this.timerRefStatic);
delete this.timerRefStatic;
}
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
//
// See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
if (this.getMap().getZoom() > 3) {
mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
this.getMap().getBounds().getNorthEast());
} else {
mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
}
var bounds = this.getExtendedBounds(mapBounds);
var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);
for (i = iFirst; i < iLast; i++) {
marker = this.markers_[i];
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
this.addToClosestCluster_(marker);
}
}
}
if (iLast < this.markers_.length) {
this.timerRefStatic = setTimeout(function () {
cMarkerClusterer.createClusters_(iLast);
}, 0);
} else {
delete this.timerRefStatic;
/**
* This event is fired when the <code>MarkerClusterer</code> stops
* clustering markers.
* @name MarkerClusterer#clusteringend
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, "clusteringend", this);
}
};
/**
* Extends an object's prototype by another's.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
MarkerClusterer.prototype.extend = function (obj1, obj2) {
return (function (object) {
var property;
for (property in object.prototype) {
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
/**
* The default function for determining the label text and style
* for a cluster icon.
*
* @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster.
* @param {number} numStyles The number of marker styles available.
* @return {ClusterIconInfo} The information resource for the cluster.
* @constant
* @ignore
*/
MarkerClusterer.CALCULATOR = function (markers, numStyles) {
var index = 0;
var title = "";
var count = markers.length.toString();
var dv = count;
while (dv !== 0) {
dv = parseInt(dv / 10, 10);
index++;
}
index = Math.min(index, numStyles);
return {
text: count,
index: index,
title: title
};
};
/**
* The number of markers to process in one batch.
*
* @type {number}
* @constant
*/
MarkerClusterer.BATCH_SIZE = 2000;
/**
* The number of markers to process in one batch (IE only).
*
* @type {number}
* @constant
*/
MarkerClusterer.BATCH_SIZE_IE = 500;
/**
* The default root name for the marker cluster images.
*
* @type {string}
* @constant
*/
MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m";
/**
* The default extension name for the marker cluster images.
*
* @type {string}
* @constant
*/
MarkerClusterer.IMAGE_EXTENSION = "png";
/**
* The default array of sizes for the marker cluster images.
*
* @type {Array.<number>}
* @constant
*/
MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];
/**
* @name MarkerWithLabel for V3
* @version 1.1.10 [April 8, 2014]
* @author Gary Little (inspired by code from Marc Ridey of Google).
* @copyright Copyright 2012 Gary Little [gary at luxcentral.com]
* @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3
* <code>google.maps.Marker</code> class.
* <p>
* MarkerWithLabel allows you to define markers with associated labels. As you would expect,
* if the marker is draggable, so too will be the label. In addition, a marker with a label
* responds to all mouse events in the same manner as a regular marker. It also fires mouse
* events and "property changed" events just as a regular marker would. Version 1.1 adds
* support for the raiseOnDrag feature introduced in API V3.3.
* <p>
* If you drag a marker by its label, you can cancel the drag and return the marker to its
* original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker
* itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class.
*/
/*!
*
* 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.
*/
/*jslint browser:true */
/*global document,google */
/**
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
* @private
*/
function inherits(childCtor, parentCtor) {
/* @constructor */
function tempCtor() {}
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
/* @override */
childCtor.prototype.constructor = childCtor;
}
/**
* This constructor creates a label and associates it with a marker.
* It is for the private use of the MarkerWithLabel class.
* @constructor
* @param {Marker} marker The marker with which the label is to be associated.
* @param {string} crossURL The URL of the cross image =.
* @param {string} handCursor The URL of the hand cursor.
* @private
*/
function MarkerLabel_(marker, crossURL, handCursorURL) {
this.marker_ = marker;
this.handCursorURL_ = marker.handCursorURL;
this.labelDiv_ = document.createElement("div");
this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;";
// Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil
// in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that
// events can be captured even if the label is in the shadow of a google.maps.InfoWindow.
// Code is included here to ensure the veil is always exactly the same size as the label.
this.eventDiv_ = document.createElement("div");
this.eventDiv_.style.cssText = this.labelDiv_.style.cssText;
// This is needed for proper behavior on MSIE:
this.eventDiv_.setAttribute("onselectstart", "return false;");
this.eventDiv_.setAttribute("ondragstart", "return false;");
// Get the DIV for the "X" to be displayed when the marker is raised.
this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL);
}
inherits(MarkerLabel_, google.maps.OverlayView);
/**
* Returns the DIV for the cross used when dragging a marker when the
* raiseOnDrag parameter set to true. One cross is shared with all markers.
* @param {string} crossURL The URL of the cross image =.
* @private
*/
MarkerLabel_.getSharedCross = function (crossURL) {
var div;
if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") {
div = document.createElement("img");
div.style.cssText = "position: absolute; z-index: 1000002; display: none;";
// Hopefully Google never changes the standard "X" attributes:
div.style.marginLeft = "-8px";
div.style.marginTop = "-9px";
div.src = crossURL;
MarkerLabel_.getSharedCross.crossDiv = div;
}
return MarkerLabel_.getSharedCross.crossDiv;
};
/**
* Adds the DIV representing the label to the DOM. This method is called
* automatically when the marker's <code>setMap</code> method is called.
* @private
*/
MarkerLabel_.prototype.onAdd = function () {
var me = this;
var cMouseIsDown = false;
var cDraggingLabel = false;
var cSavedZIndex;
var cLatOffset, cLngOffset;
var cIgnoreClick;
var cRaiseEnabled;
var cStartPosition;
var cStartCenter;
// Constants:
var cRaiseOffset = 20;
var cDraggingCursor = "url(" + this.handCursorURL_ + ")";
// Stops all processing of an event.
//
var cAbortEvent = function (e) {
if (e.preventDefault) {
e.preventDefault();
}
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
var cStopBounce = function () {
me.marker_.setAnimation(null);
};
this.getPanes().overlayImage.appendChild(this.labelDiv_);
this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_);
// One cross is shared with all markers, so only add it once:
if (typeof MarkerLabel_.getSharedCross.processed === "undefined") {
this.getPanes().overlayImage.appendChild(this.crossDiv_);
MarkerLabel_.getSharedCross.processed = true;
}
this.listeners_ = [
google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
this.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseover", e);
}
}),
google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) {
if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) {
this.style.cursor = me.marker_.getCursor();
google.maps.event.trigger(me.marker_, "mouseout", e);
}
}),
google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) {
cDraggingLabel = false;
if (me.marker_.getDraggable()) {
cMouseIsDown = true;
this.style.cursor = cDraggingCursor;
}
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "mousedown", e);
cAbortEvent(e); // Prevent map pan when starting a drag on a label
}
}),
google.maps.event.addDomListener(document, "mouseup", function (mEvent) {
var position;
if (cMouseIsDown) {
cMouseIsDown = false;
me.eventDiv_.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseup", mEvent);
}
if (cDraggingLabel) {
if (cRaiseEnabled) { // Lower the marker & label
position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition());
position.y += cRaiseOffset;
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
// This is not the same bouncing style as when the marker portion is dragged,
// but it will have to do:
try { // Will fail if running Google Maps API earlier than V3.3
me.marker_.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(cStopBounce, 1406);
} catch (e) {}
}
me.crossDiv_.style.display = "none";
me.marker_.setZIndex(cSavedZIndex);
cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag
cDraggingLabel = false;
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragend", mEvent);
}
}),
google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) {
var position;
if (cMouseIsDown) {
if (cDraggingLabel) {
// Change the reported location from the mouse position to the marker position:
mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset);
position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng);
if (cRaiseEnabled) {
me.crossDiv_.style.left = position.x + "px";
me.crossDiv_.style.top = position.y + "px";
me.crossDiv_.style.display = "";
position.y -= cRaiseOffset;
}
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly
me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px";
}
google.maps.event.trigger(me.marker_, "drag", mEvent);
} else {
// Calculate offsets from the click point to the marker position:
cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat();
cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng();
cSavedZIndex = me.marker_.getZIndex();
cStartPosition = me.marker_.getPosition();
cStartCenter = me.marker_.getMap().getCenter();
cRaiseEnabled = me.marker_.get("raiseOnDrag");
cDraggingLabel = true;
me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragstart", mEvent);
}
}
}),
google.maps.event.addDomListener(document, "keydown", function (e) {
if (cDraggingLabel) {
if (e.keyCode === 27) { // Esc key
cRaiseEnabled = false;
me.marker_.setPosition(cStartPosition);
me.marker_.getMap().setCenter(cStartCenter);
google.maps.event.trigger(document, "mouseup", e);
}
}
}),
google.maps.event.addDomListener(this.eventDiv_, "click", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
if (cIgnoreClick) { // Ignore the click reported when a label drag ends
cIgnoreClick = false;
} else {
google.maps.event.trigger(me.marker_, "click", e);
cAbortEvent(e); // Prevent click from being passed on to map
}
}
}),
google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "dblclick", e);
cAbortEvent(e); // Prevent map zoom when double-clicking on a label
}
}),
google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) {
if (!cDraggingLabel) {
cRaiseEnabled = this.get("raiseOnDrag");
}
}),
google.maps.event.addListener(this.marker_, "drag", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(cRaiseOffset);
// During a drag, the marker's z-index is temporarily set to 1000000 to
// ensure it appears above all other markers. Also set the label's z-index
// to 1000000 (plus or minus 1 depending on whether the label is supposed
// to be above or below the marker).
me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1);
}
}
}),
google.maps.event.addListener(this.marker_, "dragend", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(0); // Also restores z-index of label
}
}
}),
google.maps.event.addListener(this.marker_, "position_changed", function () {
me.setPosition();
}),
google.maps.event.addListener(this.marker_, "zindex_changed", function () {
me.setZIndex();
}),
google.maps.event.addListener(this.marker_, "visible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "labelvisible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "title_changed", function () {
me.setTitle();
}),
google.maps.event.addListener(this.marker_, "labelcontent_changed", function () {
me.setContent();
}),
google.maps.event.addListener(this.marker_, "labelanchor_changed", function () {
me.setAnchor();
}),
google.maps.event.addListener(this.marker_, "labelclass_changed", function () {
me.setStyles();
}),
google.maps.event.addListener(this.marker_, "labelstyle_changed", function () {
me.setStyles();
})
];
};
/**
* Removes the DIV for the label from the DOM. It also removes all event handlers.
* This method is called automatically when the marker's <code>setMap(null)</code>
* method is called.
* @private
*/
MarkerLabel_.prototype.onRemove = function () {
var i;
this.labelDiv_.parentNode.removeChild(this.labelDiv_);
this.eventDiv_.parentNode.removeChild(this.eventDiv_);
// Remove event listeners:
for (i = 0; i < this.listeners_.length; i++) {
google.maps.event.removeListener(this.listeners_[i]);
}
};
/**
* Draws the label on the map.
* @private
*/
MarkerLabel_.prototype.draw = function () {
this.setContent();
this.setTitle();
this.setStyles();
};
/**
* Sets the content of the label.
* The content can be plain text or an HTML DOM node.
* @private
*/
MarkerLabel_.prototype.setContent = function () {
var content = this.marker_.get("labelContent");
if (typeof content.nodeType === "undefined") {
this.labelDiv_.innerHTML = content;
this.eventDiv_.innerHTML = this.labelDiv_.innerHTML;
} else {
this.labelDiv_.innerHTML = ""; // Remove current content
this.labelDiv_.appendChild(content);
content = content.cloneNode(true);
this.eventDiv_.innerHTML = ""; // Remove current content
this.eventDiv_.appendChild(content);
}
};
/**
* Sets the content of the tool tip for the label. It is
* always set to be the same as for the marker itself.
* @private
*/
MarkerLabel_.prototype.setTitle = function () {
this.eventDiv_.title = this.marker_.getTitle() || "";
};
/**
* Sets the style of the label by setting the style sheet and applying
* other specific styles requested.
* @private
*/
MarkerLabel_.prototype.setStyles = function () {
var i, labelStyle;
// Apply style values from the style sheet defined in the labelClass parameter:
this.labelDiv_.className = this.marker_.get("labelClass");
this.eventDiv_.className = this.labelDiv_.className;
// Clear existing inline style values:
this.labelDiv_.style.cssText = "";
this.eventDiv_.style.cssText = "";
// Apply style values defined in the labelStyle parameter:
labelStyle = this.marker_.get("labelStyle");
for (i in labelStyle) {
if (labelStyle.hasOwnProperty(i)) {
this.labelDiv_.style[i] = labelStyle[i];
this.eventDiv_.style[i] = labelStyle[i];
}
}
this.setMandatoryStyles();
};
/**
* Sets the mandatory styles to the DIV representing the label as well as to the
* associated event DIV. This includes setting the DIV position, z-index, and visibility.
* @private
*/
MarkerLabel_.prototype.setMandatoryStyles = function () {
this.labelDiv_.style.position = "absolute";
this.labelDiv_.style.overflow = "hidden";
// Make sure the opacity setting causes the desired effect on MSIE:
if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") {
this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\"";
this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")";
}
this.eventDiv_.style.position = this.labelDiv_.style.position;
this.eventDiv_.style.overflow = this.labelDiv_.style.overflow;
this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE
this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\"";
this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE
this.setAnchor();
this.setPosition(); // This also updates z-index, if necessary.
this.setVisible();
};
/**
* Sets the anchor point of the label.
* @private
*/
MarkerLabel_.prototype.setAnchor = function () {
var anchor = this.marker_.get("labelAnchor");
this.labelDiv_.style.marginLeft = -anchor.x + "px";
this.labelDiv_.style.marginTop = -anchor.y + "px";
this.eventDiv_.style.marginLeft = -anchor.x + "px";
this.eventDiv_.style.marginTop = -anchor.y + "px";
};
/**
* Sets the position of the label. The z-index is also updated, if necessary.
* @private
*/
MarkerLabel_.prototype.setPosition = function (yOffset) {
var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition());
if (typeof yOffset === "undefined") {
yOffset = 0;
}
this.labelDiv_.style.left = Math.round(position.x) + "px";
this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px";
this.eventDiv_.style.left = this.labelDiv_.style.left;
this.eventDiv_.style.top = this.labelDiv_.style.top;
this.setZIndex();
};
/**
* Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index
* of the label is set to the vertical coordinate of the label. This is in keeping with the default
* stacking order for Google Maps: markers to the south are in front of markers to the north.
* @private
*/
MarkerLabel_.prototype.setZIndex = function () {
var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1);
if (typeof this.marker_.getZIndex() === "undefined") {
this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust;
this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;
} else {
this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust;
this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex;
}
};
/**
* Sets the visibility of the label. The label is visible only if the marker itself is
* visible (i.e., its visible property is true) and the labelVisible property is true.
* @private
*/
MarkerLabel_.prototype.setVisible = function () {
if (this.marker_.get("labelVisible")) {
this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none";
} else {
this.labelDiv_.style.display = "none";
}
this.eventDiv_.style.display = this.labelDiv_.style.display;
};
/**
* @name MarkerWithLabelOptions
* @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor.
* The properties available are the same as for <code>google.maps.Marker</code> with the addition
* of the properties listed below. To change any of these additional properties after the labeled
* marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>.
* <p>
* When any of these properties changes, a property changed event is fired. The names of these
* events are derived from the name of the property and are of the form <code>propertyname_changed</code>.
* For example, if the content of the label changes, a <code>labelcontent_changed</code> event
* is fired.
* <p>
* @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node).
* @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so
* that its top left corner is positioned at the anchor point of the associated marker. Use this
* property to change the anchor point of the label. For example, to center a 50px-wide label
* beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>.
* (Note: x-values increase to the right and y-values increase to the top.)
* @property {string} [labelClass] The name of the CSS class defining the styles for the label.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {Object} [labelStyle] An object literal whose properties define specific CSS
* style values to be applied to the label. Style values defined here override those that may
* be defined in the <code>labelClass</code> style sheet. If this property is changed after the
* label has been created, all previously set styles (except those defined in the style sheet)
* are removed from the label before the new style values are applied.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its
* associated marker should appear in the background (i.e., in a plane below the marker).
* The default is <code>false</code>, which causes the label to appear in the foreground.
* @property {boolean} [labelVisible] A flag indicating whether the label is to be visible.
* The default is <code>true</code>. Note that even if <code>labelVisible</code> is
* <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also
* visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>).
* @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be
* raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is
* being created and a version of Google Maps API earlier than V3.3 is being used, this property
* must be set to <code>false</code>.
* @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the
* marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel,
* so the value of this parameter is always forced to <code>false</code>.
* @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"]
* The URL of the cross image to be displayed while dragging a marker.
* @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"]
* The URL of the cursor to be displayed while dragging a marker.
*/
/**
* Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}.
* @constructor
* @param {MarkerWithLabelOptions} [opt_options] The optional parameters.
*/
function MarkerWithLabel(opt_options) {
opt_options = opt_options || {};
opt_options.labelContent = opt_options.labelContent || "";
opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0);
opt_options.labelClass = opt_options.labelClass || "markerLabels";
opt_options.labelStyle = opt_options.labelStyle || {};
opt_options.labelInBackground = opt_options.labelInBackground || false;
if (typeof opt_options.labelVisible === "undefined") {
opt_options.labelVisible = true;
}
if (typeof opt_options.raiseOnDrag === "undefined") {
opt_options.raiseOnDrag = true;
}
if (typeof opt_options.clickable === "undefined") {
opt_options.clickable = true;
}
if (typeof opt_options.draggable === "undefined") {
opt_options.draggable = false;
}
if (typeof opt_options.optimized === "undefined") {
opt_options.optimized = false;
}
opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png";
opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur";
opt_options.optimized = false; // Optimized rendering is not supported
this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker
// Call the parent constructor. It calls Marker.setValues to initialize, so all
// the new parameters are conveniently saved and can be accessed with get/set.
// Marker.set triggers a property changed event (called "propertyname_changed")
// that the marker label listens for in order to react to state changes.
google.maps.Marker.apply(this, arguments);
}
inherits(MarkerWithLabel, google.maps.Marker);
/**
* Overrides the standard Marker setMap function.
* @param {Map} theMap The map to which the marker is to be added.
* @private
*/
MarkerWithLabel.prototype.setMap = function (theMap) {
// Call the inherited function...
google.maps.Marker.prototype.setMap.apply(this, arguments);
// ... then deal with the label:
this.label.setMap(theMap);
};
//END REPLACE
window.InfoBox = InfoBox;
window.Cluster = Cluster;
window.ClusterIcon = ClusterIcon;
window.MarkerClusterer = MarkerClusterer;
window.MarkerLabel_ = MarkerLabel_;
window.MarkerWithLabel = MarkerWithLabel;
})
};
});
;/******/ (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__) {
angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapDataStructures', function() {
return {
Graph: __webpack_require__(1).Graph,
Queue: __webpack_require__(1).Queue
};
});
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
(function() {
module.exports = {
Graph: __webpack_require__(2),
Heap: __webpack_require__(3),
LinkedList: __webpack_require__(4),
Map: __webpack_require__(5),
Queue: __webpack_require__(6),
RedBlackTree: __webpack_require__(7),
Trie: __webpack_require__(8)
};
}).call(this);
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/*
Graph implemented as a modified incidence list. O(1) for every typical
operation except `removeNode()` at O(E) where E is the number of edges.
## Overview example:
```js
var graph = new Graph;
graph.addNode('A'); // => a node object. For more info, log the output or check
// the documentation for addNode
graph.addNode('B');
graph.addNode('C');
graph.addEdge('A', 'C'); // => an edge object
graph.addEdge('A', 'B');
graph.getEdge('B', 'A'); // => undefined. Directed edge!
graph.getEdge('A', 'B'); // => the edge object previously added
graph.getEdge('A', 'B').weight = 2 // weight is the only built-in handy property
// of an edge object. Feel free to attach
// other properties
graph.getInEdgesOf('B'); // => array of edge objects, in this case only one;
// connecting A to B
graph.getOutEdgesOf('A'); // => array of edge objects, one to B and one to C
graph.getAllEdgesOf('A'); // => all the in and out edges. Edge directed toward
// the node itself are only counted once
forEachNode(function(nodeObject) {
console.log(node);
});
forEachEdge(function(edgeObject) {
console.log(edgeObject);
});
graph.removeNode('C'); // => 'C'. The edge between A and C also removed
graph.removeEdge('A', 'B'); // => the edge object removed
```
## Properties:
- nodeSize: total number of nodes.
- edgeSize: total number of edges.
*/
(function() {
var Graph,
__hasProp = {}.hasOwnProperty;
Graph = (function() {
function Graph() {
this._nodes = {};
this.nodeSize = 0;
this.edgeSize = 0;
}
Graph.prototype.addNode = function(id) {
/*
The `id` is a unique identifier for the node, and should **not** change
after it's added. It will be used for adding, retrieving and deleting
related edges too.
**Note** that, internally, the ids are kept in an object. JavaScript's
object hashes the id `'2'` and `2` to the same key, so please stick to a
simple id data type such as number or string.
_Returns:_ the node object. Feel free to attach additional custom properties
on it for graph algorithms' needs. **Undefined if node id already exists**,
as to avoid accidental overrides.
*/
if (!this._nodes[id]) {
this.nodeSize++;
return this._nodes[id] = {
_outEdges: {},
_inEdges: {}
};
}
};
Graph.prototype.getNode = function(id) {
/*
_Returns:_ the node object. Feel free to attach additional custom properties
on it for graph algorithms' needs.
*/
return this._nodes[id];
};
Graph.prototype.removeNode = function(id) {
/*
_Returns:_ the node object removed, or undefined if it didn't exist in the
first place.
*/
var inEdgeId, nodeToRemove, outEdgeId, _ref, _ref1;
nodeToRemove = this._nodes[id];
if (!nodeToRemove) {
return;
} else {
_ref = nodeToRemove._outEdges;
for (outEdgeId in _ref) {
if (!__hasProp.call(_ref, outEdgeId)) continue;
this.removeEdge(id, outEdgeId);
}
_ref1 = nodeToRemove._inEdges;
for (inEdgeId in _ref1) {
if (!__hasProp.call(_ref1, inEdgeId)) continue;
this.removeEdge(inEdgeId, id);
}
this.nodeSize--;
delete this._nodes[id];
}
return nodeToRemove;
};
Graph.prototype.addEdge = function(fromId, toId, weight) {
var edgeToAdd, fromNode, toNode;
if (weight == null) {
weight = 1;
}
/*
`fromId` and `toId` are the node id specified when it was created using
`addNode()`. `weight` is optional and defaults to 1. Ignoring it effectively
makes this an unweighted graph. Under the hood, `weight` is just a normal
property of the edge object.
_Returns:_ the edge object created. Feel free to attach additional custom
properties on it for graph algorithms' needs. **Or undefined** if the nodes
of id `fromId` or `toId` aren't found, or if an edge already exists between
the two nodes.
*/
if (this.getEdge(fromId, toId)) {
return;
}
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
if (!fromNode || !toNode) {
return;
}
edgeToAdd = {
weight: weight
};
fromNode._outEdges[toId] = edgeToAdd;
toNode._inEdges[fromId] = edgeToAdd;
this.edgeSize++;
return edgeToAdd;
};
Graph.prototype.getEdge = function(fromId, toId) {
/*
_Returns:_ the edge object, or undefined if the nodes of id `fromId` or
`toId` aren't found.
*/
var fromNode, toNode;
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
if (!fromNode || !toNode) {
} else {
return fromNode._outEdges[toId];
}
};
Graph.prototype.removeEdge = function(fromId, toId) {
/*
_Returns:_ the edge object removed, or undefined of edge wasn't found.
*/
var edgeToDelete, fromNode, toNode;
fromNode = this._nodes[fromId];
toNode = this._nodes[toId];
edgeToDelete = this.getEdge(fromId, toId);
if (!edgeToDelete) {
return;
}
delete fromNode._outEdges[toId];
delete toNode._inEdges[fromId];
this.edgeSize--;
return edgeToDelete;
};
Graph.prototype.getInEdgesOf = function(nodeId) {
/*
_Returns:_ an array of edge objects that are directed toward the node, or
empty array if no such edge or node exists.
*/
var fromId, inEdges, toNode, _ref;
toNode = this._nodes[nodeId];
inEdges = [];
_ref = toNode != null ? toNode._inEdges : void 0;
for (fromId in _ref) {
if (!__hasProp.call(_ref, fromId)) continue;
inEdges.push(this.getEdge(fromId, nodeId));
}
return inEdges;
};
Graph.prototype.getOutEdgesOf = function(nodeId) {
/*
_Returns:_ an array of edge objects that go out of the node, or empty array
if no such edge or node exists.
*/
var fromNode, outEdges, toId, _ref;
fromNode = this._nodes[nodeId];
outEdges = [];
_ref = fromNode != null ? fromNode._outEdges : void 0;
for (toId in _ref) {
if (!__hasProp.call(_ref, toId)) continue;
outEdges.push(this.getEdge(nodeId, toId));
}
return outEdges;
};
Graph.prototype.getAllEdgesOf = function(nodeId) {
/*
**Note:** not the same as concatenating `getInEdgesOf()` and
`getOutEdgesOf()`. Some nodes might have an edge pointing toward itself.
This method solves that duplication.
_Returns:_ an array of edge objects linked to the node, no matter if they're
outgoing or coming. Duplicate edge created by self-pointing nodes are
removed. Only one copy stays. Empty array if node has no edge.
*/
var i, inEdges, outEdges, selfEdge, _i, _ref, _ref1;
inEdges = this.getInEdgesOf(nodeId);
outEdges = this.getOutEdgesOf(nodeId);
if (inEdges.length === 0) {
return outEdges;
}
selfEdge = this.getEdge(nodeId, nodeId);
for (i = _i = 0, _ref = inEdges.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
if (inEdges[i] === selfEdge) {
_ref1 = [inEdges[inEdges.length - 1], inEdges[i]], inEdges[i] = _ref1[0], inEdges[inEdges.length - 1] = _ref1[1];
inEdges.pop();
break;
}
}
return inEdges.concat(outEdges);
};
Graph.prototype.forEachNode = function(operation) {
/*
Traverse through the graph in an arbitrary manner, visiting each node once.
Pass a function of the form `fn(nodeObject, nodeId)`.
_Returns:_ undefined.
*/
var nodeId, nodeObject, _ref;
_ref = this._nodes;
for (nodeId in _ref) {
if (!__hasProp.call(_ref, nodeId)) continue;
nodeObject = _ref[nodeId];
operation(nodeObject, nodeId);
}
};
Graph.prototype.forEachEdge = function(operation) {
/*
Traverse through the graph in an arbitrary manner, visiting each edge once.
Pass a function of the form `fn(edgeObject)`.
_Returns:_ undefined.
*/
var edgeObject, nodeId, nodeObject, toId, _ref, _ref1;
_ref = this._nodes;
for (nodeId in _ref) {
if (!__hasProp.call(_ref, nodeId)) continue;
nodeObject = _ref[nodeId];
_ref1 = nodeObject._outEdges;
for (toId in _ref1) {
if (!__hasProp.call(_ref1, toId)) continue;
edgeObject = _ref1[toId];
operation(edgeObject);
}
}
};
return Graph;
})();
module.exports = Graph;
}).call(this);
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/*
Minimum heap, i.e. smallest node at root.
**Note:** does not accept null or undefined. This is by design. Those values
cause comparison problems and might report false negative during extraction.
## Overview example:
```js
var heap = new Heap([5, 6, 3, 4]);
heap.add(10); // => 10
heap.removeMin(); // => 3
heap.peekMin(); // => 4
```
## Properties:
- size: total number of items.
*/
(function() {
var Heap, _leftChild, _parent, _rightChild;
Heap = (function() {
function Heap(dataToHeapify) {
var i, item, _i, _j, _len, _ref;
if (dataToHeapify == null) {
dataToHeapify = [];
}
/*
Pass an optional array to be heapified. Takes only O(n) time.
*/
this._data = [void 0];
for (_i = 0, _len = dataToHeapify.length; _i < _len; _i++) {
item = dataToHeapify[_i];
if (item != null) {
this._data.push(item);
}
}
if (this._data.length > 1) {
for (i = _j = 2, _ref = this._data.length; 2 <= _ref ? _j < _ref : _j > _ref; i = 2 <= _ref ? ++_j : --_j) {
this._upHeap(i);
}
}
this.size = this._data.length - 1;
}
Heap.prototype.add = function(value) {
/*
**Remember:** rejects null and undefined for mentioned reasons.
_Returns:_ the value added.
*/
if (value == null) {
return;
}
this._data.push(value);
this._upHeap(this._data.length - 1);
this.size++;
return value;
};
Heap.prototype.removeMin = function() {
/*
_Returns:_ the smallest item (the root).
*/
var min;
if (this._data.length === 1) {
return;
}
this.size--;
if (this._data.length === 2) {
return this._data.pop();
}
min = this._data[1];
this._data[1] = this._data.pop();
this._downHeap();
return min;
};
Heap.prototype.peekMin = function() {
/*
Check the smallest item without removing it.
_Returns:_ the smallest item (the root).
*/
return this._data[1];
};
Heap.prototype._upHeap = function(index) {
var valueHolder, _ref;
valueHolder = this._data[index];
while (this._data[index] < this._data[_parent(index)] && index > 1) {
_ref = [this._data[_parent(index)], this._data[index]], this._data[index] = _ref[0], this._data[_parent(index)] = _ref[1];
index = _parent(index);
}
};
Heap.prototype._downHeap = function() {
var currentIndex, smallerChildIndex, _ref;
currentIndex = 1;
while (_leftChild(currentIndex < this._data.length)) {
smallerChildIndex = _leftChild(currentIndex);
if (smallerChildIndex < this._data.length - 1) {
if (this._data[_rightChild(currentIndex)] < this._data[smallerChildIndex]) {
smallerChildIndex = _rightChild(currentIndex);
}
}
if (this._data[smallerChildIndex] < this._data[currentIndex]) {
_ref = [this._data[currentIndex], this._data[smallerChildIndex]], this._data[smallerChildIndex] = _ref[0], this._data[currentIndex] = _ref[1];
currentIndex = smallerChildIndex;
} else {
break;
}
}
};
return Heap;
})();
_parent = function(index) {
return index >> 1;
};
_leftChild = function(index) {
return index << 1;
};
_rightChild = function(index) {
return (index << 1) + 1;
};
module.exports = Heap;
}).call(this);
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
Doubly Linked.
## Overview example:
```js
var list = new LinkedList([5, 4, 9]);
list.add(12); // => 12
list.head.next.value; // => 4
list.tail.value; // => 12
list.at(-1); // => 12
list.removeAt(2); // => 9
list.remove(4); // => 4
list.indexOf(5); // => 0
list.add(5, 1); // => 5. Second 5 at position 1.
list.indexOf(5, 1); // => 1
```
## Properties:
- head: first item.
- tail: last item.
- size: total number of items.
- item.value: value passed to the item when calling `add()`.
- item.prev: previous item.
- item.next: next item.
*/
(function() {
var LinkedList;
LinkedList = (function() {
function LinkedList(valuesToAdd) {
var value, _i, _len;
if (valuesToAdd == null) {
valuesToAdd = [];
}
/*
Can pass an array of elements to link together during `new LinkedList()`
initiation.
*/
this.head = {
prev: void 0,
value: void 0,
next: void 0
};
this.tail = {
prev: void 0,
value: void 0,
next: void 0
};
this.size = 0;
for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {
value = valuesToAdd[_i];
this.add(value);
}
}
LinkedList.prototype.at = function(position) {
/*
Get the item at `position` (optional). Accepts negative index:
```js
myList.at(-1); // Returns the last element.
```
However, passing a negative index that surpasses the boundary will return
undefined:
```js
myList = new LinkedList([2, 6, 8, 3])
myList.at(-5); // Undefined.
myList.at(-4); // 2.
```
_Returns:_ item gotten, or undefined if not found.
*/
var currentNode, i, _i, _j, _ref;
if (!((-this.size <= position && position < this.size))) {
return;
}
position = this._adjust(position);
if (position * 2 < this.size) {
currentNode = this.head;
for (i = _i = 1; _i <= position; i = _i += 1) {
currentNode = currentNode.next;
}
} else {
currentNode = this.tail;
for (i = _j = 1, _ref = this.size - position - 1; _j <= _ref; i = _j += 1) {
currentNode = currentNode.prev;
}
}
return currentNode;
};
LinkedList.prototype.add = function(value, position) {
var currentNode, nodeToAdd, _ref, _ref1, _ref2;
if (position == null) {
position = this.size;
}
/*
Add a new item at `position` (optional). Defaults to adding at the end.
`position`, just like in `at()`, can be negative (within the negative
boundary). Position specifies the place the value's going to be, and the old
node will be pushed higher. `add(-2)` on list of size 7 is the same as
`add(5)`.
_Returns:_ item added.
*/
if (!((-this.size <= position && position <= this.size))) {
return;
}
nodeToAdd = {
value: value
};
position = this._adjust(position);
if (this.size === 0) {
this.head = nodeToAdd;
} else {
if (position === 0) {
_ref = [nodeToAdd, this.head, nodeToAdd], this.head.prev = _ref[0], nodeToAdd.next = _ref[1], this.head = _ref[2];
} else {
currentNode = this.at(position - 1);
_ref1 = [currentNode.next, nodeToAdd, nodeToAdd, currentNode], nodeToAdd.next = _ref1[0], (_ref2 = currentNode.next) != null ? _ref2.prev = _ref1[1] : void 0, currentNode.next = _ref1[2], nodeToAdd.prev = _ref1[3];
}
}
if (position === this.size) {
this.tail = nodeToAdd;
}
this.size++;
return value;
};
LinkedList.prototype.removeAt = function(position) {
var currentNode, valueToReturn, _ref;
if (position == null) {
position = this.size - 1;
}
/*
Remove an item at index `position` (optional). Defaults to the last item.
Index can be negative (within the boundary).
_Returns:_ item removed.
*/
if (!((-this.size <= position && position < this.size))) {
return;
}
if (this.size === 0) {
return;
}
position = this._adjust(position);
if (this.size === 1) {
valueToReturn = this.head.value;
this.head.value = this.tail.value = void 0;
} else {
if (position === 0) {
valueToReturn = this.head.value;
this.head = this.head.next;
this.head.prev = void 0;
} else {
currentNode = this.at(position);
valueToReturn = currentNode.value;
currentNode.prev.next = currentNode.next;
if ((_ref = currentNode.next) != null) {
_ref.prev = currentNode.prev;
}
if (position === this.size - 1) {
this.tail = currentNode.prev;
}
}
}
this.size--;
return valueToReturn;
};
LinkedList.prototype.remove = function(value) {
/*
Remove the item using its value instead of position. **Will remove the fist
occurrence of `value`.**
_Returns:_ the value, or undefined if value's not found.
*/
var currentNode;
if (value == null) {
return;
}
currentNode = this.head;
while (currentNode && currentNode.value !== value) {
currentNode = currentNode.next;
}
if (!currentNode) {
return;
}
if (this.size === 1) {
this.head.value = this.tail.value = void 0;
} else if (currentNode === this.head) {
this.head = this.head.next;
this.head.prev = void 0;
} else if (currentNode === this.tail) {
this.tail = this.tail.prev;
this.tail.next = void 0;
} else {
currentNode.prev.next = currentNode.next;
currentNode.next.prev = currentNode.prev;
}
this.size--;
return value;
};
LinkedList.prototype.indexOf = function(value, startingPosition) {
var currentNode, position;
if (startingPosition == null) {
startingPosition = 0;
}
/*
Find the index of an item, similarly to `array.indexOf()`. Defaults to start
searching from the beginning, by can start at another position by passing
`startingPosition`. This parameter can also be negative; but unlike the
other methods of this class, `startingPosition` (optional) can be as small
as desired; a value of -999 for a list of size 5 will start searching
normally, at the beginning.
**Note:** searches forwardly, **not** backwardly, i.e:
```js
var myList = new LinkedList([2, 3, 1, 4, 3, 5])
myList.indexOf(3, -3); // Returns 4, not 1
```
_Returns:_ index of item found, or -1 if not found.
*/
if (((this.head.value == null) && !this.head.next) || startingPosition >= this.size) {
return -1;
}
startingPosition = Math.max(0, this._adjust(startingPosition));
currentNode = this.at(startingPosition);
position = startingPosition;
while (currentNode) {
if (currentNode.value === value) {
break;
}
currentNode = currentNode.next;
position++;
}
if (position === this.size) {
return -1;
} else {
return position;
}
};
LinkedList.prototype._adjust = function(position) {
if (position < 0) {
return this.size + position;
} else {
return position;
}
};
return LinkedList;
})();
module.exports = LinkedList;
}).call(this);
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
/*
Kind of a stopgap measure for the upcoming [JavaScript
Map](http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets)
**Note:** due to JavaScript's limitations, hashing something other than Boolean,
Number, String, Undefined, Null, RegExp, Function requires a hack that inserts a
hidden unique property into the object. This means `set`, `get`, `has` and
`delete` must employ the same object, and not a mere identical copy as in the
case of, say, a string.
## Overview example:
```js
var map = new Map({'alice': 'wonderland', 20: 'ok'});
map.set('20', 5); // => 5
map.get('20'); // => 5
map.has('alice'); // => true
map.delete(20) // => true
var arr = [1, 2];
map.add(arr, 'goody'); // => 'goody'
map.has(arr); // => true
map.has([1, 2]); // => false. Needs to compare by reference
map.forEach(function(key, value) {
console.log(key, value);
});
```
## Properties:
- size: The total number of `(key, value)` pairs.
*/
(function() {
var Map, SPECIAL_TYPE_KEY_PREFIX, _extractDataType, _isSpecialType,
__hasProp = {}.hasOwnProperty;
SPECIAL_TYPE_KEY_PREFIX = '_mapId_';
Map = (function() {
Map._mapIdTracker = 0;
Map._newMapId = function() {
return this._mapIdTracker++;
};
function Map(objectToMap) {
/*
Pass an optional object whose (key, value) pair will be hashed. **Careful**
not to pass something like {5: 'hi', '5': 'hello'}, since JavaScript's
native object behavior will crush the first 5 property before it gets to
constructor.
*/
var key, value;
this._content = {};
this._itemId = 0;
this._id = Map._newMapId();
this.size = 0;
for (key in objectToMap) {
if (!__hasProp.call(objectToMap, key)) continue;
value = objectToMap[key];
this.set(key, value);
}
}
Map.prototype.hash = function(key, makeHash) {
var propertyForMap, type;
if (makeHash == null) {
makeHash = false;
}
/*
The hash function for hashing keys is public. Feel free to replace it with
your own. The `makeHash` parameter is optional and accepts a boolean
(defaults to `false`) indicating whether or not to produce a new hash (for
the first use, naturally).
_Returns:_ the hash.
*/
type = _extractDataType(key);
if (_isSpecialType(key)) {
propertyForMap = SPECIAL_TYPE_KEY_PREFIX + this._id;
if (makeHash && !key[propertyForMap]) {
key[propertyForMap] = this._itemId++;
}
return propertyForMap + '_' + key[propertyForMap];
} else {
return type + '_' + key;
}
};
Map.prototype.set = function(key, value) {
/*
_Returns:_ value.
*/
if (!this.has(key)) {
this.size++;
}
this._content[this.hash(key, true)] = [value, key];
return value;
};
Map.prototype.get = function(key) {
/*
_Returns:_ value corresponding to the key, or undefined if not found.
*/
var _ref;
return (_ref = this._content[this.hash(key)]) != null ? _ref[0] : void 0;
};
Map.prototype.has = function(key) {
/*
Check whether a value exists for the key.
_Returns:_ true or false.
*/
return this.hash(key) in this._content;
};
Map.prototype["delete"] = function(key) {
/*
Remove the (key, value) pair.
_Returns:_ **true or false**. Unlike most of this library, this method
doesn't return the deleted value. This is so that it conforms to the future
JavaScript `map.delete()`'s behavior.
*/
var hashedKey;
hashedKey = this.hash(key);
if (hashedKey in this._content) {
delete this._content[hashedKey];
if (_isSpecialType(key)) {
delete key[SPECIAL_TYPE_KEY_PREFIX + this._id];
}
this.size--;
return true;
}
return false;
};
Map.prototype.forEach = function(operation) {
/*
Traverse through the map. Pass a function of the form `fn(key, value)`.
_Returns:_ undefined.
*/
var key, value, _ref;
_ref = this._content;
for (key in _ref) {
if (!__hasProp.call(_ref, key)) continue;
value = _ref[key];
operation(value[1], value[0]);
}
};
return Map;
})();
_isSpecialType = function(key) {
var simpleHashableTypes, simpleType, type, _i, _len;
simpleHashableTypes = ['Boolean', 'Number', 'String', 'Undefined', 'Null', 'RegExp', 'Function'];
type = _extractDataType(key);
for (_i = 0, _len = simpleHashableTypes.length; _i < _len; _i++) {
simpleType = simpleHashableTypes[_i];
if (type === simpleType) {
return false;
}
}
return true;
};
_extractDataType = function(type) {
return Object.prototype.toString.apply(type).match(/\[object (.+)\]/)[1];
};
module.exports = Map;
}).call(this);
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/*
Amortized O(1) dequeue!
## Overview example:
```js
var queue = new Queue([1, 6, 4]);
queue.enqueue(10); // => 10
queue.dequeue(); // => 1
queue.dequeue(); // => 6
queue.dequeue(); // => 4
queue.peek(); // => 10
queue.dequeue(); // => 10
queue.peek(); // => undefined
```
## Properties:
- size: The total number of items.
*/
(function() {
var Queue;
Queue = (function() {
function Queue(initialArray) {
if (initialArray == null) {
initialArray = [];
}
/*
Pass an optional array to be transformed into a queue. The item at index 0
is the first to be dequeued.
*/
this._content = initialArray;
this._dequeueIndex = 0;
this.size = this._content.length;
}
Queue.prototype.enqueue = function(item) {
/*
_Returns:_ the item.
*/
this.size++;
this._content.push(item);
return item;
};
Queue.prototype.dequeue = function() {
/*
_Returns:_ the dequeued item.
*/
var itemToDequeue;
if (this.size === 0) {
return;
}
this.size--;
itemToDequeue = this._content[this._dequeueIndex];
this._dequeueIndex++;
if (this._dequeueIndex * 2 > this._content.length) {
this._content = this._content.slice(this._dequeueIndex);
this._dequeueIndex = 0;
}
return itemToDequeue;
};
Queue.prototype.peek = function() {
/*
Check the next item to be dequeued, without removing it.
_Returns:_ the item.
*/
return this._content[this._dequeueIndex];
};
return Queue;
})();
module.exports = Queue;
}).call(this);
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
/*
Credit to Wikipedia's article on [Red-black
tree](http://en.wikipedia.org/wiki/Red–black_tree)
**Note:** doesn't handle duplicate entries, undefined and null. This is by
design.
## Overview example:
```js
var rbt = new RedBlackTree([7, 5, 1, 8]);
rbt.add(2); // => 2
rbt.add(10); // => 10
rbt.has(5); // => true
rbt.peekMin(); // => 1
rbt.peekMax(); // => 10
rbt.removeMin(); // => 1
rbt.removeMax(); // => 10
rbt.remove(8); // => 8
```
## Properties:
- size: The total number of items.
*/
(function() {
var BLACK, NODE_FOUND, NODE_TOO_BIG, NODE_TOO_SMALL, RED, RedBlackTree, STOP_SEARCHING, _findNode, _grandParentOf, _isLeft, _leftOrRight, _peekMaxNode, _peekMinNode, _siblingOf, _uncleOf;
NODE_FOUND = 0;
NODE_TOO_BIG = 1;
NODE_TOO_SMALL = 2;
STOP_SEARCHING = 3;
RED = 1;
BLACK = 2;
RedBlackTree = (function() {
function RedBlackTree(valuesToAdd) {
var value, _i, _len;
if (valuesToAdd == null) {
valuesToAdd = [];
}
/*
Pass an optional array to be turned into binary tree. **Note:** does not
accept duplicate, undefined and null.
*/
this._root;
this.size = 0;
for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) {
value = valuesToAdd[_i];
if (value != null) {
this.add(value);
}
}
}
RedBlackTree.prototype.add = function(value) {
/*
Again, make sure to not pass a value already in the tree, or undefined, or
null.
_Returns:_ value added.
*/
var currentNode, foundNode, nodeToInsert, _ref;
if (value == null) {
return;
}
this.size++;
nodeToInsert = {
value: value,
_color: RED
};
if (!this._root) {
this._root = nodeToInsert;
} else {
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else {
if (value < node.value) {
if (node._left) {
return NODE_TOO_BIG;
} else {
nodeToInsert._parent = node;
node._left = nodeToInsert;
return STOP_SEARCHING;
}
} else {
if (node._right) {
return NODE_TOO_SMALL;
} else {
nodeToInsert._parent = node;
node._right = nodeToInsert;
return STOP_SEARCHING;
}
}
}
});
if (foundNode != null) {
return;
}
}
currentNode = nodeToInsert;
while (true) {
if (currentNode === this._root) {
currentNode._color = BLACK;
break;
}
if (currentNode._parent._color === BLACK) {
break;
}
if (((_ref = _uncleOf(currentNode)) != null ? _ref._color : void 0) === RED) {
currentNode._parent._color = BLACK;
_uncleOf(currentNode)._color = BLACK;
_grandParentOf(currentNode)._color = RED;
currentNode = _grandParentOf(currentNode);
continue;
}
if (!_isLeft(currentNode) && _isLeft(currentNode._parent)) {
this._rotateLeft(currentNode._parent);
currentNode = currentNode._left;
} else if (_isLeft(currentNode) && !_isLeft(currentNode._parent)) {
this._rotateRight(currentNode._parent);
currentNode = currentNode._right;
}
currentNode._parent._color = BLACK;
_grandParentOf(currentNode)._color = RED;
if (_isLeft(currentNode)) {
this._rotateRight(_grandParentOf(currentNode));
} else {
this._rotateLeft(_grandParentOf(currentNode));
}
break;
}
return value;
};
RedBlackTree.prototype.has = function(value) {
/*
_Returns:_ true or false.
*/
var foundNode;
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else if (value < node.value) {
return NODE_TOO_BIG;
} else {
return NODE_TOO_SMALL;
}
});
if (foundNode) {
return true;
} else {
return false;
}
};
RedBlackTree.prototype.peekMin = function() {
/*
Check the minimum value without removing it.
_Returns:_ the minimum value.
*/
var _ref;
return (_ref = _peekMinNode(this._root)) != null ? _ref.value : void 0;
};
RedBlackTree.prototype.peekMax = function() {
/*
Check the maximum value without removing it.
_Returns:_ the maximum value.
*/
var _ref;
return (_ref = _peekMaxNode(this._root)) != null ? _ref.value : void 0;
};
RedBlackTree.prototype.remove = function(value) {
/*
_Returns:_ the value removed, or undefined if the value's not found.
*/
var foundNode;
foundNode = _findNode(this._root, function(node) {
if (value === node.value) {
return NODE_FOUND;
} else if (value < node.value) {
return NODE_TOO_BIG;
} else {
return NODE_TOO_SMALL;
}
});
if (!foundNode) {
return;
}
this._removeNode(this._root, foundNode);
this.size--;
return value;
};
RedBlackTree.prototype.removeMin = function() {
/*
_Returns:_ smallest item removed, or undefined if tree's empty.
*/
var nodeToRemove, valueToReturn;
nodeToRemove = _peekMinNode(this._root);
if (!nodeToRemove) {
return;
}
valueToReturn = nodeToRemove.value;
this._removeNode(this._root, nodeToRemove);
return valueToReturn;
};
RedBlackTree.prototype.removeMax = function() {
/*
_Returns:_ biggest item removed, or undefined if tree's empty.
*/
var nodeToRemove, valueToReturn;
nodeToRemove = _peekMaxNode(this._root);
if (!nodeToRemove) {
return;
}
valueToReturn = nodeToRemove.value;
this._removeNode(this._root, nodeToRemove);
return valueToReturn;
};
RedBlackTree.prototype._removeNode = function(root, node) {
var sibling, successor, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
if (node._left && node._right) {
successor = _peekMinNode(node._right);
node.value = successor.value;
node = successor;
}
successor = node._left || node._right;
if (!successor) {
successor = {
color: BLACK,
_right: void 0,
_left: void 0,
isLeaf: true
};
}
successor._parent = node._parent;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = successor;
}
if (node._color === BLACK) {
if (successor._color === RED) {
successor._color = BLACK;
if (!successor._parent) {
this._root = successor;
}
} else {
while (true) {
if (!successor._parent) {
if (!successor.isLeaf) {
this._root = successor;
} else {
this._root = void 0;
}
break;
}
sibling = _siblingOf(successor);
if ((sibling != null ? sibling._color : void 0) === RED) {
successor._parent._color = RED;
sibling._color = BLACK;
if (_isLeft(successor)) {
this._rotateLeft(successor._parent);
} else {
this._rotateRight(successor._parent);
}
}
sibling = _siblingOf(successor);
if (successor._parent._color === BLACK && (!sibling || (sibling._color === BLACK && (!sibling._left || sibling._left._color === BLACK) && (!sibling._right || sibling._right._color === BLACK)))) {
if (sibling != null) {
sibling._color = RED;
}
if (successor.isLeaf) {
successor._parent[_leftOrRight(successor)] = void 0;
}
successor = successor._parent;
continue;
}
if (successor._parent._color === RED && (!sibling || (sibling._color === BLACK && (!sibling._left || ((_ref1 = sibling._left) != null ? _ref1._color : void 0) === BLACK) && (!sibling._right || ((_ref2 = sibling._right) != null ? _ref2._color : void 0) === BLACK)))) {
if (sibling != null) {
sibling._color = RED;
}
successor._parent._color = BLACK;
break;
}
if ((sibling != null ? sibling._color : void 0) === BLACK) {
if (_isLeft(successor) && (!sibling._right || sibling._right._color === BLACK) && ((_ref3 = sibling._left) != null ? _ref3._color : void 0) === RED) {
sibling._color = RED;
if ((_ref4 = sibling._left) != null) {
_ref4._color = BLACK;
}
this._rotateRight(sibling);
} else if (!_isLeft(successor) && (!sibling._left || sibling._left._color === BLACK) && ((_ref5 = sibling._right) != null ? _ref5._color : void 0) === RED) {
sibling._color = RED;
if ((_ref6 = sibling._right) != null) {
_ref6._color = BLACK;
}
this._rotateLeft(sibling);
}
break;
}
sibling = _siblingOf(successor);
sibling._color = successor._parent._color;
if (_isLeft(successor)) {
sibling._right._color = BLACK;
this._rotateRight(successor._parent);
} else {
sibling._left._color = BLACK;
this._rotateLeft(successor._parent);
}
}
}
}
if (successor.isLeaf) {
return (_ref7 = successor._parent) != null ? _ref7[_leftOrRight(successor)] = void 0 : void 0;
}
};
RedBlackTree.prototype._rotateLeft = function(node) {
var _ref, _ref1;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = node._right;
}
node._right._parent = node._parent;
node._parent = node._right;
node._right = node._right._left;
node._parent._left = node;
if ((_ref1 = node._right) != null) {
_ref1._parent = node;
}
if (node._parent._parent == null) {
return this._root = node._parent;
}
};
RedBlackTree.prototype._rotateRight = function(node) {
var _ref, _ref1;
if ((_ref = node._parent) != null) {
_ref[_leftOrRight(node)] = node._left;
}
node._left._parent = node._parent;
node._parent = node._left;
node._left = node._left._right;
node._parent._right = node;
if ((_ref1 = node._left) != null) {
_ref1._parent = node;
}
if (node._parent._parent == null) {
return this._root = node._parent;
}
};
return RedBlackTree;
})();
_isLeft = function(node) {
return node === node._parent._left;
};
_leftOrRight = function(node) {
if (_isLeft(node)) {
return '_left';
} else {
return '_right';
}
};
_findNode = function(startingNode, comparator) {
var comparisonResult, currentNode, foundNode;
currentNode = startingNode;
foundNode = void 0;
while (currentNode) {
comparisonResult = comparator(currentNode);
if (comparisonResult === NODE_FOUND) {
foundNode = currentNode;
break;
}
if (comparisonResult === NODE_TOO_BIG) {
currentNode = currentNode._left;
} else if (comparisonResult === NODE_TOO_SMALL) {
currentNode = currentNode._right;
} else if (comparisonResult === STOP_SEARCHING) {
break;
}
}
return foundNode;
};
_peekMinNode = function(startingNode) {
return _findNode(startingNode, function(node) {
if (node._left) {
return NODE_TOO_BIG;
} else {
return NODE_FOUND;
}
});
};
_peekMaxNode = function(startingNode) {
return _findNode(startingNode, function(node) {
if (node._right) {
return NODE_TOO_SMALL;
} else {
return NODE_FOUND;
}
});
};
_grandParentOf = function(node) {
var _ref;
return (_ref = node._parent) != null ? _ref._parent : void 0;
};
_uncleOf = function(node) {
if (!_grandParentOf(node)) {
return;
}
if (_isLeft(node._parent)) {
return _grandParentOf(node)._right;
} else {
return _grandParentOf(node)._left;
}
};
_siblingOf = function(node) {
if (_isLeft(node)) {
return node._parent._right;
} else {
return node._parent._left;
}
};
module.exports = RedBlackTree;
}).call(this);
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/*
Good for fast insertion/removal/lookup of strings.
## Overview example:
```js
var trie = new Trie(['bear', 'beer']);
trie.add('hello'); // => 'hello'
trie.add('helloha!'); // => 'helloha!'
trie.has('bears'); // => false
trie.longestPrefixOf('beatrice'); // => 'bea'
trie.wordsWithPrefix('hel'); // => ['hello', 'helloha!']
trie.remove('beers'); // => undefined. 'beer' still exists
trie.remove('Beer') // => undefined. Case-sensitive
trie.remove('beer') // => 'beer'. Removed
```
## Properties:
- size: The total number of words.
*/
(function() {
var Queue, Trie, WORD_END, _hasAtLeastNChildren,
__hasProp = {}.hasOwnProperty;
Queue = __webpack_require__(6);
WORD_END = 'end';
Trie = (function() {
function Trie(words) {
var word, _i, _len;
if (words == null) {
words = [];
}
/*
Pass an optional array of strings to be inserted initially.
*/
this._root = {};
this.size = 0;
for (_i = 0, _len = words.length; _i < _len; _i++) {
word = words[_i];
this.add(word);
}
}
Trie.prototype.add = function(word) {
/*
Add a whole string to the trie.
_Returns:_ the word added. Will return undefined (without adding the value)
if the word passed is null or undefined.
*/
var currentNode, letter, _i, _len;
if (word == null) {
return;
}
this.size++;
currentNode = this._root;
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
currentNode[letter] = {};
}
currentNode = currentNode[letter];
}
currentNode[WORD_END] = true;
return word;
};
Trie.prototype.has = function(word) {
/*
__Returns:_ true or false.
*/
var currentNode, letter, _i, _len;
if (word == null) {
return false;
}
currentNode = this._root;
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
return false;
}
currentNode = currentNode[letter];
}
if (currentNode[WORD_END]) {
return true;
} else {
return false;
}
};
Trie.prototype.longestPrefixOf = function(word) {
/*
Find all words containing the prefix. The word itself counts as a prefix.
```js
var trie = new Trie;
trie.add('hello');
trie.longestPrefixOf('he'); // 'he'
trie.longestPrefixOf('hello'); // 'hello'
trie.longestPrefixOf('helloha!'); // 'hello'
```
_Returns:_ the prefix string, or empty string if no prefix found.
*/
var currentNode, letter, prefix, _i, _len;
if (word == null) {
return '';
}
currentNode = this._root;
prefix = '';
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
break;
}
prefix += letter;
currentNode = currentNode[letter];
}
return prefix;
};
Trie.prototype.wordsWithPrefix = function(prefix) {
/*
Find all words containing the prefix. The word itself counts as a prefix.
**Watch out for edge cases.**
```js
var trie = new Trie;
trie.wordsWithPrefix(''); // []. Check later case below.
trie.add('');
trie.wordsWithPrefix(''); // ['']
trie.add('he');
trie.add('hello');
trie.add('hell');
trie.add('bear');
trie.add('z');
trie.add('zebra');
trie.wordsWithPrefix('hel'); // ['hell', 'hello']
```
_Returns:_ an array of strings, or empty array if no word found.
*/
var accumulatedLetters, currentNode, letter, node, queue, subNode, words, _i, _len, _ref;
if (prefix == null) {
return [];
}
(prefix != null) || (prefix = '');
words = [];
currentNode = this._root;
for (_i = 0, _len = prefix.length; _i < _len; _i++) {
letter = prefix[_i];
currentNode = currentNode[letter];
if (currentNode == null) {
return [];
}
}
queue = new Queue();
queue.enqueue([currentNode, '']);
while (queue.size !== 0) {
_ref = queue.dequeue(), node = _ref[0], accumulatedLetters = _ref[1];
if (node[WORD_END]) {
words.push(prefix + accumulatedLetters);
}
for (letter in node) {
if (!__hasProp.call(node, letter)) continue;
subNode = node[letter];
queue.enqueue([subNode, accumulatedLetters + letter]);
}
}
return words;
};
Trie.prototype.remove = function(word) {
/*
_Returns:_ the string removed, or undefined if the word in its whole doesn't
exist. **Note:** this means removing `beers` when only `beer` exists will
return undefined and conserve `beer`.
*/
var currentNode, i, letter, prefix, _i, _j, _len, _ref;
if (word == null) {
return;
}
currentNode = this._root;
prefix = [];
for (_i = 0, _len = word.length; _i < _len; _i++) {
letter = word[_i];
if (currentNode[letter] == null) {
return;
}
currentNode = currentNode[letter];
prefix.push([letter, currentNode]);
}
if (!currentNode[WORD_END]) {
return;
}
this.size--;
delete currentNode[WORD_END];
if (_hasAtLeastNChildren(currentNode, 1)) {
return word;
}
for (i = _j = _ref = prefix.length - 1; _ref <= 1 ? _j <= 1 : _j >= 1; i = _ref <= 1 ? ++_j : --_j) {
if (!_hasAtLeastNChildren(prefix[i][1], 1)) {
delete prefix[i - 1][1][prefix[i][0]];
} else {
break;
}
}
if (!_hasAtLeastNChildren(this._root[prefix[0][0]], 1)) {
delete this._root[prefix[0][0]];
}
return word;
};
return Trie;
})();
_hasAtLeastNChildren = function(node, n) {
var child, childCount;
if (n === 0) {
return true;
}
childCount = 0;
for (child in node) {
if (!__hasProp.call(node, child)) continue;
childCount++;
if (childCount >= n) {
return true;
}
}
return false;
};
module.exports = Trie;
}).call(this);
/***/ }
/******/ ]);/**
* Performance overrides on MarkerClusterer custom to Angular Google Maps
*
* Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14.
*/
angular.module('uiGmapgoogle-maps.extensions')
.service('uiGmapExtendMarkerClusterer',['uiGmapLodash', 'uiGmapPropMap', function (uiGmapLodash, PropMap) {
return {
init: _.once(function () {
(function () {
var __hasProp = {}.hasOwnProperty,
__extends = function (child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
window.NgMapCluster = (function (_super) {
__extends(NgMapCluster, _super);
function NgMapCluster(opts) {
NgMapCluster.__super__.constructor.call(this, opts);
this.markers_ = new PropMap();
}
/**
* Adds a marker to the cluster.
*
* @param {google.maps.Marker} marker The marker to be added.
* @return {boolean} True if the marker was added.
* @ignore
*/
NgMapCluster.prototype.addMarker = function (marker) {
var i;
var mCount;
var mz;
if (this.isMarkerAlreadyAdded_(marker)) {
var oldMarker = this.markers_.get(marker.key);
if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
mCount = this.markers_.length;
mz = this.markerClusterer_.getMaxZoom();
if (mz !== null && this.map_.getZoom() > mz) {
// Zoomed in past max zoom, so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount < this.minClusterSize_) {
// Min cluster size not reached so show the marker.
if (marker.getMap() !== this.map_) {
marker.setMap(this.map_);
}
} else if (mCount === this.minClusterSize_) {
// Hide the markers that were showing.
this.markers_.each(function (m) {
m.setMap(null);
});
} else {
marker.setMap(null);
}
//this.updateIcon_();
return true;
};
/**
* Determines if a marker has already been added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker has already been added.
*/
NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) {
return uiGmapLodash.isNullOrUndefined(this.markers_.get(marker.key));
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
* @ignore
*/
NgMapCluster.prototype.getBounds = function () {
var i;
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.getMarkers().each(function(m){
bounds.extend(m.getPosition());
});
return bounds;
};
/**
* Removes the cluster from the map.
*
* @ignore
*/
NgMapCluster.prototype.remove = function () {
this.clusterIcon_.setMap(null);
this.markers_ = new PropMap();
delete this.markers_;
};
return NgMapCluster;
})(Cluster);
window.NgMapMarkerClusterer = (function (_super) {
__extends(NgMapMarkerClusterer, _super);
function NgMapMarkerClusterer(map, opt_markers, opt_options) {
NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options);
this.markers_ = new PropMap();
}
/**
* Removes all clusters and markers from the map and also removes all markers
* managed by the clusterer.
*/
NgMapMarkerClusterer.prototype.clearMarkers = function () {
this.resetViewport_(true);
this.markers_ = new PropMap();
};
/**
* Removes a marker and returns true if removed, false if not.
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
*/
NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) {
if (!this.markers_.get(marker.key)) {
return false;
}
marker.setMap(null);
this.markers_.remove(marker.key); // Remove the marker from the list of managed markers
return true;
};
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) {
var i, marker;
var mapBounds;
var cMarkerClusterer = this;
if (!this.ready_) {
return;
}
// Cancel previous batch processing if we're working on the first batch:
if (iFirst === 0) {
/**
* This event is fired when the <code>MarkerClusterer</code> begins
* clustering markers.
* @name MarkerClusterer#clusteringbegin
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, 'clusteringbegin', this);
if (typeof this.timerRefStatic !== 'undefined') {
clearTimeout(this.timerRefStatic);
delete this.timerRefStatic;
}
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
//
// See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
if (this.getMap().getZoom() > 3) {
mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
this.getMap().getBounds().getNorthEast());
} else {
mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
}
var bounds = this.getExtendedBounds(mapBounds);
var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);
var _ms = this.markers_.values();
for (i = iFirst; i < iLast; i++) {
marker = _ms[i];
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {
this.addToClosestCluster_(marker);
}
}
}
if (iLast < this.markers_.length) {
this.timerRefStatic = setTimeout(function () {
cMarkerClusterer.createClusters_(iLast);
}, 0);
} else {
// custom addition by ui-gmap
// update icon for all clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].updateIcon_();
}
delete this.timerRefStatic;
/**
* This event is fired when the <code>MarkerClusterer</code> stops
* clustering markers.
* @name MarkerClusterer#clusteringend
* @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
* @event
*/
google.maps.event.trigger(this, 'clusteringend', this);
}
};
/**
* Adds a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
*/
NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) {
var i, d, cluster, center;
var distance = 40000; // Some large number
var clusterToAddTo = null;
for (i = 0; i < this.clusters_.length; i++) {
cluster = this.clusters_[i];
center = cluster.getCenter();
if (center) {
d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
cluster = new NgMapCluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Redraws all the clusters.
*/
NgMapMarkerClusterer.prototype.redraw_ = function () {
this.createClusters_(0);
};
/**
* Removes all clusters from the map. The markers are also removed from the map
* if <code>opt_hide</code> is set to <code>true</code>.
*
* @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
* from the map.
*/
NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) {
var i, marker;
// Remove all the clusters
for (i = 0; i < this.clusters_.length; i++) {
this.clusters_[i].remove();
}
this.clusters_ = [];
// Reset the markers to not be added and to be removed from the map.
this.markers_.each(function (marker) {
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
});
};
/**
* Extends an object's prototype by another's.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) {
return (function (object) {
var property;
for (property in object.prototype) {
if (property !== 'constructor')
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
////////////////////////////////////////////////////////////////////////////////
/*
Other overrides relevant to MarkerClusterPlus
*/
////////////////////////////////////////////////////////////////////////////////
/**
* Positions and shows the icon.
*/
ClusterIcon.prototype.show = function () {
if (this.div_) {
var img = "";
// NOTE: values must be specified in px units
var bp = this.backgroundPosition_.split(" ");
var spriteH = parseInt(bp[0].trim(), 10);
var spriteV = parseInt(bp[1].trim(), 10);
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
}
// ADDED FOR RETINA SUPPORT
else {
img += "width: " + this.width_ + "px;" + "height: " + this.height_ + "px;";
}
// END ADD
img += "'>";
this.div_.innerHTML = img + "<div style='" +
"position: absolute;" +
"top: " + this.anchorText_[0] + "px;" +
"left: " + this.anchorText_[1] + "px;" +
"color: " + this.textColor_ + ";" +
"font-size: " + this.textSize_ + "px;" +
"font-family: " + this.fontFamily_ + ";" +
"font-weight: " + this.fontWeight_ + ";" +
"font-style: " + this.fontStyle_ + ";" +
"text-decoration: " + this.textDecoration_ + ";" +
"text-align: center;" +
"width: " + this.width_ + "px;" +
"line-height:" + this.height_ + "px;" +
"'>" + this.sums_.text + "</div>";
if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
} else {
this.div_.title = this.sums_.title;
}
this.div_.style.display = "";
}
this.visible_ = true;
};
//END OTHER OVERRIDES
////////////////////////////////////////////////////////////////////////////////
return NgMapMarkerClusterer;
})(MarkerClusterer);
}).call(this);
})
};
}]);
}( window,angular)); |
app/packs/src/components/MoleculeModeratorComponent.js | ComPlat/chemotion_ELN | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Col, Panel, Button, Row, FormControl, Table, Popover, ButtonGroup, Modal, OverlayTrigger, Tooltip, Form, FormGroup, InputGroup } from 'react-bootstrap';
import SVG from 'react-inlinesvg';
import { findIndex } from 'lodash';
import StructureEditorModal from './structure_editor/StructureEditorModal';
import MoleculesFetcher from './fetchers/MoleculesFetcher';
export default class MoleculeModeratorComponent extends Component {
constructor(props) {
super(props);
this.state = {
show: false,
isNew: false,
molName: {},
molNames: (this.props.molecule && this.props.molecule.molecule_names) || []
};
this.handleStructureEditorSave = this.handleStructureEditorSave.bind(this);
this.handleStructureEditorCancel = this.handleStructureEditorCancel.bind(this);
this.handleSave = this.handleSave.bind(this);
this.confirmDelete = this.confirmDelete.bind(this);
this.handleShowModal = this.handleShowModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
this.onSaveName = this.onSaveName.bind(this);
this.onAddName = this.onAddName.bind(this);
}
componentDidUpdate(prevProps) {
if (this.props !== prevProps) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({
molNames: (this.props.molecule && this.props.molecule.molecule_names) || []
});
}
}
onAddName() {
const molName = {
id: -1,
description: 'defined by user',
name: ''
};
this.setState({
molName,
isNew: true,
show: true
});
}
onSaveName() {
const { molecule } = this.props;
const { molNames, molName, isNew } = this.state;
const name = this.m_name.value.trim();
if (name == '') {
// eslint-disable-next-line no-alert
alert('Please input name!');
return false;
}
molName.name = name;
const params = {
id: molecule.id,
name_id: molName.id,
description: molName.description,
name
};
MoleculesFetcher.saveMoleculeName(params).then((result) => {
if (result.error) {
console.log(result);
alert(result.error);
} else {
if (isNew == true) {
molNames.push(result);
} else {
const idx = findIndex(molNames, o => o.id === molName.id);
molNames.splice(idx, 1, molName);
}
this.setState({
show: false,
molNames
});
}
});
return true;
}
handleStructureEditorCancel() {
this.props.handleEditor(false);
}
handleStructureEditorSave(molfile, svg_file = null, config = null) {
this.props.handleEditorSave(molfile, svg_file, config);
}
handleSave() {
this.props.onSave();
}
handleShowModal(nameObj, isNew = false) {
this.setState({
show: true,
isNew,
molName: nameObj
});
}
handleCloseModal() {
this.setState({
show: false
});
}
confirmDelete(nameObj) {
const { molNames } = this.state;
const params = { id: nameObj.id };
MoleculesFetcher.deleteMoleculeName(params).then((result) => {
if (result.error) {
console.log(result);
alert(result.error);
} else {
const idx = findIndex(molNames, o => o.id === nameObj.id);
molNames.splice(idx, 1);
this.setState({
molNames
});
}
});
}
renderDeleteButton(nameObj) {
const popover = (
<Popover id="popover-positioned-scrolling-left">
delete this molecule name <br />
<div className="btn-toolbar">
<Button bsSize="xsmall" bsStyle="danger" onClick={() => this.confirmDelete(nameObj)}>
Yes
</Button><span> </span>
<Button bsSize="xsmall" bsStyle="warning" onClick={this.handleClick} >
No
</Button>
</div>
</Popover>
);
return (
<ButtonGroup className="actions">
<OverlayTrigger
animation
placement="right"
root
trigger="focus"
overlay={popover}
>
<Button bsSize="xsmall" bsStyle="danger" >
<i className="fa fa-trash-o" />
</Button>
</OverlayTrigger>
</ButtonGroup>
);
}
renderEditButton(nameObj) {
return (
<OverlayTrigger placement="top" overlay={<Tooltip id="groupUsersAdd">Edit molecule name</Tooltip>}>
<Button bsSize="xsmall" bsStyle="primary" type="button" onClick={() => this.handleShowModal(nameObj)} >
<i className="fa fa-pencil-square-o" />
</Button>
</OverlayTrigger>
);
}
renderModal() {
const { show, isNew, molName } = this.state;
return (
<Modal show={show} onHide={this.handleCloseModal}>
<Modal.Header closeButton>
<Modal.Title>{isNew ? 'Create Molecule Name' : 'Edit Molecule Name'}</Modal.Title>
</Modal.Header>
<Modal.Body>
<Panel bsStyle="success">
<Panel.Heading>
<Panel.Title>
{isNew ? 'Create Molecule Name' : 'Edit Molecule Name'}
</Panel.Title>
</Panel.Heading>
<Panel.Body>
<Form horizontal className="input-form">
<FormGroup controlId="formControlId">
<InputGroup>
<InputGroup.Addon>Attr.</InputGroup.Addon>
<FormControl type="text" defaultValue={molName.description} readOnly />
</InputGroup>
</FormGroup>
<FormGroup controlId="formControlName">
<InputGroup>
<InputGroup.Addon>Molecule name</InputGroup.Addon>
<FormControl type="text" defaultValue={molName.name} inputRef={(ref) => { this.m_name = ref; }} />
</InputGroup>
</FormGroup>
</Form>
<Button bsSize="small" type="button" bsStyle="warning" onClick={() => this.onSaveName()}>Save</Button>
</Panel.Body>
</Panel>
</Modal.Body>
</Modal>
);
}
render() {
const { molNames } = this.state;
const componentEditor = (
<div className="search-structure-draw">
<StructureEditorModal
showModal={this.props.showStructureEditor}
onSave={this.handleStructureEditorSave}
onCancel={this.handleStructureEditorCancel}
molfile={this.props.molecule.molfile}
/>
</div>
);
const tbodyHeader = (
<thead>
<tr>
<td width="5%">#</td>
<td width="15%">Action
<OverlayTrigger placement="top" overlay={<Tooltip id="groupUsersAdd">Add new molecule name</Tooltip>}>
<Button bsSize="xsmall" bsStyle="success" onClick={() => this.onAddName()}>
<i className="fa fa-plus" />
</Button>
</OverlayTrigger>
</td>
<td width="20%">Attr.</td>
<td width="60%">Moledule Name</td>
</tr>
</thead>
);
const tbodyContent = molNames.map((na, i) => (
<tr key={`row_${na.id}`} id={`row_${na.id}`}>
<td>{i + 1}</td>
<td>
{ this.renderDeleteButton(na) }
{ this.renderEditButton(na) }
</td>
<td>{na.description}</td>
<td>{na.name}</td>
</tr>
));
return (
<div>
{componentEditor}
<div className="container">
<Panel>
<Panel.Heading>
<b>InChiKey:</b> {this.props.molecule.inchikey}
(<b>Chemotion molecule id:</b> {this.props.molecule.id})
<br />
<b>Canonical Smiles:</b> {this.props.molecule.cano_smiles}
</Panel.Heading>
<Panel.Body>
<Row>
<Col md={12}>
<Button bsStyle="primary" bsSize="sm" onClick={() => this.props.handleEditor(true)}>Open Editor <i className="fa fa-pencil" aria-hidden="true" /></Button>
<Button bsStyle="warning" bsSize="sm" onClick={() => this.handleSave()}>Update molfile and svg <i className="fa fa-floppy-o" aria-hidden="true" /></Button>
</Col>
</Row>
<Row>
<Col md={4}>
<b>molfile:</b><br />
<FormControl componentClass="textarea" placeholder="textarea" value={this.props.molecule.molfile} readOnly style={{ minHeight: 'calc(50vh)' }} />
</Col>
<Col md={8}>
<b>svg:</b><br />
<div className="svg-container">
<SVG key={this.props.molecule.molecule_svg_file} src={`/images/molecules/${this.props.molecule.molecule_svg_file}`} className="molecule-mid" />
</div>
</Col>
</Row>
<Row>
<Col md={12}>
<Table>
{tbodyHeader}
<tbody>
{tbodyContent}
</tbody>
</Table>
</Col>
</Row>
{ this.renderModal() }
</Panel.Body>
</Panel>
</div>
</div>
);
}
}
MoleculeModeratorComponent.propTypes = {
molecule: PropTypes.object,
showStructureEditor: PropTypes.bool.isRequired,
handleEditorSave: PropTypes.func.isRequired,
handleEditor: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired,
};
|
packages/node_modules/@webex/react-component-call-data-activity/src/index.js | ciscospark/react-ciscospark | import React from 'react';
import PropTypes from 'prop-types';
import {FormattedMessage} from 'react-intl';
import messages from './messages';
import {parseActivityCallData} from './helpers';
const propTypes = {
actor: PropTypes.shape({
displayName: PropTypes.string.isRequired
}),
duration: PropTypes.number.isRequired,
isGroupCall: PropTypes.bool.isRequired,
participants: PropTypes.arrayOf(
PropTypes.shape({
isInitiator: PropTypes.bool,
person: PropTypes.shape({
entryUUID: PropTypes.string
}),
state: PropTypes.string
})
).isRequired,
currentUser: PropTypes.shape({
id: PropTypes.string.isRequired
}).isRequired
};
const defaultProps = {
actor: {
displayName: ''
}
};
const CallDataActivityMessage = (props) => {
const {
actor,
duration,
isGroupCall,
participants,
currentUser
} = props;
const callData = {
actor,
duration,
isGroupCall,
participants
};
const parsedCallData = parseActivityCallData(callData, currentUser);
return parsedCallData && (
<FormattedMessage {...messages[parsedCallData.status]} values={{...parsedCallData.callInfo}} />
);
};
CallDataActivityMessage.propTypes = propTypes;
CallDataActivityMessage.defaultProps = defaultProps;
export default CallDataActivityMessage;
|
app/pages/patientprofile/patientprofile.js | hichameyessou/blip | import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../../redux/actions';
import _ from 'lodash';
import Patient from '../patient/';
/**
* Expose "Smart" Component that is connect-ed to Redux
*/
let getFetchers = (dispatchProps, ownProps, api) => {
return [
dispatchProps.fetchPatient.bind(null, api, ownProps.routeParams.id),
dispatchProps.fetchDataDonationAccounts.bind(null, api),
dispatchProps.fetchPendingSentInvites.bind(null, api),
];
};
export function mapStateToProps(state) {
let user = null;
let patient = null;
let permissions = {};
let permsOfLoggedInUser = {};
let {
allUsersMap,
loggedInUserId,
currentPatientInViewId,
} = state.blip;
if (allUsersMap){
if (loggedInUserId) {
user = allUsersMap[loggedInUserId];
}
if (currentPatientInViewId){
patient = allUsersMap[currentPatientInViewId];
permissions = _.get(
state.blip.permissionsOfMembersInTargetCareTeam,
state.blip.currentPatientInViewId,
{}
);
// if the logged-in user is viewing own data, we pass through their own permissions as permsOfLoggedInUser
if (state.blip.currentPatientInViewId === state.blip.loggedInUserId) {
permsOfLoggedInUser = permissions;
}
// otherwise, we need to pull the perms of the loggedInUser wrt the patient in view from membershipPermissionsInOtherCareTeams
else {
if (!_.isEmpty(state.blip.membershipPermissionsInOtherCareTeams)) {
permsOfLoggedInUser = state.blip.membershipPermissionsInOtherCareTeams[state.blip.currentPatientInViewId];
}
}
}
}
return {
user: user,
fetchingUser: state.blip.working.fetchingUser.inProgress,
patient: { permissions, ...patient },
permsOfLoggedInUser: permsOfLoggedInUser,
fetchingPatient: state.blip.working.fetchingPatient.inProgress,
dataDonationAccounts: state.blip.dataDonationAccounts,
updatingDataDonationAccounts: state.blip.working.updatingDataDonationAccounts.inProgress,
updatingPatientBgUnits: state.blip.working.updatingPatientBgUnits.inProgress,
dataSources: state.blip.dataSources || [],
authorizedDataSource: state.blip.authorizedDataSource,
};
}
let mapDispatchToProps = dispatch => bindActionCreators({
acknowledgeNotification: actions.sync.acknowledgeNotification,
fetchDataDonationAccounts: actions.async.fetchDataDonationAccounts,
fetchPatient: actions.async.fetchPatient,
fetchPendingSentInvites: actions.async.fetchPendingSentInvites,
fetchDataSources: actions.async.fetchDataSources,
updateDataDonationAccounts: actions.async.updateDataDonationAccounts,
updatePatient: actions.async.updatePatient,
updatePatientSettings: actions.async.updateSettings,
fetchDataSources: actions.async.fetchDataSources,
connectDataSource: actions.async.connectDataSource,
disconnectDataSource: actions.async.disconnectDataSource,
}, dispatch);
let mergeProps = (stateProps, dispatchProps, ownProps) => {
var api = ownProps.routes[0].api;
return Object.assign({}, stateProps, _.pick(dispatchProps, 'acknowledgeNotification'), {
fetchers: getFetchers(dispatchProps, ownProps, api),
onUpdateDataDonationAccounts: dispatchProps.updateDataDonationAccounts.bind(null, api),
onUpdatePatient: dispatchProps.updatePatient.bind(null, api),
onUpdatePatientSettings: dispatchProps.updatePatientSettings.bind(null, api),
fetchDataSources: dispatchProps.fetchDataSources.bind(null, api),
connectDataSource: dispatchProps.connectDataSource.bind(null, api),
disconnectDataSource: dispatchProps.disconnectDataSource.bind(null, api),
trackMetric: ownProps.routes[0].trackMetric,
queryParams: ownProps.location.query,
api: api
});
};
export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(Patient);
|
src/svg-icons/device/screen-rotation.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceScreenRotation = (props) => (
<SvgIcon {...props}>
<path d="M16.48 2.52c3.27 1.55 5.61 4.72 5.97 8.48h1.5C23.44 4.84 18.29 0 12 0l-.66.03 3.81 3.81 1.33-1.32zm-6.25-.77c-.59-.59-1.54-.59-2.12 0L1.75 8.11c-.59.59-.59 1.54 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12L10.23 1.75zm4.6 19.44L2.81 9.17l6.36-6.36 12.02 12.02-6.36 6.36zm-7.31.29C4.25 19.94 1.91 16.76 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32z"/>
</SvgIcon>
);
DeviceScreenRotation = pure(DeviceScreenRotation);
DeviceScreenRotation.displayName = 'DeviceScreenRotation';
DeviceScreenRotation.muiName = 'SvgIcon';
export default DeviceScreenRotation;
|
src/app.js | px3l/react-boilerplate | import React from 'react'
import ReactDOM from 'react-dom'
import injectTapEventPlugin from 'react-tap-event-plugin'
import { Provider } from 'react-redux'
import { applyMiddleware, compose, createStore, combineReducers } from 'redux'
import { Router, hashHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer, routerMiddleware } from 'react-router-redux'
import Routes from './routes'
import Reducer from './reducers/reducer'
const finalCreateStore = compose(
applyMiddleware(
routerMiddleware(hashHistory)
),
window.devToolsExtension ? window.devToolsExtension() : f => f
)(createStore)
const reducer = combineReducers({
reducer: Reducer,
routing: routerReducer
})
const store = finalCreateStore(reducer)
const history = syncHistoryWithStore(hashHistory, store)
const routes = Routes(store)
injectTapEventPlugin()
// ROUTES
ReactDOM.render(
<Provider store={store}>
<div>
<Router history={history}>
{routes}
</Router>
</div>
</Provider>,
document.getElementById('mount')
) |
app/containers/App.js | ycai2/visual-git-stats | // @flow
import React, { Component } from 'react';
import type { Children } from 'react';
export default class App extends Component {
props: {
children: Children
};
render () {
return (
<div>
{this.props.children}
</div>
);
}
}
|
imports/ui/components/familyInfo/components/ParentOccupation.js | AdmitHub/ScholarFisher | import React, { Component } from 'react';
import Collapse from 'react-collapse';
export default class ParentOccupation extends Component {
constructor(props) {
super(props);
this.state = { parentOccupationOpened: false };
this.handleParentOccupationOpened = this.handleParentOccupationOpened.bind(this);
this.drawCircle = this.drawCircle.bind(this);
}
handleParentOccupationOpened() {
this.setState({ parentOccupationOpened: !this.state.parentOccupationOpened });
}
renderParentOccupation(options, selectedParentOccupation, dispatchParentOccupationArray) {
return options.map((currentEl, index) => (
<div
className={'pill ' + (selectedParentOccupation.indexOf(currentEl.type) >- 1 ? 'selected' : '')}
onClick={() => dispatchParentOccupationArray(currentEl.type)}
key={index}
>
{currentEl.type}
</div>
));
}
drawCircle() {
const { options, selectedParentOccupation, dispatchParentOccupationArray } = this.props;
if (selectedParentOccupation.length > 0) {
return (
<span className="flex pull-right">
<i className="fa fa-check-circle fa-lg"></i>
</span>
)
} else {
return (
<span className="flex pull-right">
<i className="fa fa-circle-o fa-lg"></i>
</span>
)
}
}
render() {
const { options, selectedParentOccupation, dispatchParentOccupationArray } = this.props;
return (
<div>
<div className="row">
<div className="col-xs-12">
<div className="flexbox">
<h4
onClick={this.handleParentOccupationOpened}
>
PARENT(S) OCCUPATION(S)
{this.drawCircle()}
</h4>
<Collapse isOpened={this.state.parentOccupationOpened}>
<p className="caption">
<span className="caption-paragraph">
Some scholarships are available for applicants with a parent(s) in the following professions. Select one appropriate to you, if applicable.
</span>
</p>
</Collapse>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-12 flex-wrapper">
{this.renderParentOccupation(options, selectedParentOccupation, dispatchParentOccupationArray)}
</div>
</div>
</div>
);
}
}
|
src/components/Group.js | dialob/dialob-fill-ui | /**
* Copyright 2016 ReSys OÜ
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import classnames from 'classnames';
import ReactMarkdown from 'react-markdown';
import PropTypes from 'prop-types';
export default class Group extends React.Component {
static get propTypes() {
return {
group: PropTypes.array.isRequired
};
}
static get contextTypes() {
return {
componentCreator: PropTypes.func.isRequired
};
}
renderDescription() {
if (this.props.group[1].get('description')) {
return (
<div className='dialob-description'>
<ReactMarkdown source={this.props.group[1].get('description')} escapeHtml={true} />
</div>
)
} else {
return null;
}
}
render() {
let group = this.props.group && this.props.group[1];
if (!group) {
return null;
}
let className = group.get('className');
let customStyles = [];
if (className) {
customStyles = className.toJS();
}
let title = group.get('label');
let questions = group.get('items').toJS()
.map(this.context.componentCreator)
.filter(question => question);
return (
<div className={classnames('dialob-group', customStyles)}>
<span className='dialob-group-title'>{title}</span>
{ this.renderDescription() }
{questions}
</div>
);
}
}
|
src/parser/monk/brewmaster/modules/core/MasteryValue.js | FaideWW/WoWAnalyzer | import React from 'react';
import { Line as LineChart } from 'react-chartjs-2';
import SPELLS from 'common/SPELLS';
import HIT_TYPES from 'game/HIT_TYPES';
import Analyzer from 'parser/core/Analyzer';
import StatTracker from 'parser/shared/modules/StatTracker';
import LazyLoadStatisticBox from 'interface/others/LazyLoadStatisticBox';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import DamageTaken from './DamageTaken';
// coefficients to calculate dodge chance from agility
const MONK_DODGE_COEFFS = {
base_dodge: 3,
base_agi: 1468,
// names of individual coefficients are taken from ancient lore, err,
// formulae
P: 452.27,
D: 80,
v: 0.01,
h: 1.06382978723,
};
function _clampProb(prob) {
if (prob > 1.0) {
return 1.0;
} else if (prob < 0.0) {
return 0.0;
} else {
return prob;
}
}
/**
* This class represents the Markov Chain with which the Mastery stacks
* are modeled. The transition probabilities are defined by two
* potential operations:
*
* 1. Guaranteed Addition: from using an ability that generates a stack
* 100% of the time (e.g. BoS, BoF). The probability of having i stacks
* afterward is equal to the probability of having i-1 stacks before
* (the probability of having 0 stacks afterward is 0).
*
* 2. Attack: The probability of having i > 0 stacks afterward is equal to
* the probability of being hit with i - 1 stacks. The probability of
* having 0 stacks afterward is the sum of the probabilities of dodging
* with each number of stacks. Note that there is a natural cap on the
* number of stacks you can reach, since after that point every hit will
* be a dodge.
*
* The expected number of stacks you have is just the sum of the indices
* weighted by the values.
*/
class StackMarkovChain {
_stackProbs = [1.0];
_assertSum() {
const sum = this._stackProbs.reduce((sum, p) => p + sum, 0);
if (Math.abs(sum - 1.0) > 1e-6) {
const err = new Error('probabilities do not sum to 1 in StackMarkovChain');
err.data = {
sum: sum,
probs: this._stackProbs,
};
console.log(err.data);
throw err;
}
}
// add a stack with guaranteed probability
guaranteeStack() {
this._stackProbs.unshift(0.0);
this._assertSum();
}
processAttack(dodgeProb, masteryValue) {
this._stackProbs.push(0);
const n = this._stackProbs.length - 1;
// probability of ending at 0 stacks. initial
let zeroProb = 0;
// didn't dodge, gain a stack
for (let stacks = n - 1; stacks >= 0; stacks--) {
const prob = _clampProb(dodgeProb + masteryValue * stacks);
zeroProb += prob * this._stackProbs[stacks]; // dodge -> go to 0
const hitProb = 1 - prob;
this._stackProbs[stacks + 1] = hitProb * this._stackProbs[stacks]; // hit -> go to stacks + 1
}
// did dodge, reset stacks
this._stackProbs[0] = zeroProb;
this._assertSum();
}
get expected() {
return this._stackProbs.reduce((sum, prob, index) => sum + prob * index, 0);
}
}
export function baseDodge(agility, dodge_rating = 0) {
const base = MONK_DODGE_COEFFS.base_dodge + MONK_DODGE_COEFFS.base_agi / MONK_DODGE_COEFFS.P;
const chance = (agility - MONK_DODGE_COEFFS.base_agi) / MONK_DODGE_COEFFS.P + dodge_rating / MONK_DODGE_COEFFS.D;
// the x / (x + k) formula is commonly used by the wow team to
// implement diminishing returns
return (base + chance / (chance * MONK_DODGE_COEFFS.v + MONK_DODGE_COEFFS.h)) / 100;
}
/**
* Estimate the expected value of mastery on this fight. The *actual*
* estimated value is subject to greater variance.
* On the other hand, the expected value averages over all
* possible outcomes and gives a better sense of how valuable mastery is
* if you were to do this fight again. This values more stable over
* repeated attempts or kills and reflects the value of mastery (and the
* execution of the rotation) more closely than how well-favored you
* were on this particular attempt.
*
* We calculate the expected value by applying the Markov Chain above to
* the timeline to calculate the expected number of stacks at each
* dodgeable event. This is then combined with information about the
* expected damage of each dodged hit (dodge events have amount: 0,
* absorbed: 0, etc.) to provide a best-guess estimate of the damage
* you'll mitigate on average. The actual estimate (shown in the
* tooltip) may be over or under this, but is unlikely to be far from
* it.
*
* This madness was authored by emallson. If you need further explanation of
* the theory behind it, find me on discord.
*/
class MasteryValue extends Analyzer {
static dependencies = {
dmg: DamageTaken,
stats: StatTracker,
};
_loaded = false;
_dodgeableSpells = {};
_timeline = [];
_hitCounts = {};
_dodgeCounts = {};
dodgePenalty(_source) {
return 0.045; // 1.5% per level, bosses are three levels over players. not sure how to get trash levels yet -- may not matter
}
// returns the current chance to dodge a damage event assuming the
// event is dodgeable
dodgeChance(masteryStacks, masteryRating, agility, sourceID, timestamp = null) {
const masteryPercentage = this.stats.masteryPercentage(masteryRating, true);
return _clampProb(masteryPercentage * masteryStacks + baseDodge(agility) - this.dodgePenalty(sourceID));
}
on_byPlayer_cast(event) {
if (this._stacksApplied(event) > 0) {
this._timeline.push(event);
}
}
on_toPlayer_damage(event) {
event._masteryRating = this.stats.currentMasteryRating;
event._agility = this.stats.currentAgilityRating;
if (event.hitType === HIT_TYPES.DODGE) {
this._addDodge(event);
} else {
this._addHit(event);
}
}
_addDodge(event) {
const spellId = event.ability.guid;
this._dodgeableSpells[spellId] = true;
if (this._dodgeCounts[spellId] === undefined) {
this._dodgeCounts[spellId] = 0;
}
this._dodgeCounts[spellId] += 1;
this._timeline.push(event);
}
_addHit(event) {
const spellId = event.ability.guid;
if (this._hitCounts[spellId] === undefined) {
this._hitCounts[spellId] = 0;
}
this._hitCounts[spellId] += 1;
this._timeline.push(event);
}
// returns true of the event represents a cast that applies a stack of
// mastery
_stacksApplied(event) {
if(event.ability.guid !== SPELLS.BLACKOUT_STRIKE.id) {
return 0;
}
let stacks = 1;
// account for elusive footwork
if(this.selectedCombatant.hasTrait(SPELLS.ELUSIVE_FOOTWORK.id) && event.hitType === HIT_TYPES.CRIT) {
stacks += 1;
}
return stacks;
}
meanHitByAbility(spellId) {
if (this._hitCounts[spellId] !== undefined) {
return (this.dmg.byAbility(spellId).effective + this.dmg.staggeredByAbility(spellId)) / this._hitCounts[spellId];
}
return 0;
}
// events that either (a) add a stack or (b) can be dodged according
// to the data we have
get relevantTimeline() {
return this._timeline.filter(event => event.type === 'cast' || this._dodgeableSpells[event.ability.guid]);
}
_expectedValues = {
expectedDamageMitigated: 0,
estimatedDamageMitigated: 0,
meanExpectedDodge: 0,
noMasteryExpectedDamageMitigated: 0,
noMasteryMeanExpectedDodge: 0,
};
_calculateExpectedValues() {
// expected damage mitigated according to the markov chain
let expectedDamageMitigated = 0;
let noMasteryExpectedDamageMitigated = 0;
// estimate of the damage that was actually dodged in this log
let estimatedDamageMitigated = 0;
// average dodge % across each event that could be dodged
let meanExpectedDodge = 0;
let noMasteryMeanExpectedDodge = 0;
let dodgeableEvents = 0;
const stacks = new StackMarkovChain(); // mutating a const object irks me to no end
const noMasteryStacks = new StackMarkovChain();
// timeline replay is expensive, compute several things here and
// provide individual getters for each of the values
this.relevantTimeline.forEach(event => {
if (event.type === 'cast') {
const eventStacks = this._stacksApplied(event);
for(let i = 0; i < eventStacks; i++) {
stacks.guaranteeStack();
noMasteryStacks.guaranteeStack();
}
} else if (event.type === 'damage') {
const noMasteryDodgeChance = this.dodgeChance(noMasteryStacks.expected, 0, event._agility, event.sourceID, event.timestamp);
const expectedDodgeChance = this.dodgeChance(stacks.expected, event._masteryRating, event._agility, event.sourceID, event.timestamp);
const baseDodgeChance = this.dodgeChance(0, 0, event._agility, event.sourceID, event.timestamp);
const damage = (event.amount + event.absorbed) || this.meanHitByAbility(event.ability.guid);
expectedDamageMitigated += expectedDodgeChance * damage;
noMasteryExpectedDamageMitigated += noMasteryDodgeChance * damage;
estimatedDamageMitigated += (event.hitType === HIT_TYPES.DODGE) * damage;
meanExpectedDodge += expectedDodgeChance;
noMasteryMeanExpectedDodge += noMasteryDodgeChance;
dodgeableEvents += 1;
stacks.processAttack(baseDodgeChance, this.stats.masteryPercentage(event._masteryRating, true));
noMasteryStacks.processAttack(baseDodgeChance, this.stats.masteryPercentage(0, true));
}
});
meanExpectedDodge /= dodgeableEvents;
noMasteryMeanExpectedDodge /= dodgeableEvents;
return {
expectedDamageMitigated,
estimatedDamageMitigated,
meanExpectedDodge,
noMasteryExpectedDamageMitigated,
noMasteryMeanExpectedDodge,
};
}
get expectedMitigation() {
return this._expectedValues.expectedDamageMitigated;
}
get expectedMeanDodge() {
return this._expectedValues.meanExpectedDodge;
}
get noMasteryExpectedMeanDodge() {
return this._expectedValues.noMasteryMeanExpectedDodge;
}
get totalDodges() {
return Object.keys(this._dodgeableSpells).reduce((sum, spellId) => sum + this._dodgeCounts[spellId], 0);
}
get totalDodgeableHits() {
return Object.keys(this._dodgeableSpells).reduce((sum, spellId) => sum + (this._hitCounts[spellId] || 0), 0)
+ this.totalDodges;
}
get actualDodgeRate() {
return this.totalDodges / this.totalDodgeableHits;
}
get estimatedActualMitigation() {
return this._expectedValues.estimatedDamageMitigated;
}
get averageMasteryRating() {
return this.relevantTimeline.reduce((sum, event) => {
if (event.type === 'damage') {
return event._masteryRating + sum;
} else {
return sum;
}
}, 0) / this.relevantTimeline.filter(event => event.type === 'damage').length;
}
get noMasteryExpectedMitigation() {
return this._expectedValues.noMasteryExpectedDamageMitigated;
}
get expectedMitigationPerSecond() {
return this.expectedMitigation / this.owner.fightDuration * 1000;
}
get noMasteryExpectedMitigationPerSecond() {
return this.noMasteryExpectedMitigation / this.owner.fightDuration * 1000;
}
plot() {
// not the most efficient, but close enough and pretty safe
function binom(n, k) {
if(k > n) {
return null;
}
if(k === 0) {
return 1;
}
return n / k * binom(n-1, k-1);
}
// pmf of the binomial distribution with n = totalDodgeableHits and
// p = expectedMeanDodge
const dodge_prob = (i) => binom(this.totalDodgeableHits, i) * Math.pow(this.expectedMeanDodge, i) * Math.pow(1 - this.expectedMeanDodge, this.totalDodgeableHits - i);
// probability of having dodge exactly k of the n incoming hits
// assuming the expected mean dodge % is the true mean dodge %
const dodge_probs = Array.from({length: this.totalDodgeableHits}, (_x, i) => {
return { x: i, y: dodge_prob(i) };
});
return (
<LineChart
data={{
labels: Array.from({length: this.totalDodgeableHits}, (_x, i) => i),
datasets: [
{
label: 'Actual Dodge',
data: [{ x: this.totalDodges, y: dodge_prob(this.totalDodges) }],
backgroundColor: '#00ff96',
type: 'scatter',
},
{
label: 'Dodge',
data: dodge_probs,
backgroundColor: 'rgba(255, 139, 45, 0.2)',
borderColor: 'rgb(255, 139, 45)',
borderWidth: 2,
radius: 0,
},
],
}}
options={{
tooltips: {
callbacks: {
title: (tooltipItem, data) => data.datasets[tooltipItem[0].datasetIndex].label,
label: (tooltipItem, data) => `${formatPercentage(data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].x / this.totalDodgeableHits)}%`,
},
},
legend: {
display: false,
},
scales: {
xAxes: [{
stacked: true,
scaleLabel: {
display: true,
labelString: 'Dodge %',
lineHeight: 1,
padding: 0,
fontColor: '#ccc',
},
ticks: {
fontColor: '#ccc',
callback: (x) => `${formatPercentage(x / this.totalDodgeableHits, 0)}%`,
},
}],
yAxes: [{
stacked: true,
scaleLabel: {
display: true,
labelString: 'Likelihood',
fontColor: '#ccc',
},
ticks: {
fontColor: '#ccc',
callback: (y) => `${formatPercentage(y, 0)}%`,
},
}],
},
}}
/>
);
}
load() {
this._loaded = true;
this._expectedValues = this._calculateExpectedValues();
return Promise.resolve(this._expectedValues);
}
statistic() {
return (
<LazyLoadStatisticBox
loader={this.load.bind(this)}
icon={<SpellIcon id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} />}
value={`${formatNumber(this.expectedMitigationPerSecond - this.noMasteryExpectedMitigationPerSecond)} DTPS`}
label="Expected Mitigation by Mastery"
tooltip={this._loaded ? `On average, you would dodge about <b>${formatNumber(this.expectedMitigation)}</b> damage on this fight. This value was increased by about <b>${formatNumber(this.expectedMitigation - this.noMasteryExpectedMitigation)}</b> due to Mastery. You had an average expected dodge chance of <b>${formatPercentage(this.expectedMeanDodge)}%</b> and actually dodged about <b>${formatNumber(this.estimatedActualMitigation)}</b> damage with an overall rate of <b>${formatPercentage(this.actualDodgeRate)}%</b>. This amounts to an expected reduction of <b>${formatNumber((this.expectedMitigationPerSecond - this.noMasteryExpectedMitigationPerSecond) / this.averageMasteryRating)} DTPS per 1 Mastery</b> <em>on this fight</em>.<br/><br/>
<em>Technical Information:</em><br/>
<b>Estimated Actual Damage</b> is calculated by calculating the average damage per hit of an ability, then multiplying that by the number of times you dodged each ability.<br/>
<b>Expected</b> values are calculated by computing the expected number of mastery stacks each time you <em>could</em> dodge an ability.<br/>
An ability is considered <b>dodgeable</b> if you dodged it at least once.` : null}
>
<div style={{padding: '8px'}}>
{this._loaded ? this.plot() : null}
<p>Likelihood of dodging <em>exactly</em> as much as you did with your level of Mastery.</p>
</div>
</LazyLoadStatisticBox>
);
}
}
export default MasteryValue;
|
examples/js/shopping-list/client/components/StaticImage.js | reimagined/resolve | import React from 'react'
import { Image } from 'react-bootstrap'
import { useStaticResolver } from '@resolve-js/react-hooks'
const StaticImage = ({ src, ...otherProps }) => {
const resolveStatic = useStaticResolver()
return <Image {...otherProps} src={resolveStatic(src)} />
}
export { StaticImage }
|
src/containers/TodoEditPage.js | kclowes/new-edit-blog-fe | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { isEmpty } from 'lodash';
import { getTodo, updateTodo } from '../store/todos/actions';
import TodoEditForm from '../components/TodoEditForm';
export class TodoEditPage extends Component {
constructor(props) {
super(props);
this.state = {
todo: props.todo,
};
}
componentDidMount() {
const { dispatch, match } = this.props;
dispatch(getTodo(match.params.id));
}
componentWillReceiveProps(nextProps) {
if (this.props.todo !== nextProps.todo) {
this.setState({
todo: nextProps.todo,
});
}
}
handleEditSubmit = todo => {
const { dispatch, history } = this.props;
dispatch(updateTodo(todo));
history.push('/');
};
render() {
const { todo } = this.state;
if (isEmpty(todo)) {
return null;
}
return (
<TodoEditForm
todo={todo}
handleEditSubmit={todo => this.handleEditSubmit(todo)}
handleChange={e => this.handleChange(e)}
/>
);
}
}
TodoEditPage.propTypes = {
todo: PropTypes.object,
};
function mapStateToProps(state) {
return {
todo: state.todos.todo,
};
}
export default connect(mapStateToProps)(TodoEditPage);
|
packages/material-ui-icons/src/Exposure.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M15 17v2h2v-2h2v-2h-2v-2h-2v2h-2v2h2zm5-15H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM5 5h6v2H5V5zm15 15H4L20 4v16z" /></g>
, 'Exposure');
|
react-dev/pages/post.js | DeryLiu/DeryLiu.github.io | import React, { Component } from 'react';
import Paper from 'material-ui/Paper';
import { blueGrey800, grey50, teal900, green900, green500, teal500, cyan500 } from 'material-ui/styles/colors';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
//it's safe to use dangerouslySetInnerHTML because all components under /pages
//are going to be statically generated and placed in a position for Jekyll to use
const muiTheme = getMuiTheme(darkBaseTheme, {
palette: {
primary1Color: blueGrey800,
primary2Color: green900,
primary3Color: teal900,
accent1Color: green500,
accent2Color: teal500,
accent3Color: cyan500,
textColor: grey50,
alternateTextColor: grey50, //color on header
//pickerHeaderColor: grey900
},
appBar: {
height: 100
},
});
class Post extends Component {
createMarkup(markup) {
return { __html: markup };
}
render() {
return (
<MuiThemeProvider muiTheme={muiTheme}>
<div className="single-post-content" id="single-post-content">
<Paper zDepth={4} className="paper-wrapper" id="post-static-content">
<article className="post" itemScope itemType="http://schema.org/BlogPosting">
<header className="post-header">
<h1 className="post-title" itemProp="name headline">{'{{ page.title }}'}</h1>
<p className="post-meta">
<time
dateTime="{`{{ page.date | date_to_xmlschema }}`}" itemProp="datePublished"
dangerouslySetInnerHTML={this.createMarkup("{{ page.date | date: '%b %-d, %Y'}}")}
/>
{'{% if page.author %}'} • <span itemProp="author" itemScope itemType="http://schema.org/Person"><span itemProp="name">{'{{ page.author }}'}</span></span>{'{% endif %}'}</p>
</header>
<div className="post-content" itemProp="articleBody">
{'{{ content }}'}
</div>
</article>
</Paper>
</div>
</MuiThemeProvider>
);
}
}
export default Post;
|
client/src/components/LoadingSpinner/LoadingSpinner.js | timorieber/wagtail | import React from 'react';
import { STRINGS } from '../../config/wagtailConfig';
import Icon from '../../components/Icon/Icon';
/**
* A loading indicator with a text label next to it.
*/
const LoadingSpinner = () => (
<span>
<Icon name="spinner" className="c-spinner" />{` ${STRINGS.LOADING}`}
</span>
);
export default LoadingSpinner;
|
src/components/header/normal/lang-switcher.js | datea/datea-webapp-react | import React from 'react';
import classnames from 'classnames';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import MenuList from '@material-ui/core/MenuList';
import Button from '@material-ui/core/Button';
import {observer, inject} from 'mobx-react';
import {translatable} from '../../../i18n';
@inject('store')
@translatable
@observer
export default class LangSwitcher extends React.Component {
locales = ['es', 'fr'];
constructor(props) {
super(props);
this.state = { open: false};
}
handleTouchTap = (event) => {
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
switchLang = (loc) => {
this.props.store.user.setLocale(loc);
this.setState({open: false});
}
render() {
const {user, ui} = this.props.store;
if (ui.isMobile) return <span></span>;
const btnStyle = {
//border: '1px solid black',
height: 40,
width: 40,
minWidth: 40,
padding: 0,
textAlign: 'center',
borderRadius: '50%'
}
/*const labelStyle = {
padding: 0
};*/
return (
<div className={classnames('lang-switcher', ui.isMobile && 'mobile')}>
<Button
onClick={this.handleTouchTap}
style={btnStyle}>
{user.locale}
</Button>
<Menu
open={this.state.open}
anchorEl={this.state.anchorEl}
onClose={this.handleRequestClose}
>
<MenuList>
{this.locales.filter(loc => loc != user.locale).map(loc =>
<MenuItem key={loc} onClick={() => this.switchLang(loc)}>{loc.toUpperCase()}</MenuItem>
)}
</MenuList>
</Menu>
</div>
);
}
}
|
ajax/libs/6to5/1.11.15/browser-polyfill.js | iamJoeTaylor/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){if(typeof Symbol==="undefined"){require("es6-symbol/implement")}require("es6-shim");require("regenerator-6to5/runtime")},{"es6-shim":3,"es6-symbol/implement":4,"regenerator-6to5/runtime":27}],2:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],3:[function(require,module,exports){(function(process){(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.returnExports=factory()}})(this,function(){"use strict";var isCallableWithoutNew=function(func){try{func()}catch(e){return false}return true};var supportsSubclassing=function(C,f){try{var Sub=function(){C.apply(this,arguments)};if(!Sub.__proto__){return false}Object.setPrototypeOf(Sub,C);Sub.prototype=Object.create(C.prototype,{constructor:{value:C}});return f(Sub)}catch(e){return false}};var arePropertyDescriptorsSupported=function(){try{Object.defineProperty({},"x",{});return true}catch(e){return false}};var startsWithRejectsRegex=function(){var rejectsRegex=false;if(String.prototype.startsWith){try{"/a/".startsWith(/a/)}catch(e){rejectsRegex=true}}return rejectsRegex};var getGlobal=new Function("return this;");var globals=getGlobal();var global_isFinite=globals.isFinite;var supportsDescriptors=!!Object.defineProperty&&arePropertyDescriptorsSupported();var startsWithIsCompliant=startsWithRejectsRegex();var _slice=Array.prototype.slice;var _indexOf=String.prototype.indexOf;var _toString=Object.prototype.toString;var _hasOwnProperty=Object.prototype.hasOwnProperty;var ArrayIterator;var defineProperty=function(object,name,value,force){if(!force&&name in object){return}if(supportsDescriptors){Object.defineProperty(object,name,{configurable:true,enumerable:false,writable:true,value:value})}else{object[name]=value}};var defineProperties=function(object,map){Object.keys(map).forEach(function(name){var method=map[name];defineProperty(object,name,method,false)})};var create=Object.create||function(prototype,properties){function Type(){}Type.prototype=prototype;var object=new Type;if(typeof properties!=="undefined"){defineProperties(object,properties)}return object};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(globals.Set&&typeof(new globals.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var addIterator=function(prototype,impl){if(!impl){impl=function iterator(){return this}}var o={};o[$iterator$]=impl;defineProperties(prototype,o);if(!prototype[$iterator$]&&typeof $iterator$==="symbol"){prototype[$iterator$]=impl}};var isArguments=function isArguments(value){var str=_toString.call(value);var result=str==="[object Arguments]";if(!result){result=str!=="[object Array]"&&value!==null&&typeof value==="object"&&typeof value.length==="number"&&value.length>=0&&_toString.call(value.callee)==="[object Function]"}return result};var emulateES6construct=function(o){if(!ES.TypeIsObject(o)){throw new TypeError("bad object")}if(!o._es6construct){if(o.constructor&&ES.IsCallable(o.constructor["@@create"])){o=o.constructor["@@create"](o)}defineProperties(o,{_es6construct:true})}return o};var ES={CheckObjectCoercible:function(x,optMessage){if(x==null){throw new TypeError(optMessage||"Cannot call method on "+x)}return x},TypeIsObject:function(x){return x!=null&&Object(x)===x},ToObject:function(o,optMessage){return Object(ES.CheckObjectCoercible(o,optMessage))},IsCallable:function(x){return typeof x==="function"&&_toString.call(x)==="[object Function]"},ToInt32:function(x){return x>>0},ToUint32:function(x){return x>>>0},ToInteger:function(value){var number=+value;if(Number.isNaN(number)){return 0}if(number===0||!Number.isFinite(number)){return number}return(number>0?1:-1)*Math.floor(Math.abs(number))},ToLength:function(value){var len=ES.ToInteger(value);if(len<=0){return 0}if(len>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return len},SameValue:function(a,b){if(a===b){if(a===0){return 1/a===1/b}return true}return Number.isNaN(a)&&Number.isNaN(b)},SameValueZero:function(a,b){return a===b||Number.isNaN(a)&&Number.isNaN(b)},IsIterable:function(o){return ES.TypeIsObject(o)&&(typeof o[$iterator$]!=="undefined"||isArguments(o))},GetIterator:function(o){if(isArguments(o)){return new ArrayIterator(o,"value")}var it=o[$iterator$]();if(!ES.TypeIsObject(it)){throw new TypeError("bad iterator")}return it},IteratorNext:function(it){var result=arguments.length>1?it.next(arguments[1]):it.next();if(!ES.TypeIsObject(result)){throw new TypeError("bad iterator")}return result},Construct:function(C,args){var obj;if(ES.IsCallable(C["@@create"])){obj=C["@@create"]()}else{obj=create(C.prototype||null)}defineProperties(obj,{_es6construct:true});var result=C.apply(obj,args);return ES.TypeIsObject(result)?result:obj}};var numberConversion=function(){function roundToEven(n){var w=Math.floor(n),f=n-w;if(f<.5){return w}if(f>.5){return w+1}return w%2?w+1:w}function packIEEE754(v,ebits,fbits){var bias=(1<<ebits-1)-1,s,e,f,ln,i,bits,str,bytes;if(v!==v){e=(1<<ebits)-1;f=Math.pow(2,fbits-1);s=0}else if(v===Infinity||v===-Infinity){e=(1<<ebits)-1;f=0;s=v<0?1:0}else if(v===0){e=0;f=0;s=1/v===-Infinity?1:0}else{s=v<0;v=Math.abs(v);if(v>=Math.pow(2,1-bias)){e=Math.min(Math.floor(Math.log(v)/Math.LN2),1023);f=roundToEven(v/Math.pow(2,e)*Math.pow(2,fbits));if(f/Math.pow(2,fbits)>=2){e=e+1;f=1}if(e>bias){e=(1<<ebits)-1;f=0}else{e=e+bias;f=f-Math.pow(2,fbits)}}else{e=0;f=roundToEven(v/Math.pow(2,1-bias-fbits))}}bits=[];for(i=fbits;i;i-=1){bits.push(f%2?1:0);f=Math.floor(f/2)}for(i=ebits;i;i-=1){bits.push(e%2?1:0);e=Math.floor(e/2)}bits.push(s?1:0);bits.reverse();str=bits.join("");bytes=[];while(str.length){bytes.push(parseInt(str.slice(0,8),2));str=str.slice(8)}return bytes}function unpackIEEE754(bytes,ebits,fbits){var bits=[],i,j,b,str,bias,s,e,f;for(i=bytes.length;i;i-=1){b=bytes[i-1];for(j=8;j;j-=1){bits.push(b%2?1:0);b=b>>1}}bits.reverse();str=bits.join("");bias=(1<<ebits-1)-1;s=parseInt(str.slice(0,1),2)?-1:1;e=parseInt(str.slice(1,1+ebits),2);f=parseInt(str.slice(1+ebits),2);if(e===(1<<ebits)-1){return f!==0?NaN:s*Infinity}else if(e>0){return s*Math.pow(2,e-bias)*(1+f/Math.pow(2,fbits))}else if(f!==0){return s*Math.pow(2,-(bias-1))*(f/Math.pow(2,fbits))}else{return s<0?-0:0}}function unpackFloat64(b){return unpackIEEE754(b,11,52)}function packFloat64(v){return packIEEE754(v,11,52)}function unpackFloat32(b){return unpackIEEE754(b,8,23)}function packFloat32(v){return packIEEE754(v,8,23)}var conversions={toFloat32:function(num){return unpackFloat32(packFloat32(num))}};if(typeof Float32Array!=="undefined"){var float32array=new Float32Array(1);conversions.toFloat32=function(num){float32array[0]=num;return float32array[0]}}return conversions}();defineProperties(String,{fromCodePoint:function(_){var points=_slice.call(arguments,0,arguments.length);var result=[];var next;for(var i=0,length=points.length;i<length;i++){next=Number(points[i]);if(!ES.SameValue(next,ES.ToInteger(next))||next<0||next>1114111){throw new RangeError("Invalid code point "+next)}if(next<65536){result.push(String.fromCharCode(next))}else{next-=65536;result.push(String.fromCharCode((next>>10)+55296));result.push(String.fromCharCode(next%1024+56320))}}return result.join("")},raw:function(callSite){var substitutions=_slice.call(arguments,1,arguments.length);var cooked=ES.ToObject(callSite,"bad callSite");var rawValue=cooked.raw;var raw=ES.ToObject(rawValue,"bad raw value");var len=Object.keys(raw).length;var literalsegments=ES.ToLength(len);if(literalsegments===0){return""}var stringElements=[];var nextIndex=0;var nextKey,next,nextSeg,nextSub;while(nextIndex<literalsegments){nextKey=String(nextIndex);next=raw[nextKey];nextSeg=String(next);stringElements.push(nextSeg);if(nextIndex+1>=literalsegments){break}next=substitutions[nextKey];if(typeof next==="undefined"){break}nextSub=String(next);stringElements.push(nextSub);nextIndex++}return stringElements.join("")}});if(String.fromCodePoint.length!==1){var originalFromCodePoint=String.fromCodePoint;defineProperty(String,"fromCodePoint",function(_){return originalFromCodePoint.apply(this,arguments)},true)}var StringShims={repeat:function(){var repeat=function(s,times){if(times<1){return""}if(times%2){return repeat(s,times-1)+s}var half=repeat(s,times/2);return half+half};return function(times){var thisStr=String(ES.CheckObjectCoercible(this));times=ES.ToInteger(times);if(times<0||times===Infinity){throw new RangeError("Invalid String#repeat value")}return repeat(thisStr,times)}}(),startsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "startsWith" with a regex')}searchStr=String(searchStr);var startArg=arguments.length>1?arguments[1]:void 0;var start=Math.max(ES.ToInteger(startArg),0);return thisStr.slice(start,start+searchStr.length)===searchStr},endsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "endsWith" with a regex')}searchStr=String(searchStr);var thisLen=thisStr.length;var posArg=arguments.length>1?arguments[1]:void 0;var pos=typeof posArg==="undefined"?thisLen:ES.ToInteger(posArg);var end=Math.min(Math.max(pos,0),thisLen);return thisStr.slice(end-searchStr.length,end)===searchStr},contains:function(searchString){var position=arguments.length>1?arguments[1]:void 0;return _indexOf.call(this,searchString,position)!==-1},codePointAt:function(pos){var thisStr=String(ES.CheckObjectCoercible(this));var position=ES.ToInteger(pos);var length=thisStr.length;if(position<0||position>=length){return}var first=thisStr.charCodeAt(position);var isEnd=position+1===length;if(first<55296||first>56319||isEnd){return first}var second=thisStr.charCodeAt(position+1);if(second<56320||second>57343){return first}return(first-55296)*1024+(second-56320)+65536}};defineProperties(String.prototype,StringShims);var hasStringTrimBug="
".trim().length!==1;if(hasStringTrimBug){var originalStringTrim=String.prototype.trim;delete String.prototype.trim;var ws=[" \n\f\r "," \u2028","\u2029"].join("");var trimRegexp=new RegExp("(^["+ws+"]+)|(["+ws+"]+$)","g");defineProperties(String.prototype,{trim:function(){if(typeof this==="undefined"||this===null){throw new TypeError("can't convert "+this+" to object")}return String(this).replace(trimRegexp,"")}})}var StringIterator=function(s){this._s=String(ES.CheckObjectCoercible(s));this._i=0};StringIterator.prototype.next=function(){var s=this._s,i=this._i;if(typeof s==="undefined"||i>=s.length){this._s=void 0;return{value:void 0,done:true}}var first=s.charCodeAt(i),second,len;if(first<55296||first>56319||i+1==s.length){len=1}else{second=s.charCodeAt(i+1);len=second<56320||second>57343?1:2}this._i=i+len;return{value:s.substr(i,len),done:false}};addIterator(StringIterator.prototype);addIterator(String.prototype,function(){return new StringIterator(this)});if(!startsWithIsCompliant){String.prototype.startsWith=StringShims.startsWith;String.prototype.endsWith=StringShims.endsWith}var ArrayShims={from:function(iterable){var mapFn=arguments.length>1?arguments[1]:void 0;var list=ES.ToObject(iterable,"bad iterable");if(typeof mapFn!=="undefined"&&!ES.IsCallable(mapFn)){throw new TypeError("Array.from: when provided, the second argument must be a function")}var hasThisArg=arguments.length>2;var thisArg=hasThisArg?arguments[2]:void 0;var usingIterator=ES.IsIterable(list);var length;var result,i,value;if(usingIterator){i=0;result=ES.IsCallable(this)?Object(new this):[];var it=usingIterator?ES.GetIterator(list):null;var iterationValue;do{iterationValue=ES.IteratorNext(it);if(!iterationValue.done){value=iterationValue.value;if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}i+=1}}while(!iterationValue.done);length=i}else{length=ES.ToLength(list.length);result=ES.IsCallable(this)?Object(new this(length)):new Array(length);for(i=0;i<length;++i){value=list[i];if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}}}result.length=length;return result},of:function(){return Array.from(arguments)}};defineProperties(Array,ArrayShims);var arrayFromSwallowsNegativeLengths=function(){try{return Array.from({length:-1}).length===0}catch(e){return false}};if(!arrayFromSwallowsNegativeLengths()){defineProperty(Array,"from",ArrayShims.from,true)}ArrayIterator=function(array,kind){this.i=0;this.array=array;this.kind=kind};defineProperties(ArrayIterator.prototype,{next:function(){var i=this.i,array=this.array;if(!(this instanceof ArrayIterator)){throw new TypeError("Not an ArrayIterator")}if(typeof array!=="undefined"){var len=ES.ToLength(array.length);for(;i<len;i++){var kind=this.kind;var retval;if(kind==="key"){retval=i}else if(kind==="value"){retval=array[i]}else if(kind==="entry"){retval=[i,array[i]]}this.i=i+1;return{value:retval,done:false}}}this.array=void 0;return{value:void 0,done:true}}});addIterator(ArrayIterator.prototype);var ArrayPrototypeShims={copyWithin:function(target,start){var end=arguments[2];var o=ES.ToObject(this);var len=ES.ToLength(o.length);target=ES.ToInteger(target);start=ES.ToInteger(start);var to=target<0?Math.max(len+target,0):Math.min(target,len);var from=start<0?Math.max(len+start,0):Math.min(start,len);end=typeof end==="undefined"?len:ES.ToInteger(end);var fin=end<0?Math.max(len+end,0):Math.min(end,len);var count=Math.min(fin-from,len-to);var direction=1;if(from<to&&to<from+count){direction=-1;from+=count-1;to+=count-1}while(count>0){if(_hasOwnProperty.call(o,from)){o[to]=o[from]}else{delete o[from]}from+=direction;to+=direction;count-=1}return o},fill:function(value){var start=arguments.length>1?arguments[1]:void 0;var end=arguments.length>2?arguments[2]:void 0;var O=ES.ToObject(this);var len=ES.ToLength(O.length);start=ES.ToInteger(typeof start==="undefined"?0:start);end=ES.ToInteger(typeof end==="undefined"?len:end);var relativeStart=start<0?Math.max(len+start,0):Math.min(start,len);var relativeEnd=end<0?len+end:end;for(var i=relativeStart;i<len&&i<relativeEnd;++i){O[i]=value}return O},find:function find(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#find: predicate must be a function")}var thisArg=arguments[1];for(var i=0,value;i<length;i++){value=list[i];if(predicate.call(thisArg,value,i,list)){return value}}return},findIndex:function findIndex(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#findIndex: predicate must be a function")}var thisArg=arguments[1];for(var i=0;i<length;i++){if(predicate.call(thisArg,list[i],i,list)){return i}}return-1},keys:function(){return new ArrayIterator(this,"key")},values:function(){return new ArrayIterator(this,"value")},entries:function(){return new ArrayIterator(this,"entry")}};if(Array.prototype.keys&&!ES.IsCallable([1].keys().next)){delete Array.prototype.keys}if(Array.prototype.entries&&!ES.IsCallable([1].entries().next)){delete Array.prototype.entries}defineProperties(Array.prototype,ArrayPrototypeShims);addIterator(Array.prototype,function(){return this.values()});if(Object.getPrototypeOf){addIterator(Object.getPrototypeOf([].values()))}var maxSafeInteger=Math.pow(2,53)-1;defineProperties(Number,{MAX_SAFE_INTEGER:maxSafeInteger,MIN_SAFE_INTEGER:-maxSafeInteger,EPSILON:2.220446049250313e-16,parseInt:globals.parseInt,parseFloat:globals.parseFloat,isFinite:function(value){return typeof value==="number"&&global_isFinite(value)},isInteger:function(value){return Number.isFinite(value)&&ES.ToInteger(value)===value},isSafeInteger:function(value){return Number.isInteger(value)&&Math.abs(value)<=Number.MAX_SAFE_INTEGER},isNaN:function(value){return value!==value}});if(![,1].find(function(item,idx){return idx===0})){defineProperty(Array.prototype,"find",ArrayPrototypeShims.find,true)}if([,1].findIndex(function(item,idx){return idx===0})!==0){defineProperty(Array.prototype,"findIndex",ArrayPrototypeShims.findIndex,true)}if(supportsDescriptors){defineProperties(Object,{getPropertyDescriptor:function(subject,name){var pd=Object.getOwnPropertyDescriptor(subject,name);var proto=Object.getPrototypeOf(subject);while(typeof pd==="undefined"&&proto!==null){pd=Object.getOwnPropertyDescriptor(proto,name);proto=Object.getPrototypeOf(proto)}return pd},getPropertyNames:function(subject){var result=Object.getOwnPropertyNames(subject);var proto=Object.getPrototypeOf(subject);var addProperty=function(property){if(result.indexOf(property)===-1){result.push(property)}};while(proto!==null){Object.getOwnPropertyNames(proto).forEach(addProperty);proto=Object.getPrototypeOf(proto)}return result}});defineProperties(Object,{assign:function(target,source){if(!ES.TypeIsObject(target)){throw new TypeError("target must be an object")}return Array.prototype.reduce.call(arguments,function(target,source){return Object.keys(Object(source)).reduce(function(target,key){target[key]=source[key];return target},target)})},is:function(a,b){return ES.SameValue(a,b)},setPrototypeOf:function(Object,magic){var set;var checkArgs=function(O,proto){if(!ES.TypeIsObject(O)){throw new TypeError("cannot set prototype on a non-object")}if(!(proto===null||ES.TypeIsObject(proto))){throw new TypeError("can only set prototype to an object or null"+proto)}};var setPrototypeOf=function(O,proto){checkArgs(O,proto);set.call(O,proto);return O};try{set=Object.getOwnPropertyDescriptor(Object.prototype,magic).set;set.call({},null)}catch(e){if(Object.prototype!=={}[magic]){return}set=function(proto){this[magic]=proto};setPrototypeOf.polyfill=setPrototypeOf(setPrototypeOf({},null),Object.prototype)instanceof Object}return setPrototypeOf}(Object,"__proto__")})}if(Object.setPrototypeOf&&Object.getPrototypeOf&&Object.getPrototypeOf(Object.setPrototypeOf({},null))!==null&&Object.getPrototypeOf(Object.create(null))===null){(function(){var FAKENULL=Object.create(null);var gpo=Object.getPrototypeOf,spo=Object.setPrototypeOf;Object.getPrototypeOf=function(o){var result=gpo(o);return result===FAKENULL?null:result};Object.setPrototypeOf=function(o,p){if(p===null){p=FAKENULL}return spo(o,p)};Object.setPrototypeOf.polyfill=false})()}try{Object.keys("foo")}catch(e){var originalObjectKeys=Object.keys;Object.keys=function(obj){return originalObjectKeys(ES.ToObject(obj))}}var MathShims={acosh:function(value){value=Number(value);if(Number.isNaN(value)||value<1){return NaN}if(value===1){return 0}if(value===Infinity){return value}return Math.log(value+Math.sqrt(value*value-1))},asinh:function(value){value=Number(value);if(value===0||!global_isFinite(value)){return value}return value<0?-Math.asinh(-value):Math.log(value+Math.sqrt(value*value+1))},atanh:function(value){value=Number(value);if(Number.isNaN(value)||value<-1||value>1){return NaN}if(value===-1){return-Infinity}if(value===1){return Infinity}if(value===0){return value}return.5*Math.log((1+value)/(1-value))},cbrt:function(value){value=Number(value);if(value===0){return value}var negate=value<0,result;if(negate){value=-value}result=Math.pow(value,1/3);return negate?-result:result},clz32:function(value){value=Number(value);var number=ES.ToUint32(value);if(number===0){return 32}return 32-number.toString(2).length},cosh:function(value){value=Number(value);if(value===0){return 1}if(Number.isNaN(value)){return NaN}if(!global_isFinite(value)){return Infinity}if(value<0){value=-value}if(value>21){return Math.exp(value)/2}return(Math.exp(value)+Math.exp(-value))/2},expm1:function(value){value=Number(value);if(value===-Infinity){return-1}if(!global_isFinite(value)||value===0){return value}return Math.exp(value)-1},hypot:function(x,y){var anyNaN=false;var allZero=true;var anyInfinity=false;var numbers=[];Array.prototype.every.call(arguments,function(arg){var num=Number(arg);if(Number.isNaN(num)){anyNaN=true}else if(num===Infinity||num===-Infinity){anyInfinity=true}else if(num!==0){allZero=false}if(anyInfinity){return false}else if(!anyNaN){numbers.push(Math.abs(num))}return true});if(anyInfinity){return Infinity}if(anyNaN){return NaN}if(allZero){return 0}numbers.sort(function(a,b){return b-a});var largest=numbers[0];var divided=numbers.map(function(number){return number/largest});var sum=divided.reduce(function(sum,number){return sum+=number*number},0);return largest*Math.sqrt(sum)},log2:function(value){return Math.log(value)*Math.LOG2E},log10:function(value){return Math.log(value)*Math.LOG10E},log1p:function(value){value=Number(value);if(value<-1||Number.isNaN(value)){return NaN}if(value===0||value===Infinity){return value}if(value===-1){return-Infinity}var result=0;var n=50;if(value<0||value>1){return Math.log(1+value)}for(var i=1;i<n;i++){if(i%2===0){result-=Math.pow(value,i)/i}else{result+=Math.pow(value,i)/i}}return result},sign:function(value){var number=+value;if(number===0){return number}if(Number.isNaN(number)){return number}return number<0?-1:1},sinh:function(value){value=Number(value);if(!global_isFinite(value)||value===0){return value}return(Math.exp(value)-Math.exp(-value))/2},tanh:function(value){value=Number(value);if(Number.isNaN(value)||value===0){return value}if(value===Infinity){return 1}if(value===-Infinity){return-1}return(Math.exp(value)-Math.exp(-value))/(Math.exp(value)+Math.exp(-value))},trunc:function(value){var number=Number(value);return number<0?-Math.floor(-number):Math.floor(number)},imul:function(x,y){x=ES.ToUint32(x);y=ES.ToUint32(y);var ah=x>>>16&65535;var al=x&65535;var bh=y>>>16&65535;var bl=y&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0},fround:function(x){if(x===0||x===Infinity||x===-Infinity||Number.isNaN(x)){return x}var num=Number(x);return numberConversion.toFloat32(num)}};defineProperties(Math,MathShims);if(Math.imul(4294967295,5)!==-5){Math.imul=MathShims.imul}var PromiseShim=function(){var Promise,Promise$prototype;ES.IsPromise=function(promise){if(!ES.TypeIsObject(promise)){return false}if(!promise._promiseConstructor){return false}if(typeof promise._status==="undefined"){return false}return true};var PromiseCapability=function(C){if(!ES.IsCallable(C)){throw new TypeError("bad promise constructor")}var capability=this;var resolver=function(resolve,reject){capability.resolve=resolve;capability.reject=reject};capability.promise=ES.Construct(C,[resolver]);if(!capability.promise._es6construct){throw new TypeError("bad promise constructor")}if(!(ES.IsCallable(capability.resolve)&&ES.IsCallable(capability.reject))){throw new TypeError("bad promise constructor")}};var setTimeout=globals.setTimeout;var makeZeroTimeout;if(typeof window!=="undefined"&&ES.IsCallable(window.postMessage)){makeZeroTimeout=function(){var timeouts=[];var messageName="zero-timeout-message";var setZeroTimeout=function(fn){timeouts.push(fn);window.postMessage(messageName,"*")};var handleMessage=function(event){if(event.source==window&&event.data==messageName){event.stopPropagation();if(timeouts.length===0){return}var fn=timeouts.shift();fn()}};window.addEventListener("message",handleMessage,true);return setZeroTimeout}}var makePromiseAsap=function(){var P=globals.Promise;return P&&P.resolve&&function(task){return P.resolve().then(task)}};var enqueue=ES.IsCallable(globals.setImmediate)?globals.setImmediate.bind(globals):typeof process==="object"&&process.nextTick?process.nextTick:makePromiseAsap()||(ES.IsCallable(makeZeroTimeout)?makeZeroTimeout():function(task){setTimeout(task,0)});var triggerPromiseReactions=function(reactions,x){reactions.forEach(function(reaction){enqueue(function(){var handler=reaction.handler;var capability=reaction.capability;var resolve=capability.resolve;var reject=capability.reject;try{var result=handler(x);if(result===capability.promise){throw new TypeError("self resolution")}var updateResult=updatePromiseFromPotentialThenable(result,capability);if(!updateResult){resolve(result)}}catch(e){reject(e)}})})};var updatePromiseFromPotentialThenable=function(x,capability){if(!ES.TypeIsObject(x)){return false}var resolve=capability.resolve;var reject=capability.reject;try{var then=x.then;if(!ES.IsCallable(then)){return false}then.call(x,resolve,reject)}catch(e){reject(e)}return true};var promiseResolutionHandler=function(promise,onFulfilled,onRejected){return function(x){if(x===promise){return onRejected(new TypeError("self resolution"))}var C=promise._promiseConstructor;var capability=new PromiseCapability(C);var updateResult=updatePromiseFromPotentialThenable(x,capability);if(updateResult){return capability.promise.then(onFulfilled,onRejected)}else{return onFulfilled(x)}}};Promise=function(resolver){var promise=this;promise=emulateES6construct(promise);if(!promise._promiseConstructor){throw new TypeError("bad promise")}if(typeof promise._status!=="undefined"){throw new TypeError("promise already initialized")}if(!ES.IsCallable(resolver)){throw new TypeError("not a valid resolver")}promise._status="unresolved";promise._resolveReactions=[];promise._rejectReactions=[];var resolve=function(resolution){if(promise._status!=="unresolved"){return}var reactions=promise._resolveReactions;promise._result=resolution;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-resolution";triggerPromiseReactions(reactions,resolution)};var reject=function(reason){if(promise._status!=="unresolved"){return}var reactions=promise._rejectReactions;promise._result=reason;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-rejection";triggerPromiseReactions(reactions,reason)};try{resolver(resolve,reject)}catch(e){reject(e)}return promise};Promise$prototype=Promise.prototype;defineProperties(Promise,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Promise$prototype;obj=obj||create(prototype);defineProperties(obj,{_status:void 0,_result:void 0,_resolveReactions:void 0,_rejectReactions:void 0,_promiseConstructor:void 0});obj._promiseConstructor=constructor;return obj}});var _promiseAllResolver=function(index,values,capability,remaining){var done=false;return function(x){if(done){return}done=true;values[index]=x;if(--remaining.count===0){var resolve=capability.resolve;resolve(values)}}};Promise.all=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);var values=[],remaining={count:1};for(var index=0;;index++){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);var resolveElement=_promiseAllResolver(index,values,capability,remaining);remaining.count++;nextPromise.then(resolveElement,capability.reject)}if(--remaining.count===0){resolve(values)}}catch(e){reject(e)}return capability.promise};Promise.race=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);nextPromise.then(resolve,reject)}}catch(e){reject(e)}return capability.promise};Promise.reject=function(reason){var C=this;var capability=new PromiseCapability(C);var reject=capability.reject;reject(reason);return capability.promise};Promise.resolve=function(v){var C=this;if(ES.IsPromise(v)){var constructor=v._promiseConstructor;if(constructor===C){return v}}var capability=new PromiseCapability(C);var resolve=capability.resolve;resolve(v);return capability.promise};Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){var promise=this;if(!ES.IsPromise(promise)){throw new TypeError("not a promise")}var C=this.constructor;var capability=new PromiseCapability(C);if(!ES.IsCallable(onRejected)){onRejected=function(e){throw e}}if(!ES.IsCallable(onFulfilled)){onFulfilled=function(x){return x}}var resolutionHandler=promiseResolutionHandler(promise,onFulfilled,onRejected);var resolveReaction={capability:capability,handler:resolutionHandler};var rejectReaction={capability:capability,handler:onRejected};switch(promise._status){case"unresolved":promise._resolveReactions.push(resolveReaction);promise._rejectReactions.push(rejectReaction);break;case"has-resolution":triggerPromiseReactions([resolveReaction],promise._result);break;case"has-rejection":triggerPromiseReactions([rejectReaction],promise._result);break;default:throw new TypeError("unexpected")}return capability.promise};return Promise}();defineProperties(globals,{Promise:PromiseShim});var promiseSupportsSubclassing=supportsSubclassing(globals.Promise,function(S){return S.resolve(42)instanceof S});var promiseIgnoresNonFunctionThenCallbacks=function(){try{globals.Promise.reject(42).then(null,5).then(null,function(){});return true}catch(ex){return false}}();var promiseRequiresObjectContext=function(){try{Promise.call(3,function(){})}catch(e){return true}return false}();if(!promiseSupportsSubclassing||!promiseIgnoresNonFunctionThenCallbacks||!promiseRequiresObjectContext){globals.Promise=PromiseShim}var testOrder=function(a){var b=Object.keys(a.reduce(function(o,k){o[k]=true;return o},{}));return a.join(":")===b.join(":")};var preservesInsertionOrder=testOrder(["z","a","bb"]);var preservesNumericInsertionOrder=testOrder(["z",1,"a","3",2]);if(supportsDescriptors){var fastkey=function fastkey(key){if(!preservesInsertionOrder){return null}var type=typeof key;if(type==="string"){return"$"+key}else if(type==="number"){if(!preservesNumericInsertionOrder){return"n"+key}return key}return null};var emptyObject=function emptyObject(){return Object.create?Object.create(null):{}};var collectionShims={Map:function(){var empty={};function MapEntry(key,value){this.key=key;this.value=value;this.next=null;this.prev=null}MapEntry.prototype.isRemoved=function(){return this.key===empty
};function MapIterator(map,kind){this.head=map._head;this.i=this.head;this.kind=kind}MapIterator.prototype={next:function(){var i=this.i,kind=this.kind,head=this.head,result;if(typeof this.i==="undefined"){return{value:void 0,done:true}}while(i.isRemoved()&&i!==head){i=i.prev}while(i.next!==head){i=i.next;if(!i.isRemoved()){if(kind==="key"){result=i.key}else if(kind==="value"){result=i.value}else{result=[i.key,i.value]}this.i=i;return{value:result,done:false}}}this.i=void 0;return{value:void 0,done:true}}};addIterator(MapIterator.prototype);function Map(iterable){var map=this;map=emulateES6construct(map);if(!map._es6map){throw new TypeError("bad map")}var head=new MapEntry(null,null);head.next=head.prev=head;defineProperties(map,{_head:head,_storage:emptyObject(),_size:0});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=map.set;if(!ES.IsCallable(adder)){throw new TypeError("bad map")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;if(!ES.TypeIsObject(nextItem)){throw new TypeError("expected iterable of pairs")}adder.call(map,nextItem[0],nextItem[1])}}return map}var Map$prototype=Map.prototype;defineProperties(Map,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Map$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6map:true});return obj}});Object.defineProperty(Map.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._size==="undefined"){throw new TypeError("size method called on incompatible Map")}return this._size}});defineProperties(Map.prototype,{get:function(key){var fkey=fastkey(key);if(fkey!==null){var entry=this._storage[fkey];if(entry){return entry.value}else{return}}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return i.value}}return},has:function(key){var fkey=fastkey(key);if(fkey!==null){return typeof this._storage[fkey]!=="undefined"}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return true}}return false},set:function(key,value){var head=this._head,i=head,entry;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]!=="undefined"){this._storage[fkey].value=value;return}else{entry=this._storage[fkey]=new MapEntry(key,value);i=head.prev}}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.value=value;return}}entry=entry||new MapEntry(key,value);if(ES.SameValue(-0,key)){entry.key=+0}entry.next=this._head;entry.prev=this._head.prev;entry.prev.next=entry;entry.next.prev=entry;this._size+=1;return this},"delete":function(key){var head=this._head,i=head;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]==="undefined"){return false}i=this._storage[fkey].prev;delete this._storage[fkey]}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.key=i.value=empty;i.prev.next=i.next;i.next.prev=i.prev;this._size-=1;return true}}return false},clear:function(){this._size=0;this._storage=emptyObject();var head=this._head,i=head,p=i.next;while((i=p)!==head){i.key=i.value=empty;p=i.next;i.next=i.prev=head}head.next=head.prev=head},keys:function(){return new MapIterator(this,"key")},values:function(){return new MapIterator(this,"value")},entries:function(){return new MapIterator(this,"key+value")},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var it=this.entries();for(var entry=it.next();!entry.done;entry=it.next()){callback.call(context,entry.value[1],entry.value[0],this)}}});addIterator(Map.prototype,function(){return this.entries()});return Map}(),Set:function(){var SetShim=function Set(iterable){var set=this;set=emulateES6construct(set);if(!set._es6set){throw new TypeError("bad set")}defineProperties(set,{"[[SetData]]":null,_storage:emptyObject()});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=set.add;if(!ES.IsCallable(adder)){throw new TypeError("bad set")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;adder.call(set,nextItem)}}return set};var Set$prototype=SetShim.prototype;defineProperties(SetShim,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Set$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6set:true});return obj}});var ensureMap=function ensureMap(set){if(!set["[[SetData]]"]){var m=set["[[SetData]]"]=new collectionShims.Map;Object.keys(set._storage).forEach(function(k){if(k.charCodeAt(0)===36){k=k.slice(1)}else if(k.charAt(0)==="n"){k=+k.slice(1)}else{k=+k}m.set(k,k)});set._storage=null}};Object.defineProperty(SetShim.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._storage==="undefined"){throw new TypeError("size method called on incompatible Set")}ensureMap(this);return this["[[SetData]]"].size}});defineProperties(SetShim.prototype,{has:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){return!!this._storage[fkey]}ensureMap(this);return this["[[SetData]]"].has(key)},add:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){this._storage[fkey]=true;return}ensureMap(this);this["[[SetData]]"].set(key,key);return this},"delete":function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){var hasFKey=_hasOwnProperty.call(this._storage,fkey);return delete this._storage[fkey]&&hasFKey}ensureMap(this);return this["[[SetData]]"]["delete"](key)},clear:function(){if(this._storage){this._storage=emptyObject();return}return this["[[SetData]]"].clear()},keys:function(){ensureMap(this);return this["[[SetData]]"].keys()},values:function(){ensureMap(this);return this["[[SetData]]"].values()},entries:function(){ensureMap(this);return this["[[SetData]]"].entries()},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var entireSet=this;ensureMap(this);this["[[SetData]]"].forEach(function(value,key){callback.call(context,key,key,entireSet)})}});addIterator(SetShim.prototype,function(){return this.values()});return SetShim}()};defineProperties(globals,collectionShims);if(globals.Map||globals.Set){if(typeof globals.Map.prototype.clear!=="function"||(new globals.Set).size!==0||(new globals.Map).size!==0||typeof globals.Map.prototype.keys!=="function"||typeof globals.Set.prototype.keys!=="function"||typeof globals.Map.prototype.forEach!=="function"||typeof globals.Set.prototype.forEach!=="function"||isCallableWithoutNew(globals.Map)||isCallableWithoutNew(globals.Set)||!supportsSubclassing(globals.Map,function(M){var m=new M([]);m.set(42,42);return m instanceof M})){globals.Map=collectionShims.Map;globals.Set=collectionShims.Set}}addIterator(Object.getPrototypeOf((new globals.Map).keys()));addIterator(Object.getPrototypeOf((new globals.Set).keys()))}return globals})}).call(this,require("_process"))},{_process:2}],4:[function(require,module,exports){"use strict";if(!require("./is-implemented")()){Object.defineProperty(require("es5-ext/global"),"Symbol",{value:require("./polyfill"),configurable:true,enumerable:false,writable:true})}},{"./is-implemented":5,"./polyfill":20,"es5-ext/global":7}],5:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.isRegExp!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],6:[function(require,module,exports){"use strict";var assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),isCallable=require("es5-ext/object/is-callable"),contains=require("es5-ext/string/#/contains"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":8,"es5-ext/object/is-callable":11,"es5-ext/object/normalize-options":15,"es5-ext/string/#/contains":17}],7:[function(require,module,exports){"use strict";module.exports=new Function("return this")()},{}],8:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":9,"./shim":10}],9:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],10:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<l;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":12,"../valid-value":16}],11:[function(require,module,exports){"use strict";module.exports=function(obj){return typeof obj==="function"}},{}],12:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":13,"./shim":14}],13:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],14:[function(require,module,exports){"use strict";var keys=Object.keys;module.exports=function(object){return keys(object==null?object:Object(object))}},{}],15:[function(require,module,exports){"use strict";var assign=require("./assign"),forEach=Array.prototype.forEach,create=Object.create,getPrototypeOf=Object.getPrototypeOf,process;process=function(src,obj){var proto=getPrototypeOf(src);return assign(proto?process(proto,obj):obj,src)};module.exports=function(options){var result=create(null);forEach.call(arguments,function(options){if(options==null)return;process(Object(options),result)});return result}},{"./assign":8}],16:[function(require,module,exports){"use strict";module.exports=function(value){if(value==null)throw new TypeError("Cannot use null or undefined");return value}},{}],17:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":18,"./shim":19}],18:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],19:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],20:[function(require,module,exports){"use strict";var d=require("d"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;return"@@"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError("TypeError: Symbol is not a constructor")}symbol=create(Symbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};Object.defineProperties(Symbol,{create:d("",Symbol("create")),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),isRegExp:d("",Symbol("isRegExp")),iterator:d("",Symbol("iterator")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(Symbol.prototype,{properToString:d(function(){return"Symbol ("+this.__description__+")"}),toString:d("",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(hint){throw new TypeError("Conversion of symbol objects is not allowed")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"))},{d:6}],21:[function(require,module,exports){"use strict";module.exports=require("./lib/core.js");require("./lib/done.js");require("./lib/es6-extensions.js");require("./lib/node-extensions.js")},{"./lib/core.js":22,"./lib/done.js":23,"./lib/es6-extensions.js":24,"./lib/node-extensions.js":25}],22:[function(require,module,exports){"use strict";var asap=require("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 self.constructor(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{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}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:26}],23:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;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})})}},{"./core.js":22,asap:26}],24:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;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=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.all=function(arr){var args=Array.prototype.slice.call(arr);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)})})};Promise.prototype["catch"]=function(onRejected){return this.then(null,onRejected)}},{"./core.js":22,asap:26}],25:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;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;var ctx=this;try{return fn.apply(this,arguments).nodeify(callback,ctx)}catch(ex){if(callback===null||typeof callback=="undefined"){return new Promise(function(resolve,reject){reject(ex)})}else{asap(function(){callback.call(ctx,ex)})}}}};Promise.prototype.nodeify=function(callback,ctx){if(typeof callback!="function")return this;this.then(function(value){asap(function(){callback.call(ctx,null,value)})},function(err){asap(function(){callback.call(ctx,err)})})}},{"./core.js":22,asap:26}],26:[function(require,module,exports){(function(process){var head={task:void 0,next:null};var tail=head;var flushing=false;var requestFlush=void 0;var isNodeJS=false;function flush(){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){if(domain){domain.exit()}setTimeout(flush,0);if(domain){domain.enter()}throw e}else{setTimeout(function(){throw e},0)}}if(domain){domain.exit()}}flushing=false}if(typeof process!=="undefined"&&process.nextTick){isNodeJS=true;requestFlush=function(){process.nextTick(flush)}}else if(typeof setImmediate==="function"){if(typeof window!=="undefined"){requestFlush=setImmediate.bind(window,flush)}else{requestFlush=function(){setImmediate(flush)}}}else if(typeof MessageChannel!=="undefined"){var channel=new MessageChannel;channel.port1.onmessage=flush;requestFlush=function(){channel.port2.postMessage(0)}}else{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,require("_process"))},{_process:2}],27:[function(require,module,exports){!function(){var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";if(typeof Promise==="undefined")try{Promise=require("promise")}catch(ignored){}if(typeof regeneratorRuntime==="object"){return}var runtime=regeneratorRuntime=typeof exports==="undefined"?{}:exports;function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}var Gp=Generator.prototype;var GFp=GeneratorFunction.prototype=Object.create(Function.prototype);GFp.constructor=GeneratorFunction;GFp.prototype=Gp;Gp.constructor=GFp;if(GeneratorFunction.name!=="GeneratorFunction"){GeneratorFunction.name="GeneratorFunction"}if(GeneratorFunction.name!=="GeneratorFunction"){throw new Error("GeneratorFunction renamed?")}runtime.isGeneratorFunction=function(genFun){var ctor=genFun&&genFun.constructor;return ctor?GeneratorFunction.name===ctor.name:false};runtime.mark=function(genFun){genFun.__proto__=GFp;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator.throw);function step(arg){try{var info=this(arg);var value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){throw new Error("Generator has already finished")}while(true){var delegate=context.delegate;if(delegate){try{var info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator.throw=invoke.bind(generator,"throw");generator.return=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){var iterator=iterable;if(iteratorSymbol in iterable){iterator=iterable[iteratorSymbol]()}else if(!isNaN(iterable.length)){var i=-1;iterator=function next(){while(++i<iterable.length){if(i in iterable){next.value=iterable[i];next.done=false;return next}}next.done=true;return next};iterator.next=iterator}return iterator}runtime.values=values;Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}()},{promise:21}]},{},[1]); |
src/client/public/signup/component.js | k-sheth/react-getting-started | 'use strict';
const React = require('react');
const _ = require('./../../common/lodash');
const forms = require('./../../common/mixins/forms');
const debug = require('./../../common/mixins/dev-tools');
const {signup: {payload: signupSchema}} = require('./../../../shared/rest-api')(require('joi-browser'), _).users;
const connectToStore = require('./../../common/mixins/connectToStore');
const Store = require('./store');
const Actions = require('./actions');
const displayName = 'Signup';
module.exports = {
Main: React.createClass({
displayName,
mixins: [connectToStore(displayName, Store), forms(displayName), debug(displayName)],
getDefaultProps() {
return {
email: '',
password: ''
};
},
componentWillMount() {
this.__changeTitle(this.__meta('title'));
},
componentWillUnmount() {
Actions.triggerUI('signup.end');
},
onSubmit() {
const forSignup = Actions.validate('signup', signupSchema, _.merge({organisation: 'silver lining'}, this.__getValues(['email', 'password'])));
/*istanbul ignore else*/
if (forSignup) {
Actions.signup(forSignup);
}
},
render() {
const inputOptions = {};
return (
<form>
<h1 className={'page-header'}>{this.__body('PageHeader')}</h1>
{this.__renderAlerts()}
{this.__renderInput('text', 'email', _.merge({focusOnMount: true}, inputOptions))}
{this.__renderInput('password', 'password', inputOptions)}
{this.__renderButton('Signup', this.onSubmit, {className: 'pull-right', bsStyle: 'primary'})}
</form>
);
}
}),
...require('./../nav')
};
|
src/svg-icons/av/equalizer.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvEqualizer = (props) => (
<SvgIcon {...props}>
<path d="M10 20h4V4h-4v16zm-6 0h4v-8H4v8zM16 9v11h4V9h-4z"/>
</SvgIcon>
);
AvEqualizer = pure(AvEqualizer);
AvEqualizer.displayName = 'AvEqualizer';
AvEqualizer.muiName = 'SvgIcon';
export default AvEqualizer;
|
generators/electron/modules/app/containers/DevTools.js | sahat/megaboilerplate | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-q"
>
<LogMonitor />
</DockMonitor>
);
|
react/src/base/inputs/SprkCheckbox/SprkCheckboxGroup/SprkCheckboxGroup.js | sparkdesignsystem/spark-design-system | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import SprkErrorContainer from '../../SprkErrorContainer/SprkErrorContainer';
import SprkFieldError from '../../SprkFieldError/SprkFieldError';
import SprkHelperText from '../../SprkHelperText/SprkHelperText';
import SprkFieldset from '../../SprkFieldset/SprkFieldset';
class SprkCheckboxGroup extends Component {
constructor(props) {
super(props);
this.renderChildren = this.renderChildren.bind(this);
}
/**
* A function that is run when the component renders.
* It processes and updates the children & grandchildren that
* are passed into the SprkCheckboxGroup to add necessary
* a11y considerations.
* `ariaDescribedby` is checked and updated on the SprkFieldset
* element to include the `id` of the `SprkHelperText`,
* `SprkFieldError`, and `SprkErrorContainer` if present among
* the children and grandchildren.
* @returns {object} Processed and updated children elements
*/
renderChildren() {
const { children } = this.props;
let errorContainerID;
let helperTextID;
let ariaDescribedByArray = [];
let fieldsetAriaDescribedBy;
/*
* Checks each child element and grandchild element to
* store the provided `ariaDescribedby` on the SprkFieldset,
* `id` of the SprkFieldError, SprkErrorContainer,
* and SprkHelperText in variables for processing.
*/
React.Children.forEach(children, (child) => {
/**
* Add this check in case the child is being
* conditionally rendered.
* If the child is not rendered but returns a React fragment the
* child will return null and break without this check.
*/
if (child === null) {
return;
}
/**
* If the child element is a SprkFieldset, then the
* `ariaDescribedBy` is stored for later use.
*/
if (child.type && child.type.name === SprkFieldset.name) {
fieldsetAriaDescribedBy = child.props.ariaDescribedBy;
}
/**
* If the child element is a SprkFieldError or SprkErrorContainer,
* then the `id` is stored for later use.
*/
if (
child.type &&
(child.type.name === SprkFieldError.name ||
child.type.name === SprkErrorContainer.name)
) {
errorContainerID = child.props.id;
}
/**
* If the child element is a SprkHelperText,
* then the `id` is stored for later use.
*/
if (child.type && child.type.name === SprkHelperText.name) {
helperTextID = child.props.id;
}
/**
* If the child element has it's own children,
* check the grandchildren to get the necessary values.
*/
if (child.props && child.props.children) {
React.Children.forEach(child.props.children, (grandchild) => {
/**
* Add this check in case the grandchild is being
* conditionally rendered.
* If the grandchild is not rendered but returns a React fragment the
* grandchild will return null and break without this check.
*/
if (grandchild === null) {
return;
}
/**
* If the grandchild element is a SprkFieldset, then the
* `ariaDescribedBy` is stored for later use.
*/
if (grandchild.type && grandchild.type.name === SprkFieldset.name) {
fieldsetAriaDescribedBy = grandchild.props.ariaDescribedBy;
}
/**
* If the grandchild element is a SprkFieldError or
* SprkErrorContainer, then the `id` is stored for later use.
*/
if (
grandchild.type &&
(grandchild.type.name === SprkFieldError.name ||
grandchild.type.name === SprkErrorContainer.name)
) {
errorContainerID = grandchild.props.id;
}
/**
* If the grandchild element is a SprkHelperText,
* then the `id` is stored for later use.
*/
if (grandchild.type && grandchild.type.name === SprkHelperText.name) {
helperTextID = grandchild.props.id;
}
});
}
});
/**
* If there is a SprkHelperText, SprkFieldError, or SprkErrorContainer
* present in the children elements then start the `ariaDescribedBy`
* processing.
*/
if (helperTextID || errorContainerID) {
/**
* If an `ariaDescribedBy` was provided on the SprkFieldset,
* then split the string into an array.
*/
if (fieldsetAriaDescribedBy) {
ariaDescribedByArray = fieldsetAriaDescribedBy.split(' ');
}
/**
* If there is a SprkHelperText element present and the `id` is not
* present in the SprkFieldset's `ariaDescribedBy` array, add it.
*/
if (helperTextID && !ariaDescribedByArray.includes(helperTextID)) {
ariaDescribedByArray.push(helperTextID);
}
/**
* If there is a SprkFieldError or SprkErrorContainer element present
* and the `id` is not present in the SprkFieldset's `ariaDescribedBy`
* array, add it.
*/
if (
errorContainerID &&
!ariaDescribedByArray.includes(errorContainerID)
) {
ariaDescribedByArray.push(errorContainerID);
}
/**
* Once the necessary values have been added to the `ariaDescribedBy`
* array, rejoin the values to make a string that will be passed to the
* SprkFieldset prop.
*/
fieldsetAriaDescribedBy = ariaDescribedByArray.join(' ');
}
/*
* If there is an `fieldsetAriaDescribedBy` value map through
* the children to update the SprkFieldset `ariaDescribedBy` prop.
*/
if (fieldsetAriaDescribedBy) {
const childrenElements = React.Children.map(children, (child) => {
/**
* Add this check in case the child is being
* conditionally rendered.
* If the child is not rendered but returns a React fragment the
* child will return null and break without this check.
*/
if (child === null) {
return child;
}
/**
* If the child element is a SprkFieldset, then clone the child
* element and update the `ariaDescribedBy` prop with the correct value.
*/
if (child.type && child.type.name === SprkFieldset.name) {
return React.cloneElement(child, {
ariaDescribedBy: fieldsetAriaDescribedBy,
});
}
/**
* If the child element has it's own children,
* map the grandchildren to update the values.
*/
if (child.props.children) {
const grandchildrenElements = React.Children.map(
child.props.children,
(grandchild) => {
/**
* Add this check in case the grandchild is being
* conditionally rendered.
* If the grandchild is not rendered but returns a React fragment
* the grandchild will return null and break without this check.
*/
if (grandchild === null) {
return grandchild;
}
/**
* If the grandchild element is a SprkFieldset,
* then clone the grandchild element and update
* the `ariaDescribedBy` prop with the correct value.
*/
if (
grandchild.type &&
grandchild.type.name === SprkFieldset.name
) {
return React.cloneElement(grandchild, {
ariaDescribedBy: fieldsetAriaDescribedBy,
});
}
/**
* If the grandchild element does not need to be updated
* with the `ariaDescribedBy` criteria,
* return it without updating any props.
*/
return grandchild;
},
);
/**
* If there were grandchildren, return the child with the
* processed grandchildren elements.
*/
return React.cloneElement(child, {
children: grandchildrenElements,
});
}
/**
* If the child element does not need to be updated
* with the `ariaDescribedBy` criteria,
* return it without updating any props.
*/
return child;
});
/**
* Return the child elements to be rendered.
*/
return childrenElements;
}
/** Return other elements. ex. <div> */
return children;
}
render() {
const {
variant,
idString,
additionalClasses,
analyticsString,
...rest
} = this.props;
return (
<div
className={classnames('sprk-b-InputContainer', additionalClasses, {
'sprk-b-InputContainer--huge': variant === 'huge',
})}
data-analytics={analyticsString}
data-id={idString}
{...rest}
>
{this.renderChildren()}
</div>
);
}
}
SprkCheckboxGroup.propTypes = {
/** Content to render inside of the component. */
children: PropTypes.node,
/**
* Determines the style of checkbox.
* Supplying no value will cause the default styles to be used.
*/
variant: PropTypes.oneOf(['huge']),
/**
* Assigned to the `data-id` attribute serving as
* a unique selector for automated tools.
*/
idString: PropTypes.string,
/**
* Assigned to the `data-analytics` attribute
* serving as a unique selector for outside libraries to capture data.
*/
analyticsString: PropTypes.string,
/**
* A space-separated string of classes
* to add to the outermost container of the component.
*/
additionalClasses: PropTypes.string,
};
export default SprkCheckboxGroup;
|
Examples/simple-fcm-client/index.ios.js | riyaz942/react-native-fcm | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import App from "./app/App";
export default class SimpleFcmClient extends Component {
render() {
return (<App />);
}
}
AppRegistry.registerComponent('SimpleFcmClient', () => SimpleFcmClient);
|
src/client/components/HelloWorld.js | jahe/jahe-react-starter | import React from 'react';
import { FormattedRelative, FormattedMessage } from 'react-intl';
import moment from 'moment';
export default function HelloWorld() {
return (
<h1 className="hw-headline">
<span>
<FormattedMessage
id="app.helloWorld.greeting"
description="Greeting to welcome the user to the app"
defaultMessage="Hello, {name}! Last Action: {date}"
values={{
name: <i>World</i>,
date: (
<FormattedRelative
value={moment().add(7, 'days')}
options={{ style: 'numeric', units: 'second' }}
/>
)
}}
/>
</span>
</h1>
);
}
|
src/index.js | kleros/kleros-front | import React from 'react'
import ReactDOM from 'react-dom'
import App from './bootstrap/App'
import store from './bootstrap/store'
/**
* Render App React component
*/
ReactDOM.render(
<App store={store} />,
document.getElementById('root')
)
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/DefaultParameters.js | tharakawj/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load(id = 0) {
return [
{ id: id + 1, name: '1' },
{ id: id + 2, name: '2' },
{ id: id + 3, name: '3' },
{ id: id + 4, name: '4' },
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-default-parameters">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
ajax/libs/raven.js/3.19.0/plugins/angular.js | wout/cdnjs | /*! Raven.js 3.19.0 (98bda52) | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2017 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
(function(f) {
if (typeof exports === 'object' && typeof module !== 'undefined') {
module.exports = f();
} else if (typeof define === 'function' && define.amd) {
define([], f);
} else {
var g;
if (typeof window !== 'undefined') {
g = window;
} else if (typeof global !== 'undefined') {
g = global;
} else if (typeof self !== 'undefined') {
g = self;
} else {
g = this;
}
g = g.Raven || (g.Raven = {});
g = g.Plugins || (g.Plugins = {});
g.Angular = f();
}
})(function() {
var define, module, exports;
return (function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof require == 'function' && require;
if (!u && a) return a(o, !0);
if (i) return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw ((f.code = 'MODULE_NOT_FOUND'), f);
}
var l = (n[o] = {exports: {}});
t[o][0].call(
l.exports,
function(e) {
var n = t[o][1][e];
return s(n ? n : e);
},
l,
l.exports,
e,
t,
n,
r
);
}
return n[o].exports;
}
var i = typeof require == 'function' && require;
for (var o = 0; o < r.length; o++) s(r[o]);
return s;
})(
{
1: [
function(_dereq_, module, exports) {
/**
* Angular.js plugin
*
* Provides an $exceptionHandler for Angular.js
*/
var wrappedCallback = _dereq_(2).wrappedCallback;
// See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js
var angularPattern = /^\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\] (.*?)\n?(\S+)$/;
var moduleName = 'ngRaven';
function angularPlugin(Raven, angular) {
angular = angular || window.angular;
if (!angular) return;
function RavenProvider() {
this.$get = [
'$window',
function($window) {
return Raven;
}
];
}
function ExceptionHandlerProvider($provide) {
$provide.decorator('$exceptionHandler', [
'Raven',
'$delegate',
exceptionHandler
]);
}
function exceptionHandler(R, $delegate) {
return function(ex, cause) {
R.captureException(ex, {
extra: {cause: cause}
});
$delegate(ex, cause);
};
}
angular
.module(moduleName, [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
var exception = data.exception;
if (exception) {
exception = exception.values[0];
var matches = angularPattern.exec(exception.value);
if (matches) {
// This type now becomes something like: $rootScope:inprog
exception.type = matches[1];
exception.value = matches[2];
data.message = exception.type + ': ' + exception.value;
// auto set a new tag specifically for the angular error url
data.extra.angularDocs = matches[3].substr(0, 250);
}
}
return data;
};
angularPlugin.moduleName = moduleName;
module.exports = angularPlugin;
},
{'2': 2}
],
2: [
function(_dereq_, module, exports) {
(function(global) {
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: typeof self !== 'undefined' ? self : {};
function isObject(what) {
return typeof what === 'object' && what !== null;
}
// Yanked from https://git.io/vS8DV re-used under CC0
// with some tiny modifications
function isError(value) {
switch ({}.toString.call(value)) {
case '[object Error]':
return true;
case '[object Exception]':
return true;
case '[object DOMException]':
return true;
default:
return value instanceof Error;
}
}
function isErrorEvent(value) {
return (
supportsErrorEvent() && {}.toString.call(value) === '[object ErrorEvent]'
);
}
function isUndefined(what) {
return what === void 0;
}
function isFunction(what) {
return typeof what === 'function';
}
function isString(what) {
return Object.prototype.toString.call(what) === '[object String]';
}
function isEmptyObject(what) {
for (var _ in what) return false; // eslint-disable-line guard-for-in, no-unused-vars
return true;
}
function supportsErrorEvent() {
try {
new ErrorEvent(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function wrappedCallback(callback) {
function dataCallback(data, original) {
var normalizedData = callback(data) || data;
if (original) {
return original(normalizedData) || normalizedData;
}
return normalizedData;
}
return dataCallback;
}
function each(obj, callback) {
var i, j;
if (isUndefined(obj.length)) {
for (i in obj) {
if (hasKey(obj, i)) {
callback.call(null, i, obj[i]);
}
}
} else {
j = obj.length;
if (j) {
for (i = 0; i < j; i++) {
callback.call(null, i, obj[i]);
}
}
}
}
function objectMerge(obj1, obj2) {
if (!obj2) {
return obj1;
}
each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
/**
* This function is only used for react-native.
* react-native freezes object that have already been sent over the
* js bridge. We need this function in order to check if the object is frozen.
* So it's ok that objectFrozen returns false if Object.isFrozen is not
* supported because it's not relevant for other "platforms". See related issue:
* https://github.com/getsentry/react-native-sentry/issues/57
*/
function objectFrozen(obj) {
if (!Object.isFrozen) {
return false;
}
return Object.isFrozen(obj);
}
function truncate(str, max) {
return !max || str.length <= max ? str : str.substr(0, max) + '\u2026';
}
/**
* hasKey, a better form of hasOwnProperty
* Example: hasKey(MainHostObject, property) === true/false
*
* @param {Object} host object to check property
* @param {string} key to check
*/
function hasKey(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
function joinRegExp(patterns) {
// Combine an array of regular expressions and strings into one large regexp
// Be mad.
var sources = [],
i = 0,
len = patterns.length,
pattern;
for (; i < len; i++) {
pattern = patterns[i];
if (isString(pattern)) {
// If it's a string, we need to escape it
// Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'));
} else if (pattern && pattern.source) {
// If it's a regexp already, we want to extract the source
sources.push(pattern.source);
}
// Intentionally skip other cases
}
return new RegExp(sources.join('|'), 'i');
}
function urlencode(o) {
var pairs = [];
each(o, function(key, value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return pairs.join('&');
}
// borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
// intentionally using regex and not <a/> href parsing trick because React Native and other
// environments where DOM might not be available
function parseUrl(url) {
var match = url.match(
/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/
);
if (!match) return {};
// coerce to undefined values to empty string so we don't get 'undefined'
var query = match[6] || '';
var fragment = match[8] || '';
return {
protocol: match[2],
host: match[4],
path: match[5],
relative: match[5] + query + fragment // everything minus origin
};
}
function uuid4() {
var crypto = _window.crypto || _window.msCrypto;
if (!isUndefined(crypto) && crypto.getRandomValues) {
// Use window.crypto API if available
// eslint-disable-next-line no-undef
var arr = new Uint16Array(8);
crypto.getRandomValues(arr);
// set 4 in byte 7
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
arr[4] = (arr[4] & 0x3fff) | 0x8000;
var pad = function(num) {
var v = num.toString(16);
while (v.length < 4) {
v = '0' + v;
}
return v;
};
return (
pad(arr[0]) +
pad(arr[1]) +
pad(arr[2]) +
pad(arr[3]) +
pad(arr[4]) +
pad(arr[5]) +
pad(arr[6]) +
pad(arr[7])
);
} else {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
}
/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @param elem
* @returns {string}
*/
function htmlTreeAsString(elem) {
/* eslint no-extra-parens:0*/
var MAX_TRAVERSE_HEIGHT = 5,
MAX_OUTPUT_LEN = 80,
out = [],
height = 0,
len = 0,
separator = ' > ',
sepLength = separator.length,
nextStr;
while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = htmlElementAsString(elem);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds MAX_OUTPUT_LEN
// (ignore this limit if we are on the first iteration)
if (
nextStr === 'html' ||
(height > 1 &&
len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)
) {
break;
}
out.push(nextStr);
len += nextStr.length;
elem = elem.parentNode;
}
return out.reverse().join(separator);
}
/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @param HTMLElement
* @returns {string}
*/
function htmlElementAsString(elem) {
var out = [],
className,
classes,
key,
attr,
i;
if (!elem || !elem.tagName) {
return '';
}
out.push(elem.tagName.toLowerCase());
if (elem.id) {
out.push('#' + elem.id);
}
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push('.' + classes[i]);
}
}
var attrWhitelist = ['type', 'name', 'title', 'alt'];
for (i = 0; i < attrWhitelist.length; i++) {
key = attrWhitelist[i];
attr = elem.getAttribute(key);
if (attr) {
out.push('[' + key + '="' + attr + '"]');
}
}
return out.join('');
}
/**
* Returns true if either a OR b is truthy, but not both
*/
function isOnlyOneTruthy(a, b) {
return !!(!!a ^ !!b);
}
/**
* Returns true if the two input exception interfaces have the same content
*/
function isSameException(ex1, ex2) {
if (isOnlyOneTruthy(ex1, ex2)) return false;
ex1 = ex1.values[0];
ex2 = ex2.values[0];
if (ex1.type !== ex2.type || ex1.value !== ex2.value) return false;
return isSameStacktrace(ex1.stacktrace, ex2.stacktrace);
}
/**
* Returns true if the two input stack trace interfaces have the same content
*/
function isSameStacktrace(stack1, stack2) {
if (isOnlyOneTruthy(stack1, stack2)) return false;
var frames1 = stack1.frames;
var frames2 = stack2.frames;
// Exit early if frame count differs
if (frames1.length !== frames2.length) return false;
// Iterate through every frame; bail out if anything differs
var a, b;
for (var i = 0; i < frames1.length; i++) {
a = frames1[i];
b = frames2[i];
if (
a.filename !== b.filename ||
a.lineno !== b.lineno ||
a.colno !== b.colno ||
a['function'] !== b['function']
)
return false;
}
return true;
}
/**
* Polyfill a method
* @param obj object e.g. `document`
* @param name method name present on object e.g. `addEventListener`
* @param replacement replacement function
* @param track {optional} record instrumentation to an array
*/
function fill(obj, name, replacement, track) {
var orig = obj[name];
obj[name] = replacement(orig);
if (track) {
track.push([obj, name, orig]);
}
}
module.exports = {
isObject: isObject,
isError: isError,
isErrorEvent: isErrorEvent,
isUndefined: isUndefined,
isFunction: isFunction,
isString: isString,
isEmptyObject: isEmptyObject,
supportsErrorEvent: supportsErrorEvent,
wrappedCallback: wrappedCallback,
each: each,
objectMerge: objectMerge,
truncate: truncate,
objectFrozen: objectFrozen,
hasKey: hasKey,
joinRegExp: joinRegExp,
urlencode: urlencode,
uuid4: uuid4,
htmlTreeAsString: htmlTreeAsString,
htmlElementAsString: htmlElementAsString,
isSameException: isSameException,
isSameStacktrace: isSameStacktrace,
parseUrl: parseUrl,
fill: fill
};
}.call(
this,
typeof global !== 'undefined'
? global
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined' ? window : {}
));
},
{}
]
},
{},
[1]
)(1);
});
|
app/javascript/components/conditions/SkipLogicFormField/SkipRuleFormField/injector.js | thecartercenter/elmo | import React from 'react';
import PropTypes from 'prop-types';
import { Provider } from 'mobx-react';
import ConditionSetModel from '../../ConditionSetFormField/model';
import { provideConditionSetStore } from '../../ConditionSetFormField/utils';
import SkipRuleFormField from './component';
let forcedResetNonce = 0;
/**
* Provides any needed stores to its children.
*/
function Injector(props) {
const {
ruleId,
formId,
namePrefix,
conditions,
id,
refableQings,
skipIf,
} = props;
// eslint-disable-next-line react/prop-types, react/destructuring-assignment
const conditionSetStore = provideConditionSetStore(ConditionSetModel, `skip-${ruleId}`, {
formId,
namePrefix: `${namePrefix}[conditions_attributes]`,
conditions,
conditionableId: id,
conditionableType: 'SkipRule',
refableQings,
hide: skipIf === 'always',
});
// eslint-disable-next-line no-return-assign
return (
<Provider key={forcedResetNonce += 1} conditionSetStore={conditionSetStore}>
<SkipRuleFormField {...props} />
</Provider>
);
}
Injector.propTypes = {
ruleId: PropTypes.string.isRequired,
namePrefix: PropTypes.string.isRequired,
// TODO: Describe these prop types.
/* eslint-disable react/forbid-prop-types */
formId: PropTypes.any,
conditions: PropTypes.any,
id: PropTypes.any,
refableQings: PropTypes.any,
skipIf: PropTypes.any,
/* eslint-enable */
};
export default Injector;
|
src/js/components/PostPreview.js | slavapavlutin/pavlutin-node | import React from 'react';
import { Link } from 'react-router-dom';
import Markdown from 'react-markdown';
import Icon from 'react-fontawesome';
import Tags from './Tags';
import { toHumanReadableDate } from '../utils';
import {
Container,
Header,
Title,
Meta,
Description,
Button,
} from './PostPreview.styled';
function PostPreview({ post, activeTag }) {
const URL = `/blog/${post.slug}`;
return (
<Container>
<Header>
<Title>
<Link to={URL} title={`Read ${post.title}`}>
{post.title}
</Link>
</Title>
<Meta>
<Icon name="clock-o" /> {' '}
{toHumanReadableDate(post.createdAt)}
</Meta>
<Tags
activeTag={activeTag}
tags={post.tags}
className="preview__tags"
/>
</Header>
<Description>
<Markdown source={post.description || "There's no description."} />
</Description>
<Button>
<Link to={URL}>Keep Reading</Link>
</Button>
</Container>
);
}
export default PostPreview;
|
exercise-06-solution/src/components/AddPokemonCard.js | learnapollo/pokedex-react | import React from 'react'
import { withRouter } from 'react-router'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import styled from 'styled-components'
const Button = styled.div`
background-color: ${props => props.save ? '#2BC3A1' : ''};
color: ${props => props.save ? 'white' : '#A3A3A3'};
height: 48px;
line-height: 1;
font-size: 18px;
padding: 15px 30px;
cursor: pointer;
font-weight: 300;
border-radius: 4px
`
const ImageContainer = styled.div`
width: 100%;
background-color: #F7F7F7;
min-height: 250px;
margin-bottom: 20px;
`
const Card = styled.div`
background-color: white;
box-shadow: 0 1px 11px 0 rgba(0, 0, 0, 0.2);
border-radius: 3px;
padding: 20px;
`
class AddPokemonCard extends React.Component {
static propTypes = {
router: React.PropTypes.object.isRequired,
mutate: React.PropTypes.func.isRequired,
params: React.PropTypes.object.isRequired,
}
state = {
name: '',
url: '',
}
render () {
return (
<div className='w-100 pa4 flex justify-center'>
<Card style={{ maxWidth: 400 }} className=''>
<input
className='w-100 pa3 mv2'
value={this.state.name}
placeholder='Name'
onChange={(e) => this.setState({name: e.target.value})}
/>
<input
className='w-100 pa3 mv2'
value={this.state.url}
placeholder='Image Url'
onChange={(e) => this.setState({url: e.target.value})}
/>
<ImageContainer>
{this.state.url &&
<img src={this.state.url} role='presentation' className='w-100 mv3' />
}
</ImageContainer>
<div className='flex justify-between'>
<Button onClick={this.handleCancel}>Cancel</Button>
{this.canSave()
? <Button save onClick={this.handleSave}>Save</Button>
: <Button disabled>Save</Button>
}
</div>
</Card>
</div>
)
}
canSave = () => {
return this.state.name && this.state.url
}
handleSave = () => {
const {name, url} = this.state
const trainerId = this.props.params.trainerId
this.props.mutate({variables: {name, url, trainerId}})
.then(() => {
this.props.router.replace('/')
})
}
handleCancel = () => {
this.props.router.replace('/')
}
}
const createPokemonMutation = gql`
mutation createPokemon($name: String!, $url: String!, $trainerId: ID) {
createPokemon(name: $name, url: $url, trainerId: $trainerId) {
id
}
}
`
const AddPokemonCardWithMutation = graphql(createPokemonMutation)(withRouter(AddPokemonCard))
export default AddPokemonCardWithMutation
|
app/javascript/mastodon/components/avatar_overlay.js | robotstart/mastodon | import React from 'react';
import PropTypes from 'prop-types';
class AvatarOverlay extends React.PureComponent {
render() {
const {staticSrc, overlaySrc} = this.props;
const baseStyle = {
backgroundImage: `url(${staticSrc})`
};
const overlayStyle = {
backgroundImage: `url(${overlaySrc})`
};
return (
<div className='account__avatar-overlay'>
<div className="account__avatar-overlay-base" style={baseStyle} />
<div className="account__avatar-overlay-overlay" style={overlayStyle} />
</div>
);
}
}
AvatarOverlay.propTypes = {
staticSrc: PropTypes.string.isRequired,
overlaySrc: PropTypes.string.isRequired,
};
export default AvatarOverlay;
|
ajax/libs/cyclejs-core/1.0.0-rc1/cycle.js | LeaYeh/cdnjs | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Cycle = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// 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; };
},{}],2:[function(require,module,exports){
(function (process,global){
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
Error.call(this);
};
EmptyError.prototype = Error.prototype;
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
Error.call(this);
};
ObjectDisposedError.prototype = Error.prototype;
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Error.prototype;
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
Error.call(this);
};
NotSupportedError.prototype = Error.prototype;
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
Error.call(this);
};
NotImplementedError.prototype = Error.prototype;
var notImplemented = Rx.helpers.notImplemented = function () {
throw new NotImplementedError();
};
var notSupported = Rx.helpers.notSupported = function () {
throw new NotSupportedError();
};
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
tryCatchTarget = fn;
return tryCatcher;
}
function thrower(e) {
throw e;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
this.items[this.length] = undefined;
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
len = args.length;
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
for(i = 0; i < len; i++) {
if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
// Single assignment
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SingleAssignmentDisposable.prototype.getDisposable = function () {
return this.current;
};
SingleAssignmentDisposable.prototype.setDisposable = function (value) {
if (this.current) { throw new Error('Disposable has already been assigned'); }
var shouldDispose = this.isDisposed;
!shouldDispose && (this.current = value);
shouldDispose && value && value.dispose();
};
SingleAssignmentDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
// Multiple assignment disposable
var SerialDisposable = Rx.SerialDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SerialDisposable.prototype.getDisposable = function () {
return this.current;
};
SerialDisposable.prototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
SerialDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.scheduleWithState(this, scheduleItem);
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
/** Determines whether the given object is a scheduler */
Scheduler.isScheduler = function (s) {
return s instanceof Scheduler;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
}
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState([state, action], invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
period = normalizeTime(period);
var s = state, id = root.setInterval(function () { s = action(s); }, period);
return disposableCreate(function () { root.clearInterval(id); });
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.dequeue();
!item.isCancelled() && item.invoke();
}
}
function scheduleNow(state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { return thrower(result.e); }
} else {
queue.enqueue(si);
}
return si.disposable;
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
currentScheduler.scheduleRequired = function () { return !queue; };
return currentScheduler;
}());
var scheduleMethod, clearMethod;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else if (!!root.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
clearMethod = function (handle) {
delete tasksByHandle[handle];
};
function runTask(handle) {
if (currentlyRunning) {
localSetTimeout(function () { runTask(handle) }, 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunning = true;
var result = tryCatch(task)();
clearMethod(handle);
currentlyRunning = false;
if (result === errorObj) { return thrower(result.e); }
}
}
}
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false, oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (isFunction(setImmediate)) {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
setImmediate(function () { runTask(id); });
return id;
};
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
process.nextTick(function () { runTask(id); });
return id;
};
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
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) {
runTask(event.data.substring(MSG_PREFIX.length));
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else if (root.attachEvent) {
root.attachEvent('onmessage', onGlobalPostMessage);
} else {
root.onmessage = onGlobalPostMessage;
}
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
return id;
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel();
channel.port1.onmessage = function (e) { runTask(e.data); };
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
channel.port2.postMessage(id);
return id;
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
var id = nextHandle++;
tasksByHandle[id] = action;
scriptElement.onreadystatechange = function () {
runTask(id);
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
return id;
};
} else {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
localSetTimeout(function () {
runTask(id);
}, 0);
return id;
};
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () {
function scheduleNow(state, action) {
var scheduler = this, disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
!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), disposable = new SingleAssignmentDisposable();
if (dt === 0) { return scheduler.scheduleWithState(state, action); }
var id = localSetTimeout(function () {
!disposable.isDisposed && disposable.setDisposable(action(scheduler, state));
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, value, exception, accept, acceptObservable, toString) {
this.kind = kind;
this.value = value;
this.exception = exception;
this._accept = accept;
this._acceptObservable = acceptObservable;
this.toString = toString;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(self, function (_, notification) {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept(onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString() { return 'OnNext(' + this.value + ')'; }
return function (value) {
return new Notification('N', value, null, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
return new Notification('E', null, e, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
return new Notification('C', null, null, _accept, _acceptObservable, toString);
};
}());
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
Observer.prototype.makeSafe = function(disposable) {
return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (__super__) {
inherits(CheckedObserver, __super__);
function CheckedObserver(observer) {
__super__.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
var res = tryCatch(this._observer.onNext).call(this._observer, value);
this._state = 0;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
var res = tryCatch(this._observer.onError).call(this._observer, err);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
var res = tryCatch(this._observer.onCompleted).call(this._observer);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
var Enumerable = Rx.internals.Enumerable = function () { };
var ConcatEnumerableObservable = (function(__super__) {
inherits(ConcatEnumerableObservable, __super__);
function ConcatEnumerableObservable(sources) {
this.sources = sources;
__super__.call(this);
}
ConcatEnumerableObservable.prototype.subscribeCore = function (o) {
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) {
if (isDisposed) { return; }
var currentItem = tryCatch(e.next).call(e);
if (currentItem === errorObj) { return o.onError(currentItem.e); }
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
};
function InnerObserver(o, s, e) {
this.o = o;
this.s = s;
this.e = e;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } };
InnerObserver.prototype.onError = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.s(this.e);
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; };
InnerObserver.prototype.fail = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
return true;
}
return false;
};
return ConcatEnumerableObservable;
}(ObservableBase));
Enumerable.prototype.concat = function () {
return new ConcatEnumerableObservable(this);
};
var CatchErrorObservable = (function(__super__) {
inherits(CatchErrorObservable, __super__);
function CatchErrorObservable(sources) {
this.sources = sources;
__super__.call(this);
}
CatchErrorObservable.prototype.subscribeCore = function (o) {
var e = this.sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
var currentItem = tryCatch(e.next).call(e);
if (currentItem === errorObj) { return o.onError(currentItem.e); }
if (currentItem.done) {
return lastException !== null ? o.onError(lastException) : o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
};
return CatchErrorObservable;
}(ObservableBase));
Enumerable.prototype.catchError = function () {
return new CatchErrorObservable(this);
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem = tryCatch(e.next).call(e);
if (currentItem === errorObj) { return o.onError(currentItem.e); }
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var RepeatEnumerable = (function (__super__) {
inherits(RepeatEnumerable, __super__);
function RepeatEnumerable(v, c) {
this.v = v;
this.c = c == null ? -1 : c;
}
RepeatEnumerable.prototype[$iterator$] = function () {
return new RepeatEnumerator(this);
};
function RepeatEnumerator(p) {
this.v = p.v;
this.l = p.c;
}
RepeatEnumerator.prototype.next = function () {
if (this.l === 0) { return doneEnumerator; }
if (this.l > 0) { this.l--; }
return { done: false, value: this.v };
};
return RepeatEnumerable;
}(Enumerable));
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
return new RepeatEnumerable(value, repeatCount);
};
var OfEnumerable = (function(__super__) {
inherits(OfEnumerable, __super__);
function OfEnumerable(s, fn, thisArg) {
this.s = s;
this.fn = fn ? bindCallback(fn, thisArg, 3) : null;
}
OfEnumerable.prototype[$iterator$] = function () {
return new OfEnumerator(this);
};
function OfEnumerator(p) {
this.i = -1;
this.s = p.s;
this.l = this.s.length;
this.fn = p.fn;
}
OfEnumerator.prototype.next = function () {
return ++this.i < this.l ?
{ done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :
doneEnumerator;
};
return OfEnumerable;
}(Enumerable));
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
return new OfEnumerable(source, selector, thisArg);
};
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
}, source);
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
}, source);
};
var FromPromiseObservable = (function(__super__) {
inherits(FromPromiseObservable, __super__);
function FromPromiseObservable(p) {
this.p = p;
__super__.call(this);
}
FromPromiseObservable.prototype.subscribeCore = function(o) {
this.p.then(function (data) {
o.onNext(data);
o.onCompleted();
}, function (err) { o.onError(err); });
return disposableEmpty;
};
return FromPromiseObservable;
}(ObservableBase));
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new FromPromiseObservable(promise);
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
var ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o));
};
function InnerObserver(o) {
this.o = o;
this.a = [];
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.o.onNext(this.a);
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; }
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return ToArrayObservable;
}(ObservableBase));
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
var EmptyObservable = (function(__super__) {
inherits(EmptyObservable, __super__);
function EmptyObservable(scheduler) {
this.scheduler = scheduler;
__super__.call(this);
}
EmptyObservable.prototype.subscribeCore = function (observer) {
var sink = new EmptySink(observer, this);
return sink.run();
};
function EmptySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
function scheduleItem(s, state) {
state.onCompleted();
}
EmptySink.prototype.run = function () {
return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem);
};
return EmptyObservable;
}(ObservableBase));
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new EmptyObservable(scheduler);
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, mapper, scheduler) {
this.iterable = iterable;
this.mapper = mapper;
this.scheduler = scheduler;
__super__.call(this);
}
FromObservable.prototype.subscribeCore = function (observer) {
var sink = new FromSink(observer, this);
return sink.run();
};
return FromObservable;
}(ObservableBase));
var FromSink = (function () {
function FromSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromSink.prototype.run = function () {
var list = Object(this.parent.iterable),
it = getIterable(list),
observer = this.observer,
mapper = this.parent.mapper;
function loopRecursive(i, recurse) {
try {
var next = it.next();
} catch (e) {
return observer.onError(e);
}
if (next.done) {
return observer.onCompleted();
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
return observer.onError(e);
}
}
observer.onNext(result);
recurse(i + 1);
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return FromSink;
}());
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromArraySink.prototype.run = function () {
var observer = this.observer, args = this.parent.args, len = args.length;
function loopRecursive(i, recurse) {
if (i < len) {
observer.onNext(args[i]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (o) {
var first = true;
return scheduler.scheduleRecursiveWithState(initialState, function (state, self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
hasResult && (result = resultSelector(state));
} catch (e) {
return o.onError(e);
}
if (hasResult) {
o.onNext(result);
self(state);
} else {
o.onCompleted();
}
});
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
/**
* Creates an Observable sequence from changes to an array using Array.observe.
* @param {Array} array An array to observe changes.
* @returns {Observable} An observable sequence containing changes to an array from Array.observe.
*/
Observable.ofArrayChanges = function(array) {
if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); }
if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') }
return new AnonymousObservable(function(observer) {
function observerFn(changes) {
for(var i = 0, len = changes.length; i < len; i++) {
observer.onNext(changes[i]);
}
}
Array.observe(array, observerFn);
return function () {
Array.unobserve(array, observerFn);
};
});
};
/**
* Creates an Observable sequence from changes to an object using Object.observe.
* @param {Object} obj An object to observe changes.
* @returns {Observable} An observable sequence containing changes to an object from Object.observe.
*/
Observable.ofObjectChanges = function(obj) {
if (obj == null) { throw new TypeError('object must not be null or undefined.'); }
if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Object.observe is not supported on your platform') }
return new AnonymousObservable(function(observer) {
function observerFn(changes) {
for(var i = 0, len = changes.length; i < len; i++) {
observer.onNext(changes[i]);
}
}
Object.observe(obj, observerFn);
return function () {
Object.unobserve(obj, observerFn);
};
});
};
var NeverObservable = (function(__super__) {
inherits(NeverObservable, __super__);
function NeverObservable() {
__super__.call(this);
}
NeverObservable.prototype.subscribeCore = function (observer) {
return disposableEmpty;
};
return NeverObservable;
}(ObservableBase));
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new NeverObservable();
};
var PairsObservable = (function(__super__) {
inherits(PairsObservable, __super__);
function PairsObservable(obj, scheduler) {
this.obj = obj;
this.keys = Object.keys(obj);
this.scheduler = scheduler;
__super__.call(this);
}
PairsObservable.prototype.subscribeCore = function (observer) {
var sink = new PairsSink(observer, this);
return sink.run();
};
return PairsObservable;
}(ObservableBase));
function PairsSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
PairsSink.prototype.run = function () {
var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length;
function loopRecursive(i, recurse) {
if (i < len) {
var key = keys[i];
observer.onNext([key, obj[key]]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new PairsObservable(obj, scheduler);
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.rangeCount = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.rangeCount, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
var RepeatObservable = (function(__super__) {
inherits(RepeatObservable, __super__);
function RepeatObservable(value, repeatCount, scheduler) {
this.value = value;
this.repeatCount = repeatCount == null ? -1 : repeatCount;
this.scheduler = scheduler;
__super__.call(this);
}
RepeatObservable.prototype.subscribeCore = function (observer) {
var sink = new RepeatSink(observer, this);
return sink.run();
};
return RepeatObservable;
}(ObservableBase));
function RepeatSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RepeatSink.prototype.run = function () {
var observer = this.observer, value = this.parent.value;
function loopRecursive(i, recurse) {
if (i === -1 || i > 0) {
observer.onNext(value);
i > 0 && i--;
}
if (i === 0) { return observer.onCompleted(); }
recurse(i);
}
return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RepeatObservable(value, repeatCount, scheduler);
};
var JustObservable = (function(__super__) {
inherits(JustObservable, __super__);
function JustObservable(value, scheduler) {
this.value = value;
this.scheduler = scheduler;
__super__.call(this);
}
JustObservable.prototype.subscribeCore = function (observer) {
var sink = new JustSink(observer, this);
return sink.run();
};
function JustSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
function scheduleItem(s, state) {
var value = state[0], observer = state[1];
observer.onNext(value);
observer.onCompleted();
}
JustSink.prototype.run = function () {
return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem);
};
return JustObservable;
}(ObservableBase));
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just' or browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new JustObservable(value, scheduler);
};
var ThrowObservable = (function(__super__) {
inherits(ThrowObservable, __super__);
function ThrowObservable(error, scheduler) {
this.error = error;
this.scheduler = scheduler;
__super__.call(this);
}
ThrowObservable.prototype.subscribeCore = function (o) {
var sink = new ThrowSink(o, this);
return sink.run();
};
function ThrowSink(o, p) {
this.o = o;
this.p = p;
}
function scheduleItem(s, state) {
var e = state[0], o = state[1];
o.onError(e);
}
ThrowSink.prototype.run = function () {
return this.p.scheduler.scheduleWithState([this.p.error, this.o], scheduleItem);
};
return ThrowObservable;
}(ObservableBase));
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = Observable.throwException = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new ThrowObservable(error, scheduler);
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
choice === leftChoice && observer.onNext(left);
}, function (err) {
choiceL();
choice === leftChoice && observer.onError(err);
}, function () {
choiceL();
choice === leftChoice && observer.onCompleted();
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
choice === rightChoice && observer.onNext(right);
}, function (err) {
choiceR();
choice === rightChoice && observer.onError(err);
}, function () {
choiceR();
choice === rightChoice && observer.onCompleted();
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) {
try {
var result = handler(e);
} catch (ex) {
return o.onError(ex);
}
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(o));
}, function (x) { o.onCompleted(x); }));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop();
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (o) {
var n = args.length,
falseFactory = function () { return false; },
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
var res = resultSelector.apply(null, values);
} catch (e) {
return o.onError(e);
}
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}
function done (i) {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { o.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
var ConcatObservable = (function(__super__) {
inherits(ConcatObservable, __super__);
function ConcatObservable(sources) {
this.sources = sources;
__super__.call(this);
}
ConcatObservable.prototype.subscribeCore = function(o) {
var sink = new ConcatSink(this.sources, o);
return sink.run();
};
function ConcatSink(sources, o) {
this.sources = sources;
this.o = o;
}
ConcatSink.prototype.run = function () {
var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o;
var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) {
if (isDisposed) { return; }
if (i === length) {
return o.onCompleted();
}
// Check if promise
var currentValue = sources[i];
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function (x) { o.onNext(x); },
function (e) { o.onError(e); },
function () { self(i + 1); }
));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
};
return ConcatObservable;
}(ObservableBase));
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return new ConcatObservable(args);
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = observableProto.concatObservable = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function () {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
this.isStopped = false;
}
MergeObserver.prototype.handleSubscribe = function (xs) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(xs) && (xs = observableFromPromise(xs));
sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
};
MergeObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.done = true;
this.activeCount === 0 && this.o.onCompleted();
}
};
MergeObserver.prototype.dispose = function() { this.isStopped = true; };
MergeObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
var parent = this.parent;
parent.g.remove(this.sad);
if (parent.q.length > 0) {
parent.handleSubscribe(parent.q.shift());
} else {
parent.activeCount--;
parent.done && parent.activeCount === 0 && parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
return typeof maxConcurrentOrOther !== 'number' ?
observableMerge(this, maxConcurrentOrOther) :
new MergeObservable(this, maxConcurrentOrOther);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
var MergeAllObservable = (function (__super__) {
inherits(MergeAllObservable, __super__);
function MergeAllObservable(source) {
this.source = source;
__super__.call(this);
}
MergeAllObservable.prototype.subscribeCore = function (observer) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
return g;
};
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.isStopped = false;
this.done = false;
}
MergeAllObserver.prototype.onNext = function(innerSource) {
if(this.isStopped) { return; }
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad)));
};
MergeAllObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeAllObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.done = true;
this.g.length === 1 && this.o.onCompleted();
}
};
MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
MergeAllObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, g, sad) {
this.parent = parent;
this.g = g;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
this.isStopped = true;
parent.g.remove(this.sad);
parent.done && parent.g.length === 1 && parent.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeAllObservable;
}(ObservableBase));
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = observableProto.mergeObservable = function () {
return new MergeAllObservable(this);
};
var CompositeError = Rx.CompositeError = function(errors) {
this.name = "NotImplementedError";
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
}
CompositeError.prototype = Error.prototype;
/**
* Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
* receive all successfully emitted items from all of the source Observables without being interrupted by
* an error notification from one of them.
*
* This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
* error via the Observer's onError, mergeDelayError will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* @param {Array | Arguments} args Arguments or an array to merge.
* @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
*/
Observable.mergeDelayError = function() {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
var len = arguments.length;
args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
var source = observableOf(null, args);
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
isStopped = false,
errors = [];
function setCompletion() {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
group.add(m);
m.setDisposable(source.subscribe(
function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) { o.onNext(x); },
function (e) {
errors.push(e);
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
},
function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
}));
},
function (e) {
errors.push(e);
isStopped = true;
group.length === 1 && setCompletion();
},
function () {
isStopped = true;
group.length === 1 && setCompletion();
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
var SwitchObservable = (function(__super__) {
inherits(SwitchObservable, __super__);
function SwitchObservable(source) {
this.source = source;
__super__.call(this);
}
SwitchObservable.prototype.subscribeCore = function (o) {
var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));
return new CompositeDisposable(s, inner);
};
function SwitchObserver(o, inner) {
this.o = o;
this.inner = inner;
this.stopped = false;
this.latest = 0;
this.hasLatest = false;
this.isStopped = false;
}
SwitchObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
var d = new SingleAssignmentDisposable(), id = ++this.latest;
this.hasLatest = true;
this.inner.setDisposable(d);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));
};
SwitchObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
SwitchObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.stopped = true;
!this.hasLatest && this.o.onCompleted();
}
};
SwitchObserver.prototype.dispose = function () { this.isStopped = true; };
SwitchObserver.prototype.fail = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, id) {
this.parent = parent;
this.id = id;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
this.parent.latest === this.id && this.parent.o.onNext(x);
};
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.latest === this.id && this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
if (this.parent.latest === this.id) {
this.parent.hasLatest = false;
this.parent.isStopped && this.parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; }
InnerObserver.prototype.fail = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return SwitchObservable;
}(ObservableBase));
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
return new SwitchObservable(this);
};
var TakeUntilObservable = (function(__super__) {
inherits(TakeUntilObservable, __super__);
function TakeUntilObservable(source, other) {
this.source = source;
this.other = isPromise(other) ? observableFromPromise(other) : other;
__super__.call(this);
}
TakeUntilObservable.prototype.subscribeCore = function(o) {
return new CompositeDisposable(
this.source.subscribe(o),
this.other.subscribe(new InnerObserver(o))
);
};
function InnerObserver(o) {
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
this.o.onCompleted();
};
InnerObserver.prototype.onError = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
!this.isStopped && (this.isStopped = true);
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return TakeUntilObservable;
}(ObservableBase));
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
return new TakeUntilObservable(this, other);
};
function falseFactory() { return false; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop(), source = this;
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (observer) {
var n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, function (e) { observer.onError(e); }, noop));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var allValues = [x].concat(values);
if (!hasValueAll) { return; }
var res = tryCatch(resultSelector).apply(null, allValues);
if (res === errorObj) { return observer.onError(res.e); }
observer.onNext(res);
}, function (e) { observer.onError(e); }, function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (o) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], res = tryCatch(resultSelector)(left, right);
if (res === errorObj) { return o.onError(res.e); }
o.onNext(res);
} else {
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, first);
}
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var parent = this, resultSelector = args.pop();
args.unshift(parent);
return new AnonymousObservable(function (o) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
if (queues.every(function (x) { return x.length > 0; })) {
var queuedValues = queues.map(function (x) { return x.shift(); }),
res = tryCatch(resultSelector).apply(parent, queuedValues);
if (res === errorObj) { return o.onError(res.e); }
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var first = args.shift();
return first.zip.apply(first, args);
};
function falseFactory() { return false; }
function arrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources;
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
var len = arguments.length;
sources = new Array(len);
for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
}
return new AnonymousObservable(function (o) {
var n = sources.length,
queues = arrayInitialize(n, arrayFactory),
isDone = arrayInitialize(n, falseFactory);
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
return o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (o) { return source.subscribe(o); }, source);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var key = value;
if (keySelector) {
key = tryCatch(keySelector)(value);
if (key === errorObj) { return o.onError(key.e); }
}
if (hasCurrentKey) {
var comparerEquals = tryCatch(comparer)(currentKey, key);
if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); }
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
var TapObservable = (function(__super__) {
inherits(TapObservable,__super__);
function TapObservable(source, observerOrOnNext, onError, onCompleted) {
this.source = source;
this.t = !observerOrOnNext || isFunction(observerOrOnNext) ?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
__super__.call(this);
}
TapObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o, this.t));
};
function InnerObserver(o, t) {
this.o = o;
this.t = t;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var res = tryCatch(this.t.onNext).call(this.t, x);
if (res === errorObj) { this.o.onError(res.e); }
this.o.onNext(x);
};
InnerObserver.prototype.onError = function(err) {
if (!this.isStopped) {
this.isStopped = true;
var res = tryCatch(this.t.onError).call(this.t, err);
if (res === errorObj) { return this.o.onError(res.e); }
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function() {
if (!this.isStopped) {
this.isStopped = true;
var res = tryCatch(this.t.onCompleted).call(this.t);
if (res === errorObj) { return this.o.onError(res.e); }
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return TapObservable;
}(ObservableBase));
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
return new TapObservable(this, observerOrOnNext, onError, onCompleted);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
var IgnoreElementsObservable = (function(__super__) {
inherits(IgnoreElementsObservable, __super__);
function IgnoreElementsObservable(source) {
this.source = source;
__super__.call(this);
}
IgnoreElementsObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o));
};
function InnerObserver(o) {
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = noop;
InnerObserver.prototype.onError = function (err) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
return IgnoreElementsObservable;
}(ObservableBase));
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
return new IgnoreElementsObservable(this);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
var ScanObservable = (function(__super__) {
inherits(ScanObservable, __super__);
function ScanObservable(source, accumulator, hasSeed, seed) {
this.source = source;
this.accumulator = accumulator;
this.hasSeed = hasSeed;
this.seed = seed;
__super__.call(this);
}
ScanObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new ScanObserver(observer,this));
};
return ScanObservable;
}(ObservableBase));
function ScanObserver(observer, parent) {
this.observer = observer;
this.accumulator = parent.accumulator;
this.hasSeed = parent.hasSeed;
this.seed = parent.seed;
this.hasAccumulation = false;
this.accumulation = null;
this.hasValue = false;
this.isStopped = false;
}
ScanObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
!this.hasValue && (this.hasValue = true);
try {
if (this.hasAccumulation) {
this.accumulation = this.accumulator(this.accumulation, x);
} else {
this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x;
this.hasAccumulation = true;
}
} catch (e) {
return this.observer.onError(e);
}
this.observer.onNext(this.accumulation);
};
ScanObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
}
};
ScanObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
!this.hasValue && this.hasSeed && this.observer.onNext(this.seed);
this.observer.onCompleted();
}
};
ScanObserver.prototype.dispose = function() { this.isStopped = true; };
ScanObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new ScanObservable(this, accumulator, hasSeed, seed);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
o.onNext(q);
o.onCompleted();
});
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new ArgumentOutOfRangeError(); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
function concatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this,
onNextFunc = bindCallback(onNext, thisArg, 2),
onErrorFunc = bindCallback(onError, thisArg, 1),
onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNextFunc(x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onErrorFunc(err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompletedFunc();
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
},
function (e) { observer.onError(e); },
function () {
!found && observer.onNext(defaultValue);
observer.onCompleted();
});
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
}
hashSet.push(key) && o.onNext(x);
},
function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [comparer] Used to determine whether the objects are equal.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, comparer) {
return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) {
var source = this;
elementSelector || (elementSelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
function handleError(e) { return function (item) { item.onError(e); }; }
var map = new Dictionary(0, comparer),
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
var fireNewMapEntry = false,
writer = map.tryGetValue(key);
if (!writer) {
writer = new Subject();
map.set(key, writer);
fireNewMapEntry = true;
}
if (fireNewMapEntry) {
var group = new GroupedObservable(key, writer, refCountDisposable),
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(group);
var md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
map.remove(key) && writer.onCompleted();
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(
noop,
function (exn) {
map.getValues().forEach(handleError(exn));
observer.onError(exn);
},
expire)
);
}
var element;
try {
element = elementSelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
map.getValues().forEach(handleError(ex));
observer.onError(ex);
}, function () {
map.getValues().forEach(function (item) { item.onCompleted(); });
observer.onCompleted();
}));
return refCountDisposable;
}, source);
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
function innerMap(selector, self) {
return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
return new MapObservable(this.source, innerMap(selector, this), thisArg);
};
MapObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.selector, this));
};
function InnerObserver(o, selector, source) {
this.o = o;
this.selector = selector;
this.source = source;
this.i = 0;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var result = tryCatch(this.selector)(x, this.i++, this.source);
if (result === errorObj) {
return this.o.onError(result.e);
}
this.o.onNext(result);
};
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return MapObservable;
}(ObservableBase));
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var args = arguments, len = arguments.length;
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
return this.map(function (x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
});
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, source).mergeAll();
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
var SkipObservable = (function(__super__) {
inherits(SkipObservable, __super__);
function SkipObservable(source, count) {
this.source = source;
this.skipCount = count;
__super__.call(this);
}
SkipObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.skipCount));
};
function InnerObserver(o, c) {
this.c = c;
this.r = c;
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
if (this.r <= 0) {
this.o.onNext(x);
} else {
this.r--;
}
};
InnerObserver.prototype.onError = function(e) {
if (!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function() {
if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function(e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return SkipObservable;
}(ObservableBase));
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
return new SkipObservable(this, count);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining <= 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.predicate, this));
};
function innerPredicate(predicate, self) {
return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }
}
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg);
};
function InnerObserver(o, predicate, source) {
this.o = o;
this.predicate = predicate;
this.source = source;
this.i = 0;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.o.onError(shouldYield.e);
}
shouldYield && this.o.onNext(x);
};
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return FilterObservable;
}(ObservableBase));
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (o) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
o.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
o.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) { list.push(x); }
}, function (e) { o.onError(e); }, function () {
o.onNext(list);
o.onCompleted();
});
}, source);
}
function firstOnly(x) {
if (x.length === 0) { throw new EmptyError(); }
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @deprecated Use #reduce instead
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var hasSeed = false, accumulator, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
return o.onError(e);
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new EmptyError());
o.onCompleted();
}
);
}, source);
};
var ReduceObservable = (function(__super__) {
inherits(ReduceObservable, __super__);
function ReduceObservable(source, acc, hasSeed, seed) {
this.source = source;
this.acc = acc;
this.hasSeed = hasSeed;
this.seed = seed;
__super__.call(this);
}
ReduceObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new InnerObserver(observer,this));
};
function InnerObserver(o, parent) {
this.o = o;
this.acc = parent.acc;
this.hasSeed = parent.hasSeed;
this.seed = parent.seed;
this.hasAccumulation = false;
this.result = null;
this.hasValue = false;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
!this.hasValue && (this.hasValue = true);
if (this.hasAccumulation) {
this.result = tryCatch(this.acc)(this.result, x);
} else {
this.result = this.hasSeed ? tryCatch(this.acc)(this.seed, x) : x;
this.hasAccumulation = true;
}
if (this.result === errorObj) { this.o.onError(this.result.e); }
};
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.hasValue && this.o.onNext(this.result);
!this.hasValue && this.hasSeed && this.o.onNext(this.seed);
!this.hasValue && !this.hasSeed && this.o.onError(new EmptyError());
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; };
InnerObserver.prototype.fail = function(e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return ReduceObservable;
}(ObservableBase));
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var hasSeed = false;
if (arguments.length === 2) {
hasSeed = true;
var seed = arguments[1];
}
return new ReduceObservable(this, accumulator, hasSeed, seed);
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = function (predicate, thisArg) {
var source = this;
return predicate ?
source.filter(predicate, thisArg).some() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, function (e) { observer.onError(e); }, function () {
observer.onNext(false);
observer.onCompleted();
});
}, source);
};
/** @deprecated use #some instead */
observableProto.any = function () {
//deprecate('any', 'some');
return this.some.apply(this, arguments);
};
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().map(not);
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = function (predicate, thisArg) {
return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not);
};
/** @deprecated use #every instead */
observableProto.all = function () {
//deprecate('all', 'every');
return this.every.apply(this, arguments);
};
/**
* Determines whether an observable sequence includes a specified element with an optional equality comparer.
* @param searchElement The value to locate in the source sequence.
* @param {Number} [fromIndex] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
*/
observableProto.includes = function (searchElement, fromIndex) {
var source = this;
function comparer(a, b) {
return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
}
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(false);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i++ >= n && comparer(x, searchElement)) {
o.onNext(true);
o.onCompleted();
}
},
function (e) { o.onError(e); },
function () {
o.onNext(false);
o.onCompleted();
});
}, this);
};
/**
* @deprecated use #includes instead.
*/
observableProto.contains = function (searchElement, fromIndex) {
//deprecate('contains', 'includes');
observableProto.includes(searchElement, fromIndex);
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.filter(predicate, thisArg).count() :
this.reduce(function (count) { return count + 1; }, 0);
};
/**
* Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
* @param {Any} searchElement Element to locate in the array.
* @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
* @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
*/
observableProto.indexOf = function(searchElement, fromIndex) {
var source = this;
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(-1);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i >= n && x === searchElement) {
o.onNext(i);
o.onCompleted();
}
i++;
},
function (e) { o.onError(e); },
function () {
o.onNext(-1);
o.onCompleted();
});
}, source);
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).sum() :
this.reduce(function (prev, curr) { return prev + curr; }, 0);
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).average() :
this.reduce(function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}, {sum: 0, count: 0 }).map(function (s) {
if (s.count === 0) { throw new EmptyError(); }
return s.sum / s.count;
});
};
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
o.onError(e);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (doner) {
o.onNext(false);
o.onCompleted();
} else {
ql.push(x);
}
}, function(e) { o.onError(e); }, function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (doner) {
o.onNext(true);
o.onCompleted();
}
}
});
(isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal;
if (ql.length > 0) {
var v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
o.onError(exception);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (donel) {
o.onNext(false);
o.onCompleted();
} else {
qr.push(x);
}
}, function(e) { o.onError(e); }, function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (donel) {
o.onNext(true);
o.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
}, first);
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (o) {
var i = index;
return source.subscribe(function (x) {
if (i-- === 0) {
o.onNext(x);
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new ArgumentOutOfRangeError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
o.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate && isFunction(predicate) ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate && isFunction(predicate) ?
this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue);
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) {
o.onNext(x);
o.onCompleted();
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
var callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = callback(x, i, source);
} catch (e) {
o.onError(e);
return;
}
if (shouldRun) {
o.onNext(yieldIndex ? i : x);
o.onCompleted();
} else {
i++;
}
}, function (e) { o.onError(e); }, function () {
o.onNext(yieldIndex ? -1 : undefined);
o.onCompleted();
});
}, source);
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Converts the observable sequence to a Set if it exists.
* @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
*/
observableProto.toSet = function () {
if (typeof root.Set === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var s = new root.Set();
return source.subscribe(
function (x) { s.add(x); },
function (e) { o.onError(e); },
function () {
o.onNext(s);
o.onCompleted();
});
}, source);
};
/**
* Converts the observable sequence to a Map if it exists.
* @param {Function} keySelector A function which produces the key for the Map.
* @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
*/
observableProto.toMap = function (keySelector, elementSelector) {
if (typeof root.Map === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var m = new root.Map();
return source.subscribe(
function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
var element = x;
if (elementSelector) {
try {
element = elementSelector(x);
} catch (e) {
o.onError(e);
return;
}
}
m.set(key, element);
},
function (e) { o.onError(e); },
function () {
o.onNext(m);
o.onCompleted();
});
}, source);
};
var fnString = 'function',
throwString = 'throw',
isObject = Rx.internals.isObject;
function toThunk(obj, ctx) {
if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); }
if (isGenerator(obj)) { return observableSpawn(obj); }
if (isObservable(obj)) { return observableToThunk(obj); }
if (isPromise(obj)) { return promiseToThunk(obj); }
if (typeof obj === fnString) { return obj; }
if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
return obj;
}
function objectToThunk(obj) {
var ctx = this;
return function (done) {
var keys = Object.keys(obj),
pending = keys.length,
results = new obj.constructor(),
finished;
if (!pending) {
timeoutScheduler.schedule(function () { done(null, results); });
return;
}
for (var i = 0, len = keys.length; i < len; i++) {
run(obj[keys[i]], keys[i]);
}
function run(fn, key) {
if (finished) { return; }
try {
fn = toThunk(fn, ctx);
if (typeof fn !== fnString) {
results[key] = fn;
return --pending || done(null, results);
}
fn.call(ctx, function(err, res) {
if (finished) { return; }
if (err) {
finished = true;
return done(err);
}
results[key] = res;
--pending || done(null, results);
});
} catch (e) {
finished = true;
done(e);
}
}
}
}
function observableToThunk(observable) {
return function (fn) {
var value, hasValue = false;
observable.subscribe(
function (v) {
value = v;
hasValue = true;
},
fn,
function () {
hasValue && fn(null, value);
});
}
}
function promiseToThunk(promise) {
return function(fn) {
promise.then(function(res) {
fn(null, res);
}, fn);
}
}
function isObservable(obj) {
return obj && typeof obj.subscribe === fnString;
}
function isGeneratorFunction(obj) {
return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
function isGenerator(obj) {
return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString;
}
/*
* Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions.
* @param {Function} The spawning function.
* @returns {Function} a function which has a done continuation.
*/
var observableSpawn = Rx.spawn = function (fn) {
var isGenFun = isGeneratorFunction(fn);
return function (done) {
var ctx = this,
gen = fn;
if (isGenFun) {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
var len = args.length,
hasCallback = len && typeof args[len - 1] === fnString;
done = hasCallback ? args.pop() : handleError;
gen = fn.apply(this, args);
} else {
done = done || handleError;
}
next();
function exit(err, res) {
timeoutScheduler.schedule(done.bind(ctx, err, res));
}
function next(err, res) {
var ret;
// multiple args
if (arguments.length > 2) {
for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); }
}
if (err) {
try {
ret = gen[throwString](err);
} catch (e) {
return exit(e);
}
}
if (!err) {
try {
ret = gen.next(res);
} catch (e) {
return exit(e);
}
}
if (ret.done) {
return exit(null, ret.value);
}
ret.value = toThunk(ret.value, ctx);
if (typeof ret.value === fnString) {
var called = false;
try {
ret.value.call(ctx, function() {
if (called) {
return;
}
called = true;
next.apply(ctx, arguments);
});
} catch (e) {
timeoutScheduler.schedule(function () {
if (called) {
return;
}
called = true;
next.call(ctx, e);
});
}
return;
}
// Not supported
next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.'));
}
}
};
function handleError(err) {
if (!err) { return; }
timeoutScheduler.schedule(function() {
throw err;
});
}
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, context, scheduler) {
return observableToAsync(func, context, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
* @param {Function} function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return function () {
var args = arguments,
subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler() {
var len = arguments.length, results = new Array(len);
for(var i = 0; i < len; i++) { results[i] = arguments[i]; }
if (selector) {
try {
results = selector.apply(context, results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var len = arguments.length, results = [];
for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
if (selector) {
try {
results = selector.apply(context, results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList or HTMLCollection
var toStr = Object.prototype.toString;
if (toStr.call(el) === '[object NodeList]' || toStr.call(el) === '[object HTMLCollection]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette, Ember.js
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) { return o.onError(err); }
var res = tryCatch(resultSelector).apply(null, values);
if (res === errorObj) { return o.onError(res.e); }
o.onNext(res);
}
isDone && values[1] && o.onCompleted();
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(o) {
var q = [], previousShouldFire;
function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } }
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) { drainQueue(); }
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
drainQueue();
o.onError(err);
},
function () {
drainQueue();
o.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue, scheduler) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue, scheduler);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
return this.subject.request(numberOfItems == null ? -1 : numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue, scheduler) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.scheduler = scheduler || currentThreadScheduler;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
} else {
this.queue.push(Notification.createOnCompleted());
}
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
} else {
this.queue.push(Notification.createOnError(error));
}
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(Notification.createOnNext(value));
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while ((this.queue.length >= numberOfItems && numberOfItems > 0) ||
(this.queue.length > 0 && this.queue[0].kind !== 'N')) {
var first = this.queue.shift();
first.accept(this.subject);
if (first.kind === 'N') {
numberOfItems--;
} else {
this.disposeCurrentRequest();
this.queue = [];
}
}
return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0};
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this;
this.requestedDisposable = this.scheduler.scheduleWithState(number,
function(s, i) {
var r = self._processRequest(i), remaining = r.numberOfItems;
if (!r.returnValue) {
self.requestedCount = remaining;
self.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
}
});
return this.requestedDisposable;
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {bool} enableQueue truthy value to determine if values should be queued pending the next request
* @param {Scheduler} scheduler determines how the requests will be scheduled
* @returns {Observable} The observable sequence which only propagates values on request.
*/
observableProto.controlled = function (enableQueue, scheduler) {
if (enableQueue && isScheduler(enableQueue)) {
scheduler = enableQueue;
enableQueue = true;
}
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue, scheduler);
};
var StopAndWaitObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () { self.source.request(1); });
return this.subscription;
}
inherits(StopAndWaitObservable, __super__);
function StopAndWaitObservable (source) {
__super__.call(this, subscribe, source);
this.source = source;
}
var StopAndWaitObserver = (function (__sub__) {
inherits(StopAndWaitObserver, __sub__);
function StopAndWaitObserver (observer, observable, cancel) {
__sub__.call(this);
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
}
var stopAndWaitObserverProto = StopAndWaitObserver.prototype;
stopAndWaitObserverProto.completed = function () {
this.observer.onCompleted();
this.dispose();
};
stopAndWaitObserverProto.error = function (error) {
this.observer.onError(error);
this.dispose();
}
stopAndWaitObserverProto.next = function (value) {
this.observer.onNext(value);
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(1);
});
};
stopAndWaitObserverProto.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return StopAndWaitObserver;
}(AbstractObserver));
return StopAndWaitObservable;
}(Observable));
/**
* Attaches a stop and wait observable to the current observable.
* @returns {Observable} A stop and wait observable.
*/
ControlledObservable.prototype.stopAndWait = function () {
return new StopAndWaitObservable(this);
};
var WindowedObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () {
self.source.request(self.windowSize);
});
return this.subscription;
}
inherits(WindowedObservable, __super__);
function WindowedObservable(source, windowSize) {
__super__.call(this, subscribe, source);
this.source = source;
this.windowSize = windowSize;
}
var WindowedObserver = (function (__sub__) {
inherits(WindowedObserver, __sub__);
function WindowedObserver(observer, observable, cancel) {
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
this.received = 0;
}
var windowedObserverPrototype = WindowedObserver.prototype;
windowedObserverPrototype.completed = function () {
this.observer.onCompleted();
this.dispose();
};
windowedObserverPrototype.error = function (error) {
this.observer.onError(error);
this.dispose();
};
windowedObserverPrototype.next = function (value) {
this.observer.onNext(value);
this.received = ++this.received % this.observable.windowSize;
if (this.received === 0) {
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(self.observable.windowSize);
});
}
};
windowedObserverPrototype.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return WindowedObserver;
}(AbstractObserver));
return WindowedObservable;
}(Observable));
/**
* Creates a sliding windowed observable based upon the window size.
* @param {Number} windowSize The number of items in the window
* @returns {Observable} A windowed observable based upon the window size.
*/
ControlledObservable.prototype.windowed = function (windowSize) {
return new WindowedObservable(this, windowSize);
};
/**
* Pipes the existing Observable sequence into a Node.js Stream.
* @param {Stream} dest The destination Node.js stream.
* @returns {Stream} The destination stream.
*/
observableProto.pipe = function (dest) {
var source = this.pausableBuffered();
function onDrain() {
source.resume();
}
dest.addListener('drain', onDrain);
source.subscribe(
function (x) {
!dest.write(String(x)) && source.pause();
},
function (err) {
dest.emit('error', err);
},
function () {
// Hack check because STDIO is not closable
!dest._isStdio && dest.end();
dest.removeListener('drain', onDrain);
});
source.resume();
return dest;
};
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param windowSize [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
return this.replay(null, bufferSize, windowSize, scheduler).refCount();
};
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Gets the current value or throws an exception.
* Value is frozen after onCompleted is called.
* After onError is called always throws the specified exception.
* An exception is always thrown after dispose is called.
* @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
*/
getValue: function () {
checkDisposed(this);
if (this.hasError) {
throw this.error;
}
return this.value;
},
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
var maxSafeInteger = Math.pow(2, 53) - 1;
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence
* can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`)
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source.
*/
observableProto.singleInstance = function() {
var source = this, hasObservable = false, observable;
function getObservable() {
if (!hasObservable) {
hasObservable = true;
observable = source.finally(function() { hasObservable = false; }).publish().refCount();
}
return observable;
};
return new AnonymousObservable(function(o) {
return getObservable().subscribe(o);
});
};
var Dictionary = (function () {
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647],
noSuchkey = "no such key",
duplicatekey = "duplicate key";
function isPrime(candidate) {
if ((candidate & 1) === 0) { return candidate === 2; }
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) { return false; }
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) { return num; }
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) { return candidate; }
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) { return hash; }
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash << 5) - hash) + character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) { throw new Error(noSuchkey); }
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') { return stringHashFn(obj); }
if (typeof obj === 'number') { return numberHashFn(obj); }
if (typeof obj === 'boolean') { return obj === true ? 1 : 0; }
if (obj instanceof Date) { return numberHashFn(obj.valueOf()); }
if (obj instanceof RegExp) { return stringHashFn(obj.toString()); }
if (typeof obj.valueOf === 'function') {
// Hack check for valueOf
var valueOf = obj.valueOf();
if (typeof valueOf === 'number') { return numberHashFn(valueOf); }
if (typeof valueOf === 'string') { return stringHashFn(valueOf); }
}
if (obj.hashCode) { return obj.hashCode(); }
var id = 17 * uniqueIdCounter++;
obj.hashCode = function () { return id; };
return id;
};
}());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
function Dictionary(capacity, comparer) {
if (capacity < 0) { throw new ArgumentOutOfRangeError(); }
if (capacity > 0) { this._initialize(capacity); }
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
}
var dictionaryProto = Dictionary.prototype;
dictionaryProto._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
dictionaryProto.add = function (key, value) {
this._insert(key, value, true);
};
dictionaryProto._insert = function (key, value, add) {
if (!this.buckets) { this._initialize(0); }
var index3,
num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) { throw new Error(duplicatekey); }
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
dictionaryProto._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; }
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; }
for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); }
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
dictionaryProto.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length,
index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
dictionaryProto.clear = function () {
var index, len;
if (this.size <= 0) { return; }
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
dictionaryProto._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
dictionaryProto.count = function () {
return this.size - this.freeCount;
};
dictionaryProto.tryGetValue = function (key) {
var entry = this._findEntry(key);
return entry >= 0 ?
this.entries[entry].value :
undefined;
};
dictionaryProto.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
dictionaryProto.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) { return this.entries[entry].value; }
throw new Error(noSuchkey);
};
dictionaryProto.set = function (key, value) {
this._insert(key, value, false);
};
dictionaryProto.containskey = function (key) {
return this._findEntry(key) >= 0;
};
return Dictionary;
}());
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var leftDone = false, rightDone = false;
var leftId = 0, rightId = 0;
var leftMap = new Dictionary(), rightMap = new Dictionary();
group.add(left.subscribe(
function (value) {
var id = leftId++;
var md = new SingleAssignmentDisposable();
leftMap.add(id, value);
group.add(md);
var expire = function () {
leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
rightMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(value, v);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
leftDone = true;
(rightDone || leftMap.count() === 0) && observer.onCompleted();
})
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
var md = new SingleAssignmentDisposable();
rightMap.add(id, value);
group.add(md);
var expire = function () {
rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
leftMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(v, value);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
rightDone = true;
(leftDone || rightMap.count() === 0) && observer.onCompleted();
})
);
return group;
}, left);
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary(), rightMap = new Dictionary();
var leftId = 0, rightId = 0;
function handleError(e) { return function (v) { v.onError(e); }; };
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftId++;
leftMap.add(id, s);
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(result);
rightMap.getValues().forEach(function (v) { s.onNext(v); });
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
leftMap.remove(id) && s.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
observer.onCompleted.bind(observer))
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
leftMap.getValues().forEach(function (v) { v.onNext(value); });
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
})
);
return r;
}, left);
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) {
return win;
});
}
function observableWindowWithBoundaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var win = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
d.add(windowBoundaries.subscribe(function (w) {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
return r;
}, source);
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
win = new Subject();
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
function createWindowClose () {
var windowClose;
try {
windowClose = windowClosingSelector();
} catch (e) {
observer.onError(e);
return;
}
isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
var m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
createWindowClose();
}));
}
createWindowClose();
return r;
}, source);
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
}, source);
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
return [
this.filter(predicate, thisArg),
this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
var WhileEnumerable = (function(__super__) {
inherits(WhileEnumerable, __super__);
function WhileEnumerable(c, s) {
this.c = c;
this.s = s;
}
WhileEnumerable.prototype[$iterator$] = function () {
var self = this;
return {
next: function () {
return self.c() ?
{ done: false, value: self.s } :
{ done: true, value: void 0 };
}
};
};
return WhileEnumerable;
}(Enumerable));
function enumerableWhile(condition, source) {
return new WhileEnumerable(condition, source);
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) {
return enumerableOf(sources, resultSelector, thisArg).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
}, this);
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = [];
if (Array.isArray(arguments[0])) {
allSources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); }
}
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
}, first);
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = observableProto.extend = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.map(function (x) {
var curr = new ChainObservable(x);
chain && chain.onNext(x);
chain = curr;
return curr;
})
.tap(
noop,
function (e) { chain && chain.onError(e); },
function () { chain && chain.onCompleted(); }
)
.observeOn(scheduler)
.map(selector);
}, source);
};
var ChainObservable = (function (__super__) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeAll().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, __super__);
function ChainObservable(head) {
__super__.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwError(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = root.Map || (function () {
function Map() {
this._keys = [];
this._values = [];
}
Map.prototype.get = function (key) {
var i = this._keys.indexOf(key);
return i !== -1 ? this._values[i] : undefined;
};
Map.prototype.set = function (key, value) {
var i = this._keys.indexOf(key);
i !== -1 && (this._values[i] = value);
this._values[this._keys.push(key) - 1] = value;
};
Map.prototype.forEach = function (callback, thisArg) {
for (var i = 0, len = this._keys.length; i < len; i++) {
callback.call(thisArg, this._values[i], this._keys[i]);
}
};
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
* @param other Observable sequence to match in addition to the current pattern.
* @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
return new Pattern(this.patterns.concat(other));
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
* @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.thenDo = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
function ActivePlan(joinObserverArray, onNext, onCompleted) {
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
var joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
this.joinObservers.forEach(function (v) { v.queue.shift(); });
};
ActivePlan.prototype.match = function () {
var i, len, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
var firstValues = [],
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
var values = [];
for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
var JoinObserver = (function (__super__) {
inherits(JoinObserver, __super__);
function JoinObserver(source, onError) {
__super__.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
return this.onError(notification.exception);
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
JoinObserverPrototype.error = noop;
JoinObserverPrototype.completed = noop;
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
JoinObserverPrototype.removeActivePlan = function (activePlan) {
this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
this.activePlans.length === 0 && this.dispose();
};
JoinObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param {Function} selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.thenDo = function (selector) {
return new Pattern([this]).thenDo(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var len = arguments.length, plans;
if (Array.isArray(arguments[0])) {
plans = arguments[0];
} else {
plans = new Array(len);
for(var i = 0; i < len; i++) { plans[i] = arguments[i]; }
}
return new AnonymousObservable(function (o) {
var activePlans = [],
externalSubscriptions = new Map();
var outObserver = observerCreate(
function (x) { o.onNext(x); },
function (err) {
externalSubscriptions.forEach(function (v) { v.onError(err); });
o.onError(err);
},
function (x) { o.onCompleted(); }
);
try {
for (var i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
activePlans.length === 0 && o.onCompleted();
}));
}
} catch (e) {
observableThrow(e).subscribe(o);
}
var group = new CompositeDisposable();
externalSubscriptions.forEach(function (joinObserver) {
joinObserver.subscribe();
group.add(joinObserver);
});
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count);
self(count + 1, d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
}, source);
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
* @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasvalue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, this);
};
/**
* @deprecated use #debounce or #throttleWithTimeout instead.
*/
observableProto.throttle = function(dueTime, scheduler) {
//deprecate('throttle', 'debounce or throttleWithTimeout');
return this.debounce(dueTime, scheduler);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
timeShiftOrScheduler == null && (timeShift = timeSpan);
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (isScheduler(timeShiftOrScheduler)) {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
if (isShift) {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
isSpan && q.shift().onCompleted();
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
},
function (e) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
observer.onError(e);
},
function () {
for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var timerD = new SerialDisposable(),
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable),
n = 0,
windowId = 0,
s = new Subject();
function createTimer(id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
if (id !== windowId) { return; }
n = 0;
var newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
}
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(
function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
if (++n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
newWindow && createTimer(newId);
},
function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.map(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return { value: x, interval: span };
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.default);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (o) {
var atEnd = false, value, hasValue = false;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
o.onNext(value);
}
atEnd && o.onCompleted();
}
var sourceSubscription = new SingleAssignmentDisposable();
sourceSubscription.setDisposable(source.subscribe(
function (newValue) {
hasValue = true;
value = newValue;
},
function (e) { o.onError(e); },
function () {
atEnd = true;
sourceSubscription.dispose();
}
));
return new CompositeDisposable(
sourceSubscription,
sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false;
return scheduler.scheduleRecursiveWithAbsoluteAndState(initialState, scheduler.now(), function (state, self) {
hasResult && observer.onNext(state);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
var result = resultSelector(state);
var time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(result, time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false;
return scheduler.scheduleRecursiveWithRelativeAndState(initialState, 0, function (state, self) {
hasResult && observer.onNext(state);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
var result = resultSelector(state);
var time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(result, time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds
*
* @param {Number} dueTime Relative or absolute time shift of the subscription.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative';
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var d = new SerialDisposable();
d.setDisposable(scheduler[scheduleMethod](dueTime, function() {
d.setDisposable(source.subscribe(o));
}));
return d;
}, this);
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (isFunction(subscriptionDelay)) {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable();
function start() {
subscription.setDisposable(source.subscribe(
function (x) {
var delay = tryCatch(selector)(x);
if (delay === errorObj) { return observer.onError(delay.e); }
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(
function () {
observer.onNext(x);
delays.remove(d);
done();
},
function (e) { observer.onError(e); },
function () {
observer.onNext(x);
delays.remove(d);
done();
}
))
},
function (e) { observer.onError(e); },
function () {
atEnd = true;
subscription.dispose();
done();
}
))
}
function done () {
atEnd && delays.length === 0 && observer.onCompleted();
}
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start));
}
return new CompositeDisposable(subscription, delays);
}, this);
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false;
function setTimer(timeout) {
var myId = id;
function timerWins () {
return id === myId;
}
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
d.dispose();
}, function (e) {
timerWins() && observer.onError(e);
}, function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
}));
};
setTimer(firstTimeout);
function observerWins() {
var res = !switched;
if (res) { id++; }
return res;
}
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
}
}, function (e) {
observerWins() && observer.onError(e);
}, function () {
observerWins() && observer.onCompleted();
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
* @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounceWithSelector = function (durationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
var subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = durationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
isPromise(throttle) && (throttle = observableFromPromise(throttle));
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
hasValue && observer.onNext(value);
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, source);
};
/**
* @deprecated use #debounceWithSelector instead.
*/
observableProto.throttleWithSelector = function (durationSelector) {
//deprecate('throttleWithSelector', 'debounceWithSelector');
return this.debounceWithSelector(durationSelector);
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
o.onCompleted();
});
}, source);
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) { o.onNext(next.value); }
}
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
now - next.interval <= duration && res.push(next.value);
}
o.onNext(res);
o.onCompleted();
});
}, source);
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o));
}, source);
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
}, source);
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [scheduler]);
* @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && o.onNext(x); },
function (e) { o.onError(e); }, function () { o.onCompleted(); }));
}, source);
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} [scheduler] Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
return new CompositeDisposable(
scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }),
source.subscribe(o));
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(o) {
return {
'@@transducer/init': function() {
return o;
},
'@@transducer/step': function(obs, input) {
return obs.onNext(input);
},
'@@transducer/result': function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(o) {
var xform = transducer(transformForObserver(o));
return source.subscribe(
function(v) {
try {
xform['@@transducer/step'](o, v);
} catch (e) {
o.onError(e);
}
},
function (e) { o.onError(e); },
function() { xform['@@transducer/result'](o); }
);
}, source);
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
}, this);
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this,
selectorFunc = bindCallback(selector, thisArg, 3);
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selectorFunc(x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
function (e) { observer.onError(e); },
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
}, this);
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (__super__) {
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, __super__);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
__super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time),
dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); }
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
while (this.queue.length > 0) {
var next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this;
function run(scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
}
var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
this.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (__super__) {
inherits(HistoricalScheduler, __super__);
/**
* Creates a new historical scheduler with the specified initial clock value.
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
__super__.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
var sub = tryCatch(subscribe)(ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
function s(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, subscribe];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var GroupedObservable = (function (__super__) {
inherits(GroupedObservable, __super__);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
__super__.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Used to pause and resume streams.
*/
Rx.Pauser = (function (__super__) {
inherits(Pauser, __super__);
function Pauser() {
__super__.call(this);
}
/**
* Pauses the underlying sequence.
*/
Pauser.prototype.pause = function () { this.onNext(false); };
/**
* Resumes the underlying sequence.
*/
Pauser.prototype.resume = function () { this.onNext(true); };
return Pauser;
}(Subject));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":1}],3:[function(require,module,exports){
'use strict';
var Rx = require('rx');
function makeRequestProxies(drivers) {
var requestProxies = {};
for (var _name in drivers) {
if (drivers.hasOwnProperty(_name)) {
requestProxies[_name] = new Rx.ReplaySubject(1);
}
}
return requestProxies;
}
function callDrivers(drivers, requestProxies) {
var responses = {};
for (var _name2 in drivers) {
if (drivers.hasOwnProperty(_name2)) {
responses[_name2] = drivers[_name2](requestProxies[_name2], _name2);
}
}
return responses;
}
function makeDispose(requestProxies, rawResponses) {
return function dispose() {
for (var x in requestProxies) {
if (requestProxies.hasOwnProperty(x)) {
requestProxies[x].dispose();
}
}
for (var _name3 in rawResponses) {
if (rawResponses.hasOwnProperty(_name3) && typeof rawResponses[_name3].dispose === 'function') {
rawResponses[_name3].dispose();
}
}
};
}
function makeAppInput(requestProxies, rawResponses) {
Object.defineProperty(rawResponses, 'dispose', {
enumerable: false,
value: makeDispose(requestProxies, rawResponses)
});
return rawResponses;
}
function replicateMany(original, imitators) {
for (var _name4 in original) {
if (original.hasOwnProperty(_name4)) {
if (imitators.hasOwnProperty(_name4) && !imitators[_name4].isDisposed) {
original[_name4].subscribe(imitators[_name4].asObserver());
}
}
}
}
function isObjectEmpty(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
function run(app, drivers) {
if (typeof app !== 'function') {
throw new Error('First argument given to Cycle.run() must be the `app` ' + 'function.');
}
if (typeof drivers !== 'object' || drivers === null) {
throw new Error('Second argument given to Cycle.run() must be an object ' + 'with driver functions as properties.');
}
if (isObjectEmpty(drivers)) {
throw new Error('Second argument given to Cycle.run() must be an object ' + 'with at least one driver function declared as a property.');
}
var requestProxies = makeRequestProxies(drivers);
var rawResponses = callDrivers(drivers, requestProxies);
var responses = makeAppInput(requestProxies, rawResponses);
var requests = app(responses);
setTimeout(function () {
return replicateMany(requests, requestProxies);
}, 1);
return [requests, responses];
}
var Cycle = {
/**
* Takes an `app` function and circularly connects it to the given collection
* of driver functions.
*
* The `app` function expects a collection of "driver response" Observables as
* input, and should return a collection of "driver request" Observables.
* A "collection of Observables" is a JavaScript object where
* keys match the driver names registered by the `drivers` object, and values
* are Observables or a collection of Observables.
*
* @param {Function} app a function that takes `responses` as input
* and outputs a collection of `requests` Observables.
* @param {Object} drivers an object where keys are driver names and values
* are driver functions.
* @return {Array} an array where the first object is the collection of driver
* requests, and the second objet is the collection of driver responses, that
* can be used for debugging or testing.
* @function run
*/
run: run,
/**
* A shortcut to the root object of
* [RxJS](https://github.com/Reactive-Extensions/RxJS).
* @name Rx
*/
Rx: Rx
};
module.exports = Cycle;
},{"rx":2}]},{},[3])(3)
}); |
dapp/src/shared/components/app/add.js | airalab/DAO-IPCI | import React from 'react'
import { Field } from 'redux-form'
const renderField = ({
input, type, label, placeholder, disabled, className, meta: { touched, error }
}) => {
if (type === 'hidden') {
return <input {...input} type={type} />
}
return (
<div>
{label}
<input
{...input}
className={className}
type={type}
placeholder={placeholder}
disabled={disabled}
/>
{touched && error && error}
</div>
)
}
const Form = (props) => {
const { fields, handleSubmit, submitting } = props
// {address.touched && address.error ? <div className="alert alert-danger">
// {address.error}</div> : ''}
return (
<form onSubmit={handleSubmit}>
<div className="input-group">
<div className="input-group-addon"><span>DAO address</span></div>
{fields.map((item, index) => (
<Field key={index} component={renderField} {...item} type="text" className="form-control" />
))}
<div className="input-group-btn">
<button className="btn btn-default" type="submit" disabled={submitting}>{submitting ? '...' : 'Go!'}</button>
</div>
</div>
</form>
)
}
export default Form
|
react-flux-mui/js/material-ui/src/svg-icons/av/video-library.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvVideoLibrary = (props) => (
<SvgIcon {...props}>
<path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8 12.5v-9l6 4.5-6 4.5z"/>
</SvgIcon>
);
AvVideoLibrary = pure(AvVideoLibrary);
AvVideoLibrary.displayName = 'AvVideoLibrary';
AvVideoLibrary.muiName = 'SvgIcon';
export default AvVideoLibrary;
|
src/components/game_stats.js | adamakers/Scoreboard | import React from 'react';
import styles from './../styles/game_stats.css';
const GameStats = ({stats}) => {
return (
<section className="game-stats">
<div className="game-downs stat-box">DOWN <span className="num-box">1</span></div>
<div className="game-togo stat-box">TO GO <span className="num-box">10</span></div>
<div className="game-ball-pos stat-box">BALL ON <span className="num-box">50</span></div>
</section>
);
};
export default GameStats; |
ajax/libs/react-data-grid/1.0.17/react-data-grid.min.js | sufuf3/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.ReactDataGrid=t(require("react"),require("react-dom")):e.ReactDataGrid=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(r){if(o[r])return o[r].exports;var s=o[r]={exports:{},id:r,loaded:!1};return e[r].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var o={};return t.m=e,t.c=o,t.p="",t(0)}([function(e,t,o){"use strict";var r=o(27),s=o(9),i=o(11);e.exports=r,e.exports.Row=s,e.exports.Cell=i},function(t,o){t.exports=e},function(e,o){e.exports=t},function(e,t,o){function r(){for(var e,t="",o=0;o<arguments.length;o++)if(e=arguments[o])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+r.apply(null,e);else if("object"==typeof e)for(var s in e)e.hasOwnProperty(s)&&e[s]&&(t+=" "+s);return t.substr(1)}var s,i;"undefined"!=typeof e&&e.exports&&(e.exports=r),s=[],i=function(){return r}.apply(t,s),!(void 0!==i&&(e.exports=i))},function(e,t){"use strict";e.exports={getColumn:function(e,t){return Array.isArray(e)?e[t]:"undefined"!=typeof Immutable?e.get(t):void 0},spliceColumn:function(e,t,o){return Array.isArray(e.columns)?e.columns.splice(t,1,o):"undefined"!=typeof Immutable&&(e.columns=e.columns.splice(t,1,o)),e},getSize:function(e){return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0},canEdit:function(e,t,o){return null!=e.editable&&"function"==typeof e.editable?o===!0&&e.editable(t):!(o!==!0||!e.editor&&!e.editable)}}},function(e,t,o){"use strict";var r=o(1),s={name:r.PropTypes.node.isRequired,key:r.PropTypes.string.isRequired,width:r.PropTypes.number.isRequired,filterable:r.PropTypes.bool};e.exports=s},function(e,t,o){"use strict";var r=o(1).PropTypes;e.exports={selected:r.object.isRequired,copied:r.object,dragged:r.object,onCellClick:r.func.isRequired,onCellDoubleClick:r.func.isRequired,onCommit:r.func.isRequired,onCommitCancel:r.func.isRequired,handleDragEnterRow:r.func.isRequired,handleTerminateDrag:r.func.isRequired}},function(e,t,o){"use strict";var r=o(1),s=o(10),i={metricsComputator:r.PropTypes.object},n={childContextTypes:i,getChildContext:function(){return{metricsComputator:this}},getMetricImpl:function(e){return this._DOMMetrics.metrics[e].value},registerMetricsImpl:function(e,t){var o={},r=this._DOMMetrics;for(var s in t){if(void 0!==r.metrics[s])throw new Error("DOM metric "+s+" is already defined");r.metrics[s]={component:e,computator:t[s].bind(e)},o[s]=this.getMetricImpl.bind(null,s)}return r.components.indexOf(e)===-1&&r.components.push(e),o},unregisterMetricsFor:function(e){var t=this._DOMMetrics,o=t.components.indexOf(e);if(o>-1){t.components.splice(o,1);var r=void 0,s={};for(r in t.metrics)t.metrics[r].component===e&&(s[r]=!0);for(r in s)s.hasOwnProperty(r)&&delete t.metrics[r]}},updateMetrics:function(){var e=this._DOMMetrics,t=!1;for(var o in e.metrics)if(e.metrics.hasOwnProperty(o)){var r=e.metrics[o].computator();r!==e.metrics[o].value&&(t=!0),e.metrics[o].value=r}if(t)for(var s=0,i=e.components.length;s<i;s++)e.components[s].metricsUpdated&&e.components[s].metricsUpdated()},componentWillMount:function(){this._DOMMetrics={metrics:{},components:[]}},componentDidMount:function(){window.addEventListener?window.addEventListener("resize",this.updateMetrics):window.attachEvent("resize",this.updateMetrics),this.updateMetrics()},componentWillUnmount:function(){window.removeEventListener("resize",this.updateMetrics)}},l={contextTypes:i,componentWillMount:function(){if(this.DOMMetrics){this._DOMMetricsDefs=s(this.DOMMetrics),this.DOMMetrics={};for(var e in this._DOMMetricsDefs)this._DOMMetricsDefs.hasOwnProperty(e)&&(this.DOMMetrics[e]=function(){})}},componentDidMount:function(){this.DOMMetrics&&(this.DOMMetrics=this.registerMetrics(this._DOMMetricsDefs))},componentWillUnmount:function(){return this.registerMetricsImpl?void(this.hasOwnProperty("DOMMetrics")&&delete this.DOMMetrics):this.context.metricsComputator.unregisterMetricsFor(this)},registerMetrics:function(e){return this.registerMetricsImpl?this.registerMetricsImpl(this,e):this.context.metricsComputator.registerMetricsImpl(this,e)},getMetric:function(e){return this.getMetricImpl?this.getMetricImpl(e):this.context.metricsComputator.getMetricImpl(e)}};e.exports={MetricsComputatorMixin:n,MetricsMixin:l}},function(e,t,o){"use strict";function r(e,t){return e.map(function(e){var o=Object.assign({},e);return e.width&&/^([0-9]+)%$/.exec(e.width.toString())&&(o.width=Math.floor(e.width/100*t)),o})}function s(e,t,o){var r=e.filter(function(e){return!e.width});return e.map(function(e){return e.width||(t<=0?e.width=o:e.width=Math.floor(t/h.getSize(r))),e})}function i(e){var t=0;return e.map(function(e){return e.left=t,t+=e.width,e})}function n(e){var t=r(e.columns,e.totalWidth),o=t.filter(function(e){return e.width}).reduce(function(e,t){return e-t.width},e.totalWidth);o-=f();var n=t.filter(function(e){return e.width}).reduce(function(e,t){return e+t.width},0);return t=s(t,o,e.minColumnWidth),t=i(t),{columns:t,width:n,totalWidth:e.totalWidth,minColumnWidth:e.minColumnWidth}}function l(e,t,o){var r=h.getColumn(e.columns,t),s=u(e);s.columns=e.columns.slice(0);var i=u(r);return i.width=Math.max(o,s.minColumnWidth),s=h.spliceColumn(s,t,i),n(s)}function a(e,t){return"undefined"!=typeof Immutable&&e instanceof Immutable.List&&t instanceof Immutable.List}function c(e,t,o){var r=void 0,s=void 0,i=void 0,n={},l={};if(h.getSize(e)!==h.getSize(t))return!1;for(r=0,s=h.getSize(e);r<s;r++)i=e[r],n[i.key]=i;for(r=0,s=h.getSize(t);r<s;r++){i=t[r],l[i.key]=i;var a=n[i.key];if(void 0===a||!o(a,i))return!1}for(r=0,s=h.getSize(e);r<s;r++){i=e[r];var c=l[i.key];if(void 0===c)return!1}return!0}function p(e,t,o){return a(e,t)?e===t:c(e,t,o)}var u=o(10),d=o(18),h=o(4),f=o(14);e.exports={recalculate:n,resizeColumn:l,sameColumn:d,sameColumns:p}},function(e,t,o){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},s=o(1),i=o(3),n=o(11),l=o(8),a=o(4),c=o(6),p=s.PropTypes,u=s.createClass({displayName:"CellExpander",render:function(){return s.createElement(n,this.props)}}),d=s.createClass({displayName:"Row",propTypes:{height:p.number.isRequired,columns:p.oneOfType([p.object,p.array]).isRequired,row:p.any.isRequired,cellRenderer:p.func,cellMetaData:p.shape(c),isSelected:p.bool,idx:p.number.isRequired,key:p.string,expandedRows:p.arrayOf(p.object),extraClasses:p.string,forceUpdate:p.bool,subRowDetails:p.object},mixins:[a],getDefaultProps:function(){return{cellRenderer:n,isSelected:!1,height:35}},shouldComponentUpdate:function(e){return!l.sameColumns(this.props.columns,e.columns,l.sameColumn)||this.doesRowContainSelectedCell(this.props)||this.doesRowContainSelectedCell(e)||this.willRowBeDraggedOver(e)||e.row!==this.props.row||this.hasRowBeenCopied()||this.props.isSelected!==e.isSelected||e.height!==this.props.height||this.props.forceUpdate===!0},handleDragEnter:function(){var e=this.props.cellMetaData.handleDragEnterRow;e&&e(this.props.idx)},getSelectedColumn:function(){if(this.props.cellMetaData){var e=this.props.cellMetaData.selected;if(e&&e.idx)return this.getColumn(this.props.columns,e.idx)}},getCellRenderer:function(e){var t=this.props.cellRenderer;return this.props.subRowDetails&&this.props.subRowDetails.field===e?u:t},getCells:function(){var e=this,t=[],o=[],r=this.getSelectedColumn();return this.props.columns&&this.props.columns.forEach(function(i,n){var l=e.props.cellRenderer,a=s.createElement(l,{ref:n,key:i.key+"-"+n,idx:n,rowIdx:e.props.idx,value:e.getCellValue(i.key||n),column:i,height:e.getRowHeight(),formatter:i.formatter,cellMetaData:e.props.cellMetaData,rowData:e.props.row,selectedColumn:r,isRowSelected:e.props.isSelected,expandableOptions:e.getExpandableOptions(i.key)});i.locked?o.push(a):t.push(a)}),t.concat(o)},getRowHeight:function(){var e=this.props.expandedRows||null;if(e&&this.props.key){var t=e[this.props.key]||null;if(t)return t.height}return this.props.height},getCellValue:function(e){var t=void 0;return"select-row"===e?this.props.isSelected:t="function"==typeof this.props.row.get?this.props.row.get(e):this.props.row[e]},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(o,r){if(o.locked){if(!t.refs[r])return;t.refs[r].setScrollLeft(e)}})},doesRowContainSelectedCell:function(e){var t=e.cellMetaData.selected;return!(!t||t.rowIdx!==e.idx)},isContextMenuDisplayed:function(){if(this.props.cellMetaData){var e=this.props.cellMetaData.selected;if(e&&e.contextMenuDisplayed&&e.rowIdx===this.props.idx)return!0}return!1},willRowBeDraggedOver:function(e){var t=e.cellMetaData.dragged;return null!=t&&(t.rowIdx>=0||t.complete===!0)},hasRowBeenCopied:function(){var e=this.props.cellMetaData.copied;return null!=e&&e.rowIdx===this.props.idx},getExpandableOptions:function(e){return{canExpand:this.props.subRowDetails&&this.props.subRowDetails.field===e,expanded:this.props.subRowDetails&&this.props.subRowDetails.expanded,children:this.props.subRowDetails&&this.props.subRowDetails.children,treeDepth:this.props.subRowDetails?this.props.subRowDetails.treeDepth:0}},renderCell:function(e){return"function"==typeof this.props.cellRenderer&&this.props.cellRenderer.call(this,e),s.isValidElement(this.props.cellRenderer)?s.cloneElement(this.props.cellRenderer,e):this.props.cellRenderer(e)},render:function(){var e=i("react-grid-Row","react-grid-Row--"+(this.props.idx%2===0?"even":"odd"),{"row-selected":this.props.isSelected,"row-context-menu":this.isContextMenuDisplayed()},this.props.extraClasses),t={height:this.getRowHeight(this.props),overflow:"hidden"},o=this.getCells();return s.createElement("div",r({},this.props,{className:e,style:t,onDragEnter:this.handleDragEnter}),s.isValidElement(this.props.row)?this.props.row:o)}});e.exports=d},function(e,t){"use strict";function o(e){var t={};for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o]);return t}e.exports=o},function(e,t,o){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},s=o(1),i=o(2),n=o(3),l=o(39),a=o(5),c=o(13),p=o(6),u=o(41),d=o(4),h=s.createClass({displayName:"Cell",propTypes:{rowIdx:s.PropTypes.number.isRequired,idx:s.PropTypes.number.isRequired,selected:s.PropTypes.shape({idx:s.PropTypes.number.isRequired}),selectedColumn:s.PropTypes.object,height:s.PropTypes.number,tabIndex:s.PropTypes.number,ref:s.PropTypes.string,column:s.PropTypes.shape(a).isRequired,value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired,isExpanded:s.PropTypes.bool,isRowSelected:s.PropTypes.bool,cellMetaData:s.PropTypes.shape(p).isRequired,handleDragStart:s.PropTypes.func,className:s.PropTypes.string,cellControls:s.PropTypes.any,rowData:s.PropTypes.object.isRequired,forceUpdate:s.PropTypes.bool,expandableOptions:s.PropTypes.object.isRequired},getDefaultProps:function(){return{tabIndex:-1,ref:"cell",isExpanded:!1}},getInitialState:function(){return{isCellValueChanging:!1}},componentDidMount:function(){this.checkFocus()},componentWillReceiveProps:function(e){this.setState({isCellValueChanging:this.props.value!==e.value})},componentDidUpdate:function(){this.checkFocus();var e=this.props.cellMetaData.dragged;e&&e.complete===!0&&this.props.cellMetaData.handleTerminateDrag(),this.state.isCellValueChanging&&null!=this.props.selectedColumn&&this.applyUpdateClass()},shouldComponentUpdate:function(e){return this.props.column.width!==e.column.width||this.props.column.left!==e.column.left||this.props.height!==e.height||this.props.rowIdx!==e.rowIdx||this.isCellSelectionChanging(e)||this.isDraggedCellChanging(e)||this.isCopyCellChanging(e)||this.props.isRowSelected!==e.isRowSelected||this.isSelected()||this.props.value!==e.value||this.props.forceUpdate===!0},onCellClick:function(e){var t=this.props.cellMetaData;null!=t&&t.onCellClick&&"function"==typeof t.onCellClick&&t.onCellClick({rowIdx:this.props.rowIdx,idx:this.props.idx},e)},onCellContextMenu:function(){var e=this.props.cellMetaData;null!=e&&e.onCellContextMenu&&"function"==typeof e.onCellContextMenu&&e.onCellContextMenu({rowIdx:this.props.rowIdx,idx:this.props.idx})},onCellDoubleClick:function(e){var t=this.props.cellMetaData;null!=t&&t.onCellDoubleClick&&"function"==typeof t.onCellDoubleClick&&t.onCellDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx},e)},onCellExpand:function(e){e.stopPropagation();var t=this.props.cellMetaData;null!=t&&null!=t.onCellExpand&&t.onCellExpand({rowIdx:this.props.rowIdx,idx:this.props.idx,rowData:this.props.rowData,expandArgs:this.props.expandableOptions})},onCellKeyDown:function(e){this.canExpand()&&"Enter"===e.key&&this.onCellExpand(e)},onDragHandleDoubleClick:function(e){e.stopPropagation();var t=this.props.cellMetaData;null!=t&&t.onDragHandleDoubleClick&&"function"==typeof t.onDragHandleDoubleClick&&t.onDragHandleDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx,rowData:this.getRowData(),e:e})},onDragOver:function(e){e.preventDefault()},getStyle:function(){var e={position:"absolute",width:this.props.column.width,height:this.props.height,left:this.props.column.left};return e},getFormatter:function(){var e=this.props.column;return this.isActive()?s.createElement(l,{rowData:this.getRowData(),rowIdx:this.props.rowIdx,idx:this.props.idx,cellMetaData:this.props.cellMetaData,column:e,height:this.props.height}):this.props.column.formatter},getRowData:function(){return this.props.rowData.toJSON?this.props.rowData.toJSON():this.props.rowData},getFormatterDependencies:function(){if("function"==typeof this.props.column.getRowMetaData)return this.props.column.getRowMetaData(this.getRowData(),this.props.column)},getCellClass:function(){var e=n(this.props.column.cellClass,"react-grid-Cell",this.props.className,this.props.column.locked?"react-grid-Cell--locked":null),t=n({"row-selected":this.props.isRowSelected,selected:this.isSelected()&&!this.isActive()&&this.isCellSelectEnabled(),editing:this.isActive(),copied:this.isCopied()||this.wasDraggedOver()||this.isDraggedOverUpwards()||this.isDraggedOverDownwards(),"active-drag-cell":this.isSelected()||this.isDraggedOver(),"is-dragged-over-up":this.isDraggedOverUpwards(),"is-dragged-over-down":this.isDraggedOverDownwards(),"was-dragged-over":this.wasDraggedOver()});return n(e,t)},getUpdateCellClass:function(){return this.props.column.getUpdateCellClass?this.props.column.getUpdateCellClass(this.props.selectedColumn,this.props.column,this.state.isCellValueChanging):""},isColumnSelected:function(){var e=this.props.cellMetaData;return null!=e&&(e.selected&&e.selected.idx===this.props.idx)},isSelected:function(){var e=this.props.cellMetaData;return null!=e&&(e.selected&&e.selected.rowIdx===this.props.rowIdx&&e.selected.idx===this.props.idx)},isActive:function(){var e=this.props.cellMetaData;return null!=e&&(this.isSelected()&&e.selected.active===!0)},isCellSelectionChanging:function(e){var t=this.props.cellMetaData;if(null==t)return!1;var o=e.cellMetaData.selected;return!t.selected||!o||(this.props.idx===o.idx||this.props.idx===t.selected.idx)},isCellSelectEnabled:function(){var e=this.props.cellMetaData;return null!=e&&e.enableCellSelect},applyUpdateClass:function(){var e=this.getUpdateCellClass();if(null!=e&&""!==e){var t=i.findDOMNode(this);t.classList?(t.classList.remove(e),t.classList.add(e)):t.className.indexOf(e)===-1&&(t.className=t.className+" "+e)}},setScrollLeft:function(e){var t=this;if(t.isMounted()){var o=i.findDOMNode(this),r="translate3d("+e+"px, 0px, 0px)";o.style.webkitTransform=r,o.style.transform=r}},isCopied:function(){var e=this.props.cellMetaData.copied;return e&&e.rowIdx===this.props.rowIdx&&e.idx===this.props.idx},isDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&e.overRowIdx===this.props.rowIdx&&e.idx===this.props.idx},wasDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&(e.overRowIdx<this.props.rowIdx&&this.props.rowIdx<e.rowIdx||e.overRowIdx>this.props.rowIdx&&this.props.rowIdx>e.rowIdx)&&e.idx===this.props.idx},isDraggedCellChanging:function(e){var t=void 0,o=this.props.cellMetaData.dragged,r=e.cellMetaData.dragged;return!!o&&(t=r&&this.props.idx===r.idx||o&&this.props.idx===o.idx)},isCopyCellChanging:function(e){var t=void 0,o=this.props.cellMetaData.copied,r=e.cellMetaData.copied;return!!o&&(t=r&&this.props.idx===r.idx||o&&this.props.idx===o.idx)},isDraggedOverUpwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx<e.rowIdx},isDraggedOverDownwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx>e.rowIdx},checkFocus:function(){if(this.isSelected()&&!this.isActive()){for(var e=i.findDOMNode(this);null!=e&&e.className.indexOf("react-grid-Viewport")===-1;)e=e.parentElement;var t=!1;if(null==document.activeElement||document.activeElement.nodeName&&"string"==typeof document.activeElement.nodeName&&"body"===document.activeElement.nodeName.toLowerCase())t=!0;else if(e)for(var o=document.activeElement;null!=o;){if(o===e){t=!0;break}o=o.parentElement}t&&i.findDOMNode(this).focus()}},canEdit:function(){return null!=this.props.column.editor||this.props.column.editable},canExpand:function(){return this.props.expandableOptions&&this.props.expandableOptions.canExpand},createColumEventCallBack:function(e,t){return function(o){e(o,t)}},createCellEventCallBack:function(e,t){return function(o){e(o),t(o)}},createEventDTO:function(e,t,o){var r=Object.assign({},e);for(var s in t)if(t.hasOwnProperty(s)){var i=t[i],n={rowIdx:this.props.rowIdx,idx:this.props.idx,name:s},l=this.createColumEventCallBack(o,n);if(r.hasOwnProperty(s)){var a=r[s];r[s]=this.createCellEventCallBack(a,l)}else r[s]=l}return r},getEvents:function(){var e=this.props.column?Object.assign({},this.props.column.events):void 0,t=this.props.cellMetaData?this.props.cellMetaData.onColumnEvent:void 0,o={onClick:this.onCellClick,onDoubleClick:this.onCellDoubleClick,onDragOver:this.onDragOver};return e&&t?this.createEventDTO(o,e,t):o},renderCellContent:function(e){var t=void 0,o=this.getFormatter();s.isValidElement(o)?(e.dependentValues=this.getFormatterDependencies(),t=s.cloneElement(o,e)):t=c(o)?s.createElement(o,{value:this.props.value,dependentValues:this.getFormatterDependencies()}):s.createElement(u,{value:this.props.value});var r=void 0,i=this.props.expandableOptions?30*this.props.expandableOptions.treeDepth:0,n=this.props.expandableOptions?10*this.props.expandableOptions.treeDepth:0;return this.canExpand()&&(r=s.createElement("span",{style:{"float":"left",marginLeft:i},onClick:this.onCellExpand},this.props.expandableOptions.expanded?String.fromCharCode("9660"):String.fromCharCode("9658"))),s.createElement("div",{ref:"cell",className:"react-grid-Cell__value"},r,s.createElement("span",{style:{"float":"left",marginLeft:n}},t)," ",this.props.cellControls," ")},render:function(){var e=this.getStyle(),t=this.getCellClass(),o=this.renderCellContent({value:this.props.value,column:this.props.column,rowIdx:this.props.rowIdx,isExpanded:this.props.isExpanded}),i=!this.isActive()&&d.canEdit(this.props.column,this.props.rowData,this.props.cellMetaData.enableCellSelect)?s.createElement("div",{className:"drag-handle",draggable:"true",onDoubleClick:this.onDragHandleDoubleClick},s.createElement("span",{style:{display:"none"}})):null,n=this.getEvents();return s.createElement("div",r({},this.props,{className:t,style:e,onClick:this.onCellClick,onDoubleClick:this.onCellDoubleClick,onContextMenu:this.onCellContextMenu,onDragOver:this.onDragOver},n),o,i)}});e.exports=h},function(e,t){"use strict";var o={onKeyDown:function(e){if(this.isCtrlKeyHeldDown(e))this.checkAndCall("onPressKeyWithCtrl",e);else if(this.isKeyExplicitlyHandled(e.key)){var t="onPress"+e.key;this.checkAndCall(t,e)}else this.isKeyPrintable(e.keyCode)&&this.checkAndCall("onPressChar",e)},isKeyPrintable:function(e){var t=e>47&&e<58||32===e||13===e||e>64&&e<91||e>95&&e<112||e>185&&e<193||e>218&&e<223;return t},isKeyExplicitlyHandled:function(e){return"function"==typeof this["onPress"+e]},isCtrlKeyHeldDown:function(e){return e.ctrlKey===!0&&"Control"!==e.key},checkAndCall:function(e,t){"function"==typeof this[e]&&this[e](t)}};e.exports=o},function(e,t){"use strict";var o=function(e){var t={};return e&&"[object Function]"===t.toString.call(e)};e.exports=o},function(e,t){"use strict";function o(){if(void 0===r){var e=document.createElement("div");e.style.width="50px",e.style.height="50px",e.style.position="absolute",e.style.top="-200px",e.style.left="-200px";var t=document.createElement("div");t.style.height="100px",t.style.width="100%",e.appendChild(t),document.body.appendChild(e);var o=e.clientWidth;e.style.overflowY="scroll";var s=t.clientWidth;document.body.removeChild(e),r=o-s}return r}var r=void 0;e.exports=o},function(e,t){"use strict";function o(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var o=Object.keys(e),s=Object.keys(t);if(o.length!==s.length)return!1;for(var i=r.bind(t),n=0;n<o.length;n++)if(!i(o[n])||e[o[n]]!==t[o[n]])return!1;return!0}var r=Object.prototype.hasOwnProperty;e.exports=o},function(e,t){"use strict";function o(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var r,s,i=o(e),n=1;n<arguments.length;n++){r=arguments[n],s=Object.keys(Object(r));for(var l=0;l<s.length;l++)i[s[l]]=r[s[l]]}return i}},function(e,t,o){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},i=o(15),n=r(i),l=o(31),a=r(l),c=o(29),p=r(c),u=o(1),d=o(2),h=o(3),f=u.PropTypes,m=o(32),g=o(9),w=o(6),y=u.createClass({displayName:"Canvas",mixins:[m],propTypes:{rowRenderer:f.oneOfType([f.func,f.element]),rowHeight:f.number.isRequired,height:f.number.isRequired,width:f.number,totalWidth:f.oneOfType([f.number,f.string]),style:f.string,className:f.string,displayStart:f.number.isRequired,displayEnd:f.number.isRequired,rowsCount:f.number.isRequired,rowGetter:f.oneOfType([f.func.isRequired,f.array.isRequired]),expandedRows:f.array,onRows:f.func,onScroll:f.func,columns:f.oneOfType([f.object,f.array]).isRequired,cellMetaData:f.shape(w).isRequired,selectedRows:f.array,rowKey:u.PropTypes.string,rowScrollTimeout:u.PropTypes.number,contextMenu:f.element,getSubRowDetails:f.func},getDefaultProps:function(){return{rowRenderer:g,onRows:function(){},selectedRows:[],rowScrollTimeout:0}},getInitialState:function(){return{displayStart:this.props.displayStart,displayEnd:this.props.displayEnd,scrollingTimeout:null}},componentWillMount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidMount:function(){this.onRows()},componentWillReceiveProps:function(e){e.displayStart===this.state.displayStart&&e.displayEnd===this.state.displayEnd||this.setState({displayStart:e.displayStart,displayEnd:e.displayEnd})},shouldComponentUpdate:function(e,t){var o=t.displayStart!==this.state.displayStart||t.displayEnd!==this.state.displayEnd||t.scrollingTimeout!==this.state.scrollingTimeout||e.rowsCount!==this.props.rowsCount||e.rowHeight!==this.props.rowHeight||e.columns!==this.props.columns||e.width!==this.props.width||e.cellMetaData!==this.props.cellMetaData||!(0,n["default"])(e.style,this.props.style);return o},componentWillUnmount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidUpdate:function(){0!==this._scroll.scrollTop&&0!==this._scroll.scrollLeft&&this.setScrollLeft(this._scroll.scrollLeft),this.onRows()},onRows:function(){this._currentRowsRange!=={start:0,end:0}&&(this.props.onRows(this._currentRowsRange),this._currentRowsRange={start:0,end:0})},onScroll:function(e){var t=this;if(d.findDOMNode(this)===e.target){this.appendScrollShim();var o=e.target.scrollLeft,r=e.target.scrollTop,s={scrollTop:r,scrollLeft:o},i=Math.abs(this._scroll.scrollTop-s.scrollTop)/this.props.rowHeight,n=i>this.props.displayEnd-this.props.displayStart;if(this._scroll=s,this.props.onScroll(s),n&&this.props.rowScrollTimeout>0){var l=this.state.scrollingTimeout;l&&clearTimeout(l),l=setTimeout(function(){null!==t.state.scrollingTimeout&&t.setState({scrollingTimeout:null})},this.props.rowScrollTimeout),this.setState({scrollingTimeout:l})}}},getSubRows:function(e){var t=this.props.getSubRowDetails(e);if(t.expanded===!0)return t.children.map(function(e){return{row:e}})},addSubRows:function(e,t,o,r,s){var i=this,n=this.props.getSubRowDetails(t)||{},l=e,a=o;if(a<r&&(n.treeDepth=s,l.push({row:t,subRowDetails:n}),a++),n&&n.expanded){var c=this.getSubRows(t);c.forEach(function(e){var t=i.addSubRows(l,e.row,a,r,s+1);l=t.rows,a=t.increment})}return{rows:l,increment:a}},getRows:function(e,t){if(this._currentRowsRange={start:e,end:t},Array.isArray(this.props.rowGetter))return this.props.rowGetter.slice(e,t);for(var o=[],r=e,s=e;s<t;){var i=this.props.rowGetter(r);if(this.props.getSubRowDetails){var n=0,l=this.addSubRows(o,i,s,t,n);o=l.rows,s=l.increment}else o.push({row:i}),s++;r++}return o},getScrollbarWidth:function(){var e=0,t=d.findDOMNode(this);return e=t.offsetWidth-t.clientWidth},getScroll:function(){var e=d.findDOMNode(this),t=e.scrollTop,o=e.scrollLeft;return{scrollTop:t,scrollLeft:o}},isRowSelected:function(e){var t=this,o=this.props.selectedRows.filter(function(o){var r=e.get?e.get(t.props.rowKey):e[t.props.rowKey];return o[t.props.rowKey]===r});return o.length>0&&o[0].isSelected},_currentRowsLength:0,_currentRowsRange:{start:0,end:0},_scroll:{scrollTop:0,scrollLeft:0},setScrollLeft:function(e){if(0!==this._currentRowsLength){if(!this.refs)return;for(var t=0,o=this._currentRowsLength;t<o;t++)this.refs[t]&&this.refs[t].setScrollLeft&&this.refs[t].setScrollLeft(e)}},renderRow:function(e){var t=e.row;if(t.__metaData&&t.__metaData.isGroup)return u.createElement(p["default"],s({name:t.name},t.__metaData,{idx:e.idx,cellMetaData:this.props.cellMetaData}));if(null!==this.state.scrollingTimeout)return this.renderScrollingPlaceholder(e);var o=this.props.rowRenderer;return"function"==typeof o?u.createElement(o,e):u.isValidElement(this.props.rowRenderer)?u.cloneElement(this.props.rowRenderer,e):void 0},renderScrollingPlaceholder:function(e){var t={row:{height:e.height,overflow:"hidden"},cell:{height:e.height,position:"absolute"},placeholder:{backgroundColor:"rgba(211, 211, 211, 0.45)",width:"60%",height:Math.floor(.3*e.height)}};return u.createElement("div",{key:e.key,style:t.row,className:"react-grid-Row"},this.props.columns.map(function(e,o){return u.createElement("div",{style:Object.assign(t.cell,{width:e.width,left:e.left}),key:o,className:"react-grid-Cell"},u.createElement("div",{style:Object.assign(t.placeholder,{width:Math.floor(.6*e.width)})}))}))},renderPlaceholder:function(e,t){return u.createElement("div",{key:e,style:{height:t}},this.props.columns.map(function(e,t){return u.createElement("div",{style:{width:e.width},key:t})}))},render:function(){var e=this,t=this.state.displayStart,o=this.state.displayEnd,r=this.props.rowHeight,s=this.props.rowsCount,i=this.getRows(t,o).map(function(o,s){return e.renderRow({key:t+s,ref:s,idx:t+s,row:o.row,height:r,columns:e.props.columns,isSelected:e.isRowSelected(o.row),expandedRows:e.props.expandedRows,cellMetaData:e.props.cellMetaData,subRowDetails:o.subRowDetails})});this._currentRowsLength=i.length,t>0&&i.unshift(this.renderPlaceholder("top",t*r)),s-o>0&&i.push(this.renderPlaceholder("bottom",(s-o)*r));var n={position:"absolute",top:0,left:0,overflowX:"auto",overflowY:"scroll",width:this.props.totalWidth,height:this.props.height,transform:"translate3d(0, 0, 0)"};return u.createElement("div",{style:n,onScroll:this.onScroll,className:h("react-grid-Canvas",this.props.className,{opaque:this.props.cellMetaData.selected&&this.props.cellMetaData.selected.active})},u.createElement(a["default"],{width:this.props.width,rows:i,contextMenu:this.props.contextMenu,rowIdx:this.props.cellMetaData.selected.rowIdx,idx:this.props.cellMetaData.selected.idx}))}});e.exports=y},function(e,t,o){"use strict";var r=o(1).isValidElement;e.exports=function(e,t){var o=void 0;for(o in e)if(e.hasOwnProperty(o)){if("function"==typeof e[o]&&"function"==typeof t[o]||r(e[o])&&r(t[o]))continue;if(!t.hasOwnProperty(o)||e[o]!==t[o])return!1}for(o in t)if(t.hasOwnProperty(o)&&!e.hasOwnProperty(o))return!1;return!0}},function(e,t,o){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=o(2),n=r(i),l=o(8),a=o(7);Object.assign=o(16);var c=o(1).PropTypes,p=o(4),u=function d(){s(this,d)};e.exports={mixins:[a.MetricsMixin],propTypes:{columns:c.arrayOf(u),minColumnWidth:c.number,columnEquality:c.func,onColumnResize:c.func},DOMMetrics:{gridWidth:function(){return n["default"].findDOMNode(this).parentElement.offsetWidth}},getDefaultProps:function(){return{minColumnWidth:80,columnEquality:l.sameColumn}},componentWillMount:function(){this._mounted=!0},componentWillReceiveProps:function(e){if(e.columns&&(!l.sameColumns(this.props.columns,e.columns,this.props.columnEquality)||e.minWidth!==this.props.minWidth)){var t=this.createColumnMetrics(e);this.setState({columnMetrics:t})}},getTotalWidth:function(){var e=0;return e=this._mounted?this.DOMMetrics.gridWidth():p.getSize(this.props.columns)*this.props.minColumnWidth},getColumnMetricsType:function(e){var t=e.totalWidth||this.getTotalWidth(),o={columns:e.columns,totalWidth:t,minColumnWidth:e.minColumnWidth},r=l.recalculate(o);return r},getColumn:function(e){var t=this.state.columnMetrics.columns;return Array.isArray(t)?t[e]:"undefined"!=typeof Immutable?t.get(e):void 0},getSize:function(){var e=this.state.columnMetrics.columns;return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0},metricsUpdated:function(){var e=this.createColumnMetrics();this.setState({columnMetrics:e})},createColumnMetrics:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=this.setupGridColumns(e);return this.getColumnMetricsType({columns:t,minColumnWidth:this.props.minColumnWidth,totalWidth:e.minWidth})},onColumnResize:function(e,t){var o=l.resizeColumn(this.state.columnMetrics,e,t);this.setState({columnMetrics:o}),this.props.onColumnResize&&this.props.onColumnResize(e,t)}}},function(e,t,o){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},s=o(1),i=s.PropTypes,n=s.createClass({displayName:"Draggable",propTypes:{onDragStart:i.func,onDragEnd:i.func,onDrag:i.func,component:i.oneOfType([i.func,i.constructor])},getDefaultProps:function(){return{onDragStart:function(){return!0},onDragEnd:function(){},onDrag:function(){}}},getInitialState:function(){return{drag:null}},componentWillUnmount:function(){this.cleanUp()},onMouseDown:function(e){var t=this.props.onDragStart(e);null===t&&0!==e.button||(window.addEventListener("mouseup",this.onMouseUp),window.addEventListener("mousemove",this.onMouseMove),window.addEventListener("touchend",this.onMouseUp),window.addEventListener("touchmove",this.onMouseMove),this.setState({drag:t}))},onMouseMove:function(e){null!==this.state.drag&&(e.preventDefault&&e.preventDefault(),this.props.onDrag(e))},onMouseUp:function(e){this.cleanUp(),this.props.onDragEnd(e,this.state.drag),this.setState({drag:null})},cleanUp:function(){window.removeEventListener("mouseup",this.onMouseUp),
window.removeEventListener("mousemove",this.onMouseMove),window.removeEventListener("touchend",this.onMouseUp),window.removeEventListener("touchmove",this.onMouseMove)},render:function(){return s.createElement("div",r({},this.props,{onMouseDown:this.onMouseDown,onTouchStart:this.onMouseDown,className:"react-grid-HeaderCell__draggable"}))}});e.exports=n},function(e,t,o){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},s=o(1),i=s.PropTypes,n=o(23),l=o(33),a=o(22),c=o(7),p=o(6),u=s.createClass({displayName:"Grid",propTypes:{rowGetter:i.oneOfType([i.array,i.func]).isRequired,columns:i.oneOfType([i.array,i.object]),columnMetrics:i.object,minHeight:i.number,totalWidth:i.oneOfType([i.number,i.string]),headerRows:i.oneOfType([i.array,i.func]),rowHeight:i.number,rowRenderer:i.func,emptyRowsView:i.func,expandedRows:i.oneOfType([i.array,i.func]),selectedRows:i.oneOfType([i.array,i.func]),rowsCount:i.number,onRows:i.func,sortColumn:s.PropTypes.string,sortDirection:s.PropTypes.oneOf(["ASC","DESC","NONE"]),rowOffsetHeight:i.number.isRequired,onViewportKeydown:i.func.isRequired,onViewportDragStart:i.func.isRequired,onViewportDragEnd:i.func.isRequired,onViewportDoubleClick:i.func.isRequired,onColumnResize:i.func,onSort:i.func,cellMetaData:i.shape(p),rowKey:i.string.isRequired,rowScrollTimeout:i.number,contextMenu:i.element,getSubRowDetails:i.func,draggableHeaderCell:i.func},mixins:[a,c.MetricsComputatorMixin],getDefaultProps:function(){return{rowHeight:35,minHeight:350}},getStyle:function(){return{overflow:"hidden",outline:0,position:"relative",minHeight:this.props.minHeight}},render:function(){var e=this.props.headerRows||[{ref:"row"}],t=this.props.emptyRowsView;return s.createElement("div",r({},this.props,{style:this.getStyle(),className:"react-grid-Grid"}),s.createElement(n,{ref:"header",columnMetrics:this.props.columnMetrics,onColumnResize:this.props.onColumnResize,height:this.props.rowHeight,totalWidth:this.props.totalWidth,headerRows:e,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection,draggableHeaderCell:this.props.draggableHeaderCell,onSort:this.props.onSort,onScroll:this.onHeaderScroll}),this.props.rowsCount>=1||0===this.props.rowsCount&&!this.props.emptyRowsView?s.createElement("div",{ref:"viewPortContainer",onKeyDown:this.props.onViewportKeydown,onDoubleClick:this.props.onViewportDoubleClick,onDragStart:this.props.onViewportDragStart,onDragEnd:this.props.onViewportDragEnd},s.createElement(l,{ref:"viewport",rowKey:this.props.rowKey,width:this.props.columnMetrics.width,rowHeight:this.props.rowHeight,rowRenderer:this.props.rowRenderer,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columnMetrics:this.props.columnMetrics,totalWidth:this.props.totalWidth,onScroll:this.onScroll,onRows:this.props.onRows,cellMetaData:this.props.cellMetaData,rowOffsetHeight:this.props.rowOffsetHeight||this.props.rowHeight*e.length,minHeight:this.props.minHeight,rowScrollTimeout:this.props.rowScrollTimeout,contextMenu:this.props.contextMenu,getSubRowDetails:this.props.getSubRowDetails})):s.createElement("div",{ref:"emptyView",className:"react-grid-Empty"},s.createElement(t,null)))}});e.exports=u},function(e,t,o){"use strict";var r=o(2);e.exports={componentDidMount:function(){this._scrollLeft=this.refs.viewport?this.refs.viewport.getScroll().scrollLeft:0,this._onScroll()},componentDidUpdate:function(){this._onScroll()},componentWillMount:function(){this._scrollLeft=void 0},componentWillUnmount:function(){this._scrollLeft=void 0},onScroll:function(e){this._scrollLeft!==e.scrollLeft&&(this._scrollLeft=e.scrollLeft,this._onScroll())},onHeaderScroll:function(e){var t=e.target.scrollLeft;if(this._scrollLeft!==t){this._scrollLeft=t,this.refs.header.setScrollLeft(t);var o=r.findDOMNode(this.refs.viewport.refs.canvas);o.scrollLeft=t,this.refs.viewport.refs.canvas.setScrollLeft(t)}},_onScroll:function(){void 0!==this._scrollLeft&&(this.refs.header.setScrollLeft(this._scrollLeft),this.refs.viewport&&this.refs.viewport.setScrollLeft(this._scrollLeft))}}},function(e,t,o){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},s=o(1),i=o(2),n=o(3),l=o(10),a=o(8),c=o(4),p=o(26),u=s.PropTypes,d=s.createClass({displayName:"Header",propTypes:{columnMetrics:u.shape({width:u.number.isRequired,columns:u.any}).isRequired,totalWidth:u.oneOfType([u.number,u.string]),height:u.number.isRequired,headerRows:u.array.isRequired,sortColumn:u.string,sortDirection:u.oneOf(["ASC","DESC","NONE"]),onSort:u.func,onColumnResize:u.func,onScroll:u.func,draggableHeaderCell:u.func},getInitialState:function(){return{resizing:null}},componentWillReceiveProps:function(){this.setState({resizing:null})},shouldComponentUpdate:function(e,t){var o=!a.sameColumns(this.props.columnMetrics.columns,e.columnMetrics.columns,a.sameColumn)||this.props.totalWidth!==e.totalWidth||this.props.headerRows.length!==e.headerRows.length||this.state.resizing!==t.resizing||this.props.sortColumn!==e.sortColumn||this.props.sortDirection!==e.sortDirection;return o},onColumnResize:function(e,t){var o=this.state.resizing||this.props,r=this.getColumnPosition(e);if(null!=r){var s={columnMetrics:l(o.columnMetrics)};s.columnMetrics=a.resizeColumn(s.columnMetrics,r,t),s.columnMetrics.totalWidth<o.columnMetrics.totalWidth&&(s.columnMetrics.totalWidth=o.columnMetrics.totalWidth),s.column=c.getColumn(s.columnMetrics.columns,r),this.setState({resizing:s})}},onColumnResizeEnd:function(e,t){var o=this.getColumnPosition(e);null!==o&&this.props.onColumnResize&&this.props.onColumnResize(o,t||e.width)},getHeaderRows:function(){var e=this,t=this.getColumnMetrics(),o=void 0;this.state.resizing&&(o=this.state.resizing.column);var r=[];return this.props.headerRows.forEach(function(i,n){var l={position:"absolute",top:e.getCombinedHeaderHeights(n),left:0,width:e.props.totalWidth,overflow:"hidden"};r.push(s.createElement(p,{key:i.ref,ref:i.ref,rowType:i.rowType,style:l,onColumnResize:e.onColumnResize,onColumnResizeEnd:e.onColumnResizeEnd,width:t.width,height:i.height||e.props.height,columns:t.columns,resizing:o,draggableHeaderCell:e.props.draggableHeaderCell,filterable:i.filterable,onFilterChange:i.onFilterChange,sortColumn:e.props.sortColumn,sortDirection:e.props.sortDirection,onSort:e.props.onSort,onScroll:e.props.onScroll}))}),r},getColumnMetrics:function(){var e=void 0;return e=this.state.resizing?this.state.resizing.columnMetrics:this.props.columnMetrics},getColumnPosition:function(e){var t=this.getColumnMetrics(),o=-1;return t.columns.forEach(function(t,r){t.key===e.key&&(o=r)}),o===-1?null:o},getCombinedHeaderHeights:function(e){var t=this.props.headerRows.length;"undefined"!=typeof e&&(t=e);for(var o=0,r=0;r<t;r++)o+=this.props.headerRows[r].height||this.props.height;return o},getStyle:function(){return{position:"relative",height:this.getCombinedHeaderHeights(),overflow:"hidden"}},setScrollLeft:function(e){var t=i.findDOMNode(this.refs.row);if(t.scrollLeft=e,this.refs.row.setScrollLeft(e),this.refs.filterRow){var o=i.findDOMNode(this.refs.filterRow);o.scrollLeft=e,this.refs.filterRow.setScrollLeft(e)}},render:function(){var e=n({"react-grid-Header":!0,"react-grid-Header--resizing":!!this.state.resizing}),t=this.getHeaderRows();return s.createElement("div",r({},this.props,{style:this.getStyle(),className:e}),t)}});e.exports=d},function(e,t,o){"use strict";function r(e){return s.createElement("div",{className:"widget-HeaderCell__value"},e.column.name)}var s=o(1),i=o(2),n=o(3),l=o(5),a=o(28),c=s.PropTypes,p=s.createClass({displayName:"HeaderCell",propTypes:{renderer:c.oneOfType([c.func,c.element]).isRequired,column:c.shape(l).isRequired,onResize:c.func.isRequired,height:c.number.isRequired,onResizeEnd:c.func.isRequired,className:c.string},getDefaultProps:function(){return{renderer:r}},getInitialState:function(){return{resizing:!1}},onDragStart:function(e){this.setState({resizing:!0}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},onDrag:function(e){var t=this.props.onResize||null;if(t){var o=this.getWidthFromMouseEvent(e);o>0&&t(this.props.column,o)}},onDragEnd:function(e){var t=this.getWidthFromMouseEvent(e);this.props.onResizeEnd(this.props.column,t),this.setState({resizing:!1})},getWidthFromMouseEvent:function(e){var t=e.pageX||e.touches&&e.touches[0]&&e.touches[0].pageX||e.changedTouches&&e.changedTouches[e.changedTouches.length-1].pageX,o=i.findDOMNode(this).getBoundingClientRect().left;return t-o},getCell:function(){return s.isValidElement(this.props.renderer)?s.cloneElement(this.props.renderer,{column:this.props.column,height:this.props.height}):this.props.renderer({column:this.props.column})},getStyle:function(){return{width:this.props.column.width,left:this.props.column.left,display:"inline-block",position:"absolute",overflow:"hidden",height:this.props.height,margin:0,textOverflow:"ellipsis",whiteSpace:"nowrap"}},setScrollLeft:function(e){var t=i.findDOMNode(this);t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},render:function(){var e=void 0;this.props.column.resizable&&(e=s.createElement(a,{onDrag:this.onDrag,onDragStart:this.onDragStart,onDragEnd:this.onDragEnd}));var t=n({"react-grid-HeaderCell":!0,"react-grid-HeaderCell--resizing":this.state.resizing,"react-grid-HeaderCell--locked":this.props.column.locked});t=n(t,this.props.className,this.props.column.cellClass);var o=this.getCell();return s.createElement("div",{className:t,style:this.getStyle()},o,e)}});e.exports=p},function(e,t){"use strict";var o={SORTABLE:0,FILTERABLE:1,NONE:2,CHECKBOX:3};e.exports=o},function(e,t,o){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},s=o(1),i=o(15),n=o(24),l=o(14),a=(o(5),o(4)),c=o(36),p=o(35),u=o(25),d=s.PropTypes,h={overflow:s.PropTypes.string,width:d.oneOfType([d.number,d.string]),height:s.PropTypes.number,position:s.PropTypes.string},f=["ASC","DESC","NONE"],m=s.createClass({displayName:"HeaderRow",propTypes:{width:d.oneOfType([d.number,d.string]),height:d.number.isRequired,columns:d.oneOfType([d.array,d.object]),onColumnResize:d.func,onSort:d.func.isRequired,onColumnResizeEnd:d.func,style:d.shape(h),sortColumn:d.string,sortDirection:s.PropTypes.oneOf(f),cellRenderer:d.func,headerCellRenderer:d.func,filterable:d.bool,onFilterChange:d.func,resizing:d.object,onScroll:d.func,rowType:d.string,draggableHeaderCell:d.func},mixins:[a],shouldComponentUpdate:function(e){return e.width!==this.props.width||e.height!==this.props.height||e.columns!==this.props.columns||!i(e.style,this.props.style)||this.props.sortColumn!==e.sortColumn||this.props.sortDirection!==e.sortDirection},getHeaderCellType:function(e){return e.filterable&&this.props.filterable?u.FILTERABLE:e.sortable?u.SORTABLE:u.NONE},getFilterableHeaderCell:function(){return s.createElement(p,{onChange:this.props.onFilterChange})},getSortableHeaderCell:function(e){var t=this.props.sortColumn===e.key?this.props.sortDirection:f.NONE;return s.createElement(c,{columnKey:e.key,onSort:this.props.onSort,sortDirection:t})},getHeaderRenderer:function(e){var t=void 0;if(e.headerRenderer)t=e.headerRenderer;else{var o=this.getHeaderCellType(e);switch(o){case u.SORTABLE:t=this.getSortableHeaderCell(e);break;case u.FILTERABLE:t=this.getFilterableHeaderCell()}}return t},getStyle:function(){return{overflow:"hidden",width:"100%",height:this.props.height,position:"absolute"}},getCells:function(){for(var e=[],t=[],o=0,r=this.getSize(this.props.columns);o<r;o++){var i=this.getColumn(this.props.columns,o),l=this.getHeaderRenderer(i);"select-row"===i.key&&"filter"===this.props.rowType&&(l=s.createElement("div",null));var a=i.draggable?this.props.draggableHeaderCell:n,c=s.createElement(a,{ref:o,key:o,height:this.props.height,column:i,renderer:l,resizing:this.props.resizing===i,onResize:this.props.onColumnResize,onResizeEnd:this.props.onColumnResizeEnd});i.locked?t.push(c):e.push(c)}return e.concat(t)},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(o,r){o.locked&&t.refs[r].setScrollLeft(e)})},render:function(){var e={width:this.props.width?this.props.width+l():"100%",height:this.props.height,whiteSpace:"nowrap",overflowX:"hidden",overflowY:"hidden"},t=this.getCells();return s.createElement("div",r({},this.props,{className:"react-grid-HeaderRow",onScroll:this.props.onScroll}),s.createElement("div",{style:e},t))}});e.exports=m},function(e,t,o){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},s=o(1),i=o(2),n=o(21),l=(o(9),o(5),o(12)),a=o(37),c=o(7),p=o(19),u=o(30),d=o(4);Object.assign||(Object.assign=o(16));var h=s.createClass({displayName:"ReactDataGrid",mixins:[p,c.MetricsComputatorMixin,l],propTypes:{rowHeight:s.PropTypes.number.isRequired,headerRowHeight:s.PropTypes.number,minHeight:s.PropTypes.number.isRequired,minWidth:s.PropTypes.number,enableRowSelect:s.PropTypes.oneOfType([s.PropTypes.bool,s.PropTypes.string]),onRowUpdated:s.PropTypes.func,rowGetter:s.PropTypes.func.isRequired,rowsCount:s.PropTypes.number.isRequired,toolbar:s.PropTypes.element,enableCellSelect:s.PropTypes.bool,columns:s.PropTypes.oneOfType([s.PropTypes.object,s.PropTypes.array]).isRequired,onFilter:s.PropTypes.func,onCellCopyPaste:s.PropTypes.func,onCellsDragged:s.PropTypes.func,onAddFilter:s.PropTypes.func,onGridSort:s.PropTypes.func,onDragHandleDoubleClick:s.PropTypes.func,onGridRowsUpdated:s.PropTypes.func,onRowSelect:s.PropTypes.func,rowKey:s.PropTypes.string,rowScrollTimeout:s.PropTypes.number,onClearFilters:s.PropTypes.func,contextMenu:s.PropTypes.element,cellNavigationMode:s.PropTypes.oneOf(["none","loopOverRow","changeRow"]),onCellSelected:s.PropTypes.func,onCellDeSelected:s.PropTypes.func,onCellExpand:s.PropTypes.func,enableDragAndDrop:s.PropTypes.bool,onRowExpandToggle:s.PropTypes.func,draggableHeaderCell:s.PropTypes.func},getDefaultProps:function(){return{enableCellSelect:!1,tabIndex:-1,rowHeight:35,enableRowSelect:!1,minHeight:350,rowKey:"id",rowScrollTimeout:0,cellNavigationMode:"none"}},getInitialState:function(){var e=this.createColumnMetrics(),t={columnMetrics:e,selectedRows:[],copied:null,expandedRows:[],canFilter:!1,columnFilters:{},sortDirection:null,sortColumn:null,dragged:null,scrollOffset:0};return this.props.enableCellSelect?t.selected={rowIdx:0,idx:0}:t.selected={rowIdx:-1,idx:-1},t},hasSelectedCellChanged:function(e){var t=Object.assign({},this.state.selected);return t.rowIdx!==e.rowIdx||t.idx!==e.idx||t.active===!1},onContextMenuHide:function(){document.removeEventListener("click",this.onContextMenuHide);var e=Object.assign({},this.state.selected,{contextMenuDisplayed:!1});this.setState({selected:e})},onColumnEvent:function(e,t){var o=t.idx,r=t.name;if(r&&"undefined"!=typeof o){var s=this.getColumn(o);if(s&&s.events&&s.events[r]&&"function"==typeof s.events[r]){var i={rowIdx:t.rowIdx,idx:o,column:s};s.events[r](e,i)}}},onSelect:function(e){var t=this;if(this.state.selected.rowIdx!==e.rowIdx||this.state.selected.idx!==e.idx||this.state.selected.active===!1){var o=e.idx,r=e.rowIdx;o>=0&&r>=0&&o<d.getSize(this.state.columnMetrics.columns)&&r<this.props.rowsCount&&!function(){var o=t.state.selected;t.setState({selected:e},function(){"function"==typeof t.props.onCellDeSelected&&t.props.onCellDeSelected(o),"function"==typeof t.props.onCellSelected&&t.props.onCellSelected(e)})}()}},onCellClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx})},onCellContextMenu:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx,contextMenuDisplayed:this.props.contextMenu}),this.props.contextMenu&&document.addEventListener("click",this.onContextMenuHide)},onCellDoubleClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx}),this.setActive("Enter")},onViewportDoubleClick:function(){this.setActive()},onPressArrowUp:function(e){this.moveSelectedCell(e,-1,0)},onPressArrowDown:function(e){this.moveSelectedCell(e,1,0)},onPressArrowLeft:function(e){this.moveSelectedCell(e,0,-1)},onPressArrowRight:function(e){this.moveSelectedCell(e,0,1)},onPressTab:function(e){this.moveSelectedCell(e,0,e.shiftKey?-1:1)},onPressEnter:function(e){this.setActive(e.key)},onPressDelete:function(e){this.setActive(e.key)},onPressEscape:function(e){this.setInactive(e.key)},onPressBackspace:function(e){this.setActive(e.key)},onPressChar:function(e){this.isKeyPrintable(e.keyCode)&&this.setActive(e.keyCode)},onPressKeyWithCtrl:function(e){var t={KeyCode_c:99,KeyCode_C:67,KeyCode_V:86,KeyCode_v:118},o=this.state.selected.rowIdx,r=this.props.rowGetter(o),s=this.state.selected.idx,i=this.getColumn(s);if(d.canEdit(i,r,this.props.enableCellSelect))if(e.keyCode===t.KeyCode_c||e.keyCode===t.KeyCode_C){var n=this.getSelectedValue();this.handleCopy({value:n})}else e.keyCode!==t.KeyCode_v&&e.keyCode!==t.KeyCode_V||this.handlePaste()},onCellCommit:function(e){var t=Object.assign({},this.state.selected);t.active=!1,"Tab"===e.key&&(t.idx+=1);var o=this.state.expandedRows;this.setState({selected:t,expandedRows:o}),this.props.onRowUpdated&&this.props.onRowUpdated(e);var r=e.rowIdx;this.props.onGridRowsUpdated&&this.props.onGridRowsUpdated({cellKey:e.cellKey,fromRow:r,toRow:r,updated:e.updated,action:"cellUpdate"})},onDragStart:function(e){var t=this.getSelectedValue();this.handleDragStart({idx:this.state.selected.idx,rowIdx:this.state.selected.rowIdx,value:t}),e&&e.dataTransfer&&e.dataTransfer.setData&&(e.dataTransfer.dropEffect="move",e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain","dummy"))},onToggleFilter:function(){var e=this;this.setState({canFilter:!this.state.canFilter},function(){e.state.canFilter===!1&&e.props.onClearFilters&&e.props.onClearFilters()})},onDragHandleDoubleClick:function(e){if(this.props.onDragHandleDoubleClick&&this.props.onDragHandleDoubleClick(e),this.props.onGridRowsUpdated){var t,o=this.getColumn(e.idx).key,r=(t={},t[o]=e.rowData[o],t);this.props.onGridRowsUpdated({cellKey:o,fromRow:e.rowIdx,toRow:this.props.rowsCount-1,updated:r,action:"columnFill"})}},onCellExpand:function(e){this.props.onCellExpand&&this.props.onCellExpand(e)},onRowExpandToggle:function(e){"function"==typeof this.props.onRowExpandToggle&&this.props.onRowExpandToggle(e)},handleDragStart:function(e){if(this.dragEnabled()){var t=e.idx,o=e.rowIdx;t>=0&&o>=0&&t<this.getSize()&&o<this.props.rowsCount&&this.setState({dragged:e})}},handleDragEnd:function(){if(this.dragEnabled()){var e=void 0,t=void 0,o=this.state.selected,r=this.state.dragged,s=this.getColumn(this.state.selected.idx).key;if(e=o.rowIdx<r.overRowIdx?o.rowIdx:r.overRowIdx,t=o.rowIdx>r.overRowIdx?o.rowIdx:r.overRowIdx,this.props.onCellsDragged&&this.props.onCellsDragged({cellKey:s,fromRow:e,toRow:t,value:r.value}),this.props.onGridRowsUpdated){var i,n=(i={},i[s]=r.value,i);this.props.onGridRowsUpdated({cellKey:s,fromRow:e,toRow:t,updated:n,action:"cellDrag"})}this.setState({dragged:{complete:!0}})}},handleDragEnter:function(e){if(this.dragEnabled()){var t=this.state.dragged;t.overRowIdx=e,this.setState({dragged:t})}},handleTerminateDrag:function(){this.dragEnabled()&&this.setState({dragged:null})},handlePaste:function(){if(this.copyPasteEnabled()){var e=this.state.selected,t=this.getColumn(this.state.selected.idx).key,o=this.state.textToCopy,r=e.rowIdx;if(this.props.onCellCopyPaste&&this.props.onCellCopyPaste({cellKey:t,rowIdx:r,value:o,fromRow:this.state.copied.rowIdx,toRow:r}),this.props.onGridRowsUpdated){var s,i=(s={},s[t]=o,s);this.props.onGridRowsUpdated({cellKey:t,fromRow:r,toRow:r,updated:i,action:"copyPaste"})}this.setState({copied:null})}},handleCopy:function(e){if(this.copyPasteEnabled()){var t=e.value,o=this.state.selected,r={idx:o.idx,rowIdx:o.rowIdx};this.setState({textToCopy:t,copied:r})}},handleSort:function(e,t){this.setState({sortDirection:t,sortColumn:e},function(){this.props.onGridSort(e,t)})},getSelectedRow:function(e,t){var o=this,r=e.filter(function(e){return e[o.props.rowKey]===t});if(r.length>0)return r[0]},handleRowSelect:function(e,t,o,r){r.stopPropagation();var s="single"===this.props.enableRowSelect?[]:this.state.selectedRows.slice(0),i=this.getSelectedRow(s,o[this.props.rowKey]);i?i.isSelected=!i.isSelected:(o.isSelected=!0,s.push(o)),this.setState({selectedRows:s,selected:{rowIdx:e,idx:0}}),this.props.onRowSelect&&this.props.onRowSelect(s.filter(function(e){return e.isSelected===!0}))},handleCheckboxChange:function(e){var t=void 0;t=e.currentTarget instanceof HTMLInputElement&&e.currentTarget.checked===!0;for(var o=[],r=0;r<this.props.rowsCount;r++){var s=Object.assign({},this.props.rowGetter(r),{isSelected:t});o.push(s)}this.setState({selectedRows:o}),"function"==typeof this.props.onRowSelect&&this.props.onRowSelect(o.filter(function(e){return e.isSelected===!0}))},getScrollOffSet:function(){var e=0,t=i.findDOMNode(this).querySelector(".react-grid-Canvas");t&&(e=t.offsetWidth-t.clientWidth),this.setState({scrollOffset:e})},getRowOffsetHeight:function(){var e=0;return this.getHeaderRows().forEach(function(t){return e+=parseFloat(t.height,10)}),e},getHeaderRows:function(){var e=[{ref:"row",height:this.props.headerRowHeight||this.props.rowHeight,rowType:"header"}];return this.state.canFilter===!0&&e.push({ref:"filterRow",filterable:!0,onFilterChange:this.props.onAddFilter,height:45,rowType:"filter"}),e},getInitialSelectedRows:function(){for(var e=[],t=0;t<this.props.rowsCount;t++)e.push(!1);return e},getSelectedValue:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx,o=this.getColumn(t).key,r=this.props.rowGetter(e);return u.get(r,o)},moveSelectedCell:function(e,t,o){e.preventDefault();var r=void 0,s=void 0,i=this.props.cellNavigationMode;if("none"!==i){var n=this.calculateNextSelectionPosition(i,o,t);s=n.idx,r=n.rowIdx}else r=this.state.selected.rowIdx+t,s=this.state.selected.idx+o;this.onSelect({idx:s,rowIdx:r})},getNbrColumns:function(){var e=this.props,t=e.columns,o=e.enableRowSelect;return o?t.length+1:t.length},calculateNextSelectionPosition:function(e,t,o){var r=o,s=this.state.selected.idx+t,i=this.getNbrColumns();t>0?this.isAtLastCellInRow(i)&&("changeRow"===e?(r=this.isAtLastRow()?o:o+1,s=this.isAtLastRow()?s:0):s=0):t<0&&this.isAtFirstCellInRow()&&("changeRow"===e?(r=this.isAtFirstRow()?o:o-1,s=this.isAtFirstRow()?0:i-1):s=i-1);var n=this.state.selected.rowIdx+r;return{idx:s,rowIdx:n}},isAtLastCellInRow:function(e){return this.state.selected.idx===e-1},isAtLastRow:function(){return this.state.selected.rowIdx===this.props.rowsCount-1},isAtFirstCellInRow:function(){return 0===this.state.selected.idx},isAtFirstRow:function(){return 0===this.state.selected.rowIdx},openCellEditor:function(e,t){var o=this,r=this.props.rowGetter(e),s=this.getColumn(t);if(d.canEdit(s,r,this.props.enableCellSelect)){var i={rowIdx:e,idx:t};this.hasSelectedCellChanged(i)?this.setState({selected:i},function(){o.setActive("Enter")}):this.setActive("Enter")}},setActive:function(e){var t=this.state.selected.rowIdx,o=this.props.rowGetter(t),r=this.state.selected.idx,s=this.getColumn(r);if(d.canEdit(s,o,this.props.enableCellSelect)&&!this.isActive()){var i=Object.assign(this.state.selected,{idx:r,rowIdx:t,active:!0,initialKeyCode:e});this.setState({selected:i})}},setInactive:function(){var e=this.state.selected.rowIdx,t=this.props.rowGetter(e),o=this.state.selected.idx,r=this.getColumn(o);if(d.canEdit(r,t,this.props.enableCellSelect)&&this.isActive()){var s=Object.assign(this.state.selected,{idx:o,rowIdx:e,active:!1});this.setState({selected:s})}},isActive:function(){return this.state.selected.active===!0},setupGridColumns:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=e.columns.slice(0),o={};if(e.enableRowSelect){var r="single"===e.enableRowSelect?null:s.createElement("div",{className:"react-grid-checkbox-container"},s.createElement("input",{className:"react-grid-checkbox",type:"checkbox",name:"select-all-checkbox",id:"select-all-checkbox",onChange:this.handleCheckboxChange}),s.createElement("label",{htmlFor:"select-all-checkbox",className:"react-grid-checkbox-label"})),i={key:"select-row",name:"",formatter:s.createElement(a,null),onCellChange:this.handleRowSelect,filterable:!1,headerRenderer:r,width:60,locked:!0,getRowMetaData:function(e){return e}};o=t.unshift(i),t=o>0?t:o}return t},copyPasteEnabled:function(){return null!==this.props.onCellCopyPaste},dragEnabled:function(){return null!==this.props.onCellsDragged},renderToolbar:function(){var e=this.props.toolbar;if(s.isValidElement(e))return s.cloneElement(e,{columns:this.props.columns,onToggleFilter:this.onToggleFilter,numberOfRows:this.props.rowsCount})},render:function(){var e={selected:this.state.selected,dragged:this.state.dragged,onCellClick:this.onCellClick,onCellContextMenu:this.onCellContextMenu,onCellDoubleClick:this.onCellDoubleClick,onCommit:this.onCellCommit,onCommitCancel:this.setInactive,copied:this.state.copied,handleDragEnterRow:this.handleDragEnter,handleTerminateDrag:this.handleTerminateDrag,enableCellSelect:this.props.enableCellSelect,onColumnEvent:this.onColumnEvent,openCellEditor:this.openCellEditor,onDragHandleDoubleClick:this.onDragHandleDoubleClick,onCellExpand:this.onCellExpand,onRowExpandToggle:this.onRowExpandToggle},t=this.renderToolbar(),o=this.props.minWidth||this.DOMMetrics.gridWidth(),i=o-this.state.scrollOffset;return("undefined"==typeof o||isNaN(o)||0===o)&&(o="100%"),("undefined"==typeof i||isNaN(i)||0===i)&&(i="100%"),s.createElement("div",{className:"react-grid-Container",style:{width:o}},t,s.createElement("div",{className:"react-grid-Main"},s.createElement(n,r({ref:"base"},this.props,{rowKey:this.props.rowKey,headerRows:this.getHeaderRows(),columnMetrics:this.state.columnMetrics,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,rowHeight:this.props.rowHeight,cellMetaData:e,selectedRows:this.state.selectedRows.filter(function(e){return e.isSelected===!0}),expandedRows:this.state.expandedRows,rowOffsetHeight:this.getRowOffsetHeight(),sortColumn:this.state.sortColumn,sortDirection:this.state.sortDirection,onSort:this.handleSort,minHeight:this.props.minHeight,totalWidth:i,onViewportKeydown:this.onKeyDown,onViewportDragStart:this.onDragStart,onViewportDragEnd:this.handleDragEnd,onViewportDoubleClick:this.onViewportDoubleClick,onColumnResize:this.onColumnResize,rowScrollTimeout:this.props.rowScrollTimeout,contextMenu:this.props.contextMenu}))))}});e.exports=h},function(e,t,o){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},s=o(1),i=o(20),n=s.createClass({displayName:"ResizeHandle",style:{position:"absolute",top:0,right:0,width:6,height:"100%"},render:function(){return s.createElement(i,r({},this.props,{className:"react-grid-HeaderCell__resizeHandle",style:this.style}))}});e.exports=n},function(e,t,o){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function n(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var l=o(1),a=r(l),c=o(2),p=r(c),u=o(3),d=r(u),h=function(e){function t(){s(this,t);var o=i(this,e.call(this));return o.checkFocus=o.checkFocus.bind(o),o.isSelected=o.isSelected.bind(o),o.onClick=o.onClick.bind(o),o.onRowExpandToggle=o.onRowExpandToggle.bind(o),o.onKeyDown=o.onKeyDown.bind(o),o.onRowExpandClick=o.onRowExpandClick.bind(o),o}return n(t,e),t.prototype.componentDidMount=function(){this.checkFocus()},t.prototype.componentDidUpdate=function(){this.checkFocus()},t.prototype.isSelected=function(){var e=this.props.cellMetaData;return null!=e&&(e.selected&&e.selected.rowIdx===this.props.idx)},t.prototype.onClick=function(e){var t=this.props.cellMetaData;null!=t&&t.onCellClick&&"function"==typeof t.onCellClick&&t.onCellClick({rowIdx:this.props.idx,idx:0},e)},t.prototype.onKeyDown=function(e){"ArrowLeft"===e.key&&this.onRowExpandToggle(!1),"ArrowRight"===e.key&&this.onRowExpandToggle(!0),"Enter"===e.key&&this.onRowExpandToggle(!this.props.isExpanded)},t.prototype.onRowExpandClick=function(){this.onRowExpandToggle(!this.props.isExpanded)},t.prototype.onRowExpandToggle=function(e){var t=null==e?!this.props.isExpanded:e,o=this.props.cellMetaData;null!=o&&o.onRowExpandToggle&&"function"==typeof o.onRowExpandToggle&&o.onRowExpandToggle({rowIdx:this.props.idx,shouldExpand:t,columnGroupName:this.props.columnGroupName,name:this.props.name})},t.prototype.getClassName=function(){return(0,d["default"])("react-grid-row-group","react-grid-Row",{"row-selected":this.isSelected()})},t.prototype.checkFocus=function(){this.isSelected()&&p["default"].findDOMNode(this).focus()},t.prototype.render=function(){var e=this.props.treeDepth||0,t=20*e,o={height:"50px",overflow:"hidden",border:"1px solid #dddddd",paddingTop:"15px",paddingLeft:"5px"};return a["default"].createElement("div",{style:o,className:this.getClassName(),onClick:this.onClick,onKeyDown:this.onKeyDown,tabIndex:-1},a["default"].createElement("span",{className:"row-expand-icon",style:{"float":"left",marginLeft:t,cursor:"pointer"},onClick:this.onRowExpandClick},this.props.isExpanded?String.fromCharCode("9660"):String.fromCharCode("9658")),a["default"].createElement("strong",null,this.props.columnGroupName," : ",this.props.name))},t}(l.Component);h.propTypes={name:l.PropTypes.string.isRequired,columnGroupName:l.PropTypes.string.isRequired,isExpanded:l.PropTypes.bool.isRequired,treeDepth:l.PropTypes.number.isRequired,height:l.PropTypes.number.isRequired,cellMetaData:l.PropTypes.object,idx:l.PropTypes.number.isRequired},t["default"]=h},function(e,t){"use strict";var o={get:function(e,t){return"function"==typeof e.get?e.get(t):e[t]}};e.exports=o},function(e,t,o){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function n(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0,t.SimpleRowsContainer=void 0;var l=o(1),a=r(l),c=function(e){return a["default"].createElement("div",{style:{width:e.width,overflow:"hidden"}},e.rows)};c.propTypes={width:l.PropTypes.number,rows:l.PropTypes.array};var p=function(e){function t(o){s(this,t);var r=i(this,e.call(this,o));return r.plugins=o.window?o.window.ReactDataGridPlugins:window.ReactDataGridPlugins,r.hasContextMenu=r.hasContextMenu.bind(r),r.renderRowsWithContextMenu=r.renderRowsWithContextMenu.bind(r),r.getContextMenuContainer=r.getContextMenuContainer.bind(r),r.state={ContextMenuContainer:r.getContextMenuContainer(o)},r}return n(t,e),t.prototype.getContextMenuContainer=function(){if(this.hasContextMenu()){if(!this.plugins)throw new Error("You need to include ReactDataGrid UiPlugins in order to initialise context menu");
return this.plugins.Menu.ContextMenuLayer("reactDataGridContextMenu")(c)}},t.prototype.hasContextMenu=function(){return this.props.contextMenu&&a["default"].isValidElement(this.props.contextMenu)},t.prototype.renderRowsWithContextMenu=function(){var e=this.state.ContextMenuContainer,t={rowIdx:this.props.rowIdx,idx:this.props.idx},o=a["default"].cloneElement(this.props.contextMenu,t);return a["default"].createElement("div",null,a["default"].createElement(e,this.props),o)},t.prototype.render=function(){return this.hasContextMenu()?this.renderRowsWithContextMenu():a["default"].createElement(c,this.props)},t}(a["default"].Component);p.propTypes={contextMenu:l.PropTypes.element,rowIdx:l.PropTypes.number,idx:l.PropTypes.number,window:l.PropTypes.object},t["default"]=p,t.SimpleRowsContainer=c},function(e,t,o){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var s=o(2),i=r(s),n={appendScrollShim:function(){if(!this._scrollShim){var e=this._scrollShimSize(),t=document.createElement("div");t.classList?t.classList.add("react-grid-ScrollShim"):t.className+=" react-grid-ScrollShim",t.style.position="absolute",t.style.top=0,t.style.left=0,t.style.width=e.width+"px",t.style.height=e.height+"px",i["default"].findDOMNode(this).appendChild(t),this._scrollShim=t}this._scheduleRemoveScrollShim()},_scrollShimSize:function(){return{width:this.props.width,height:this.props.length*this.props.rowHeight}},_scheduleRemoveScrollShim:function(){this._scheduleRemoveScrollShimTimer&&clearTimeout(this._scheduleRemoveScrollShimTimer),this._scheduleRemoveScrollShimTimer=setTimeout(this._removeScrollShim,200)},_removeScrollShim:function(){this._scrollShim&&(this._scrollShim.parentNode.removeChild(this._scrollShim),this._scrollShim=void 0)}};e.exports=n},function(e,t,o){"use strict";var r=o(1),s=o(17),i=o(34),n=o(6),l=r.PropTypes,a=r.createClass({displayName:"Viewport",mixins:[i],propTypes:{rowOffsetHeight:l.number.isRequired,totalWidth:l.oneOfType([l.number,l.string]).isRequired,columnMetrics:l.object.isRequired,rowGetter:l.oneOfType([l.array,l.func]).isRequired,selectedRows:l.array,expandedRows:l.array,rowRenderer:l.func,rowsCount:l.number.isRequired,rowHeight:l.number.isRequired,onRows:l.func,onScroll:l.func,minHeight:l.number,cellMetaData:l.shape(n),rowKey:l.string.isRequired,rowScrollTimeout:l.number,contextMenu:l.element,getSubRowDetails:l.func},onScroll:function(e){this.updateScroll(e.scrollTop,e.scrollLeft,this.state.height,this.props.rowHeight,this.props.rowsCount),this.props.onScroll&&this.props.onScroll({scrollTop:e.scrollTop,scrollLeft:e.scrollLeft})},getScroll:function(){return this.refs.canvas.getScroll()},setScrollLeft:function(e){this.refs.canvas.setScrollLeft(e)},render:function(){var e={padding:0,bottom:0,left:0,right:0,overflow:"hidden",position:"absolute",top:this.props.rowOffsetHeight};return r.createElement("div",{className:"react-grid-Viewport",style:e},r.createElement(s,{ref:"canvas",rowKey:this.props.rowKey,totalWidth:this.props.totalWidth,width:this.props.columnMetrics.width,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columns:this.props.columnMetrics.columns,rowRenderer:this.props.rowRenderer,displayStart:this.state.displayStart,displayEnd:this.state.displayEnd,cellMetaData:this.props.cellMetaData,height:this.state.height,rowHeight:this.props.rowHeight,onScroll:this.onScroll,onRows:this.props.onRows,rowScrollTimeout:this.props.rowScrollTimeout,contextMenu:this.props.contextMenu,getSubRowDetails:this.props.getSubRowDetails}))}});e.exports=a},function(e,t,o){"use strict";var r=o(1),s=o(2),i=o(7),n=Math.min,l=Math.max,a=Math.floor,c=Math.ceil;e.exports={mixins:[i.MetricsMixin],DOMMetrics:{viewportHeight:function(){return s.findDOMNode(this).offsetHeight}},propTypes:{rowHeight:r.PropTypes.number,rowsCount:r.PropTypes.number.isRequired},getDefaultProps:function(){return{rowHeight:30}},getInitialState:function(){return this.getGridState(this.props)},getGridState:function(e){var t=c((e.minHeight-e.rowHeight)/e.rowHeight),o=n(2*t,e.rowsCount);return{displayStart:0,displayEnd:o,height:e.minHeight,scrollTop:0,scrollLeft:0}},updateScroll:function(e,t,o,r,s){var i=c(o/r),p=a(e/r),u=n(p+i,s),d=l(0,p-2*i),h=n(p+2*i,s),f={visibleStart:p,visibleEnd:u,displayStart:d,displayEnd:h,height:o,scrollTop:e,scrollLeft:t};this.setState(f)},metricsUpdated:function(){var e=this.DOMMetrics.viewportHeight();e&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,e,this.props.rowHeight,this.props.rowsCount)},componentWillReceiveProps:function(e){if(this.props.rowHeight!==e.rowHeight||this.props.minHeight!==e.minHeight)this.setState(this.getGridState(e));else if(this.props.rowsCount!==e.rowsCount)this.updateScroll(this.state.scrollTop,this.state.scrollLeft,this.state.height,e.rowHeight,e.rowsCount);else if(this.props.rowOffsetHeight!==e.rowOffsetHeight){var t=this.props.rowOffsetHeight-e.rowOffsetHeight;this.updateScroll(this.state.scrollTop,this.state.scrollLeft,this.state.height+t,e.rowHeight,e.rowsCount)}}}},function(e,t,o){"use strict";var r=o(1),s=o(5),i=r.createClass({displayName:"FilterableHeaderCell",propTypes:{onChange:r.PropTypes.func.isRequired,column:r.PropTypes.shape(s)},getInitialState:function(){return{filterTerm:""}},handleChange:function(e){var t=e.target.value;this.setState({filterTerm:t}),this.props.onChange({filterTerm:t,columnKey:this.props.column.key})},renderInput:function(){if(this.props.column.filterable===!1)return r.createElement("span",null);var e="header-filter-"+this.props.column.key;return r.createElement("input",{key:e,type:"text",className:"form-control input-sm",placeholder:"Search",value:this.state.filterTerm,onChange:this.handleChange})},render:function(){return r.createElement("div",null,r.createElement("div",{className:"form-group"},this.renderInput()))}});e.exports=i},function(e,t,o){"use strict";var r=o(1),s=o(3),i={ASC:"ASC",DESC:"DESC",NONE:"NONE"},n=r.createClass({displayName:"SortableHeaderCell",propTypes:{columnKey:r.PropTypes.string.isRequired,column:r.PropTypes.shape({name:r.PropTypes.node}),onSort:r.PropTypes.func.isRequired,sortDirection:r.PropTypes.oneOf(["ASC","DESC","NONE"])},onClick:function(){var e=void 0;switch(this.props.sortDirection){default:case null:case void 0:case i.NONE:e=i.ASC;break;case i.ASC:e=i.DESC;break;case i.DESC:e=i.NONE}this.props.onSort(this.props.columnKey,e)},getSortByText:function(){var e={ASC:"9650",DESC:"9660",NONE:""};return String.fromCharCode(e[this.props.sortDirection])},render:function(){var e=s({"react-grid-HeaderCell-sortable":!0,"react-grid-HeaderCell-sortable--ascending":"ASC"===this.props.sortDirection,"react-grid-HeaderCell-sortable--descending":"DESC"===this.props.sortDirection});return r.createElement("div",{className:e,onClick:this.onClick,style:{cursor:"pointer"}},this.props.column.name,r.createElement("span",{className:"pull-right"},this.getSortByText()))}});e.exports=n},function(e,t,o){"use strict";var r=o(1),s=r.createClass({displayName:"CheckboxEditor",propTypes:{value:r.PropTypes.bool,rowIdx:r.PropTypes.number,column:r.PropTypes.shape({key:r.PropTypes.string,onCellChange:r.PropTypes.func}),dependentValues:r.PropTypes.object},handleChange:function(e){this.props.column.onCellChange(this.props.rowIdx,this.props.column.key,this.props.dependentValues,e)},render:function(){var e=null!=this.props.value&&this.props.value,t="checkbox"+this.props.rowIdx;return r.createElement("div",{className:"react-grid-checkbox-container",onClick:this.handleChange},r.createElement("input",{className:"react-grid-checkbox",type:"checkbox",name:t,checked:e}),r.createElement("label",{htmlFor:t,className:"react-grid-checkbox-label"}))}});e.exports=s},function(e,t,o){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var n=o(1),l=o(2),a=o(5),c=function(e){function t(){return r(this,t),s(this,e.apply(this,arguments))}return i(t,e),t.prototype.getStyle=function(){return{width:"100%"}},t.prototype.getValue=function(){var e={};return e[this.props.column.key]=this.getInputNode().value,e},t.prototype.getInputNode=function(){var e=l.findDOMNode(this);return"INPUT"===e.tagName?e:e.querySelector("input:not([type=hidden])")},t.prototype.inheritContainerStyles=function(){return!0},t}(n.Component);c.propTypes={onKeyDown:n.PropTypes.func.isRequired,value:n.PropTypes.any.isRequired,onBlur:n.PropTypes.func.isRequired,column:n.PropTypes.shape(a).isRequired,commit:n.PropTypes.func.isRequired},e.exports=c},function(e,t,o){"use strict";var r=o(1),s=o(3),i=o(12),n=o(40),l=o(13),a=r.createClass({displayName:"EditorContainer",mixins:[i],propTypes:{rowIdx:r.PropTypes.number,rowData:r.PropTypes.object.isRequired,value:r.PropTypes.oneOfType([r.PropTypes.string,r.PropTypes.number,r.PropTypes.object,r.PropTypes.bool]).isRequired,cellMetaData:r.PropTypes.shape({selected:r.PropTypes.object.isRequired,copied:r.PropTypes.object,dragged:r.PropTypes.object,onCellClick:r.PropTypes.func,onCellDoubleClick:r.PropTypes.func,onCommitCancel:r.PropTypes.func,onCommit:r.PropTypes.func}).isRequired,column:r.PropTypes.object.isRequired,height:r.PropTypes.number.isRequired},changeCommitted:!1,getInitialState:function(){return{isInvalid:!1}},componentDidMount:function(){var e=this.getInputNode();void 0!==e&&(this.setTextInputFocus(),this.getEditor().disableContainerStyles||(e.className+=" editor-main",e.style.height=this.props.height-1+"px"))},componentWillUnmount:function(){this.changeCommitted||this.hasEscapeBeenPressed()||this.commit({key:"Enter"})},createEditor:function(){var e=this,t=function(t){return e.editor=t},o={ref:t,column:this.props.column,value:this.getInitialValue(),onCommit:this.commit,rowMetaData:this.getRowMetaData(),rowData:this.props.rowData,height:this.props.height,onBlur:this.commit,onOverrideKeyDown:this.onKeyDown},s=this.props.column.editor;return s&&r.isValidElement(s)?r.cloneElement(s,o):r.createElement(n,{ref:t,column:this.props.column,value:this.getInitialValue(),onBlur:this.commit,rowMetaData:this.getRowMetaData(),onKeyDown:function(){},commit:function(){}})},onPressEnter:function(){this.commit({key:"Enter"})},onPressTab:function(){this.commit({key:"Tab"})},onPressEscape:function(e){this.editorIsSelectOpen()?e.stopPropagation():this.props.cellMetaData.onCommitCancel()},onPressArrowDown:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowUp:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowLeft:function(e){this.isCaretAtBeginningOfInput()?this.commit(e):e.stopPropagation()},onPressArrowRight:function(e){this.isCaretAtEndOfInput()?this.commit(e):e.stopPropagation()},editorHasResults:function(){return!!l(this.getEditor().hasResults)&&this.getEditor().hasResults()},editorIsSelectOpen:function(){return!!l(this.getEditor().isSelectOpen)&&this.getEditor().isSelectOpen()},getRowMetaData:function(){if("function"==typeof this.props.column.getRowMetaData)return this.props.column.getRowMetaData(this.props.rowData,this.props.column)},getEditor:function(){return this.editor},getInputNode:function(){return this.getEditor().getInputNode()},getInitialValue:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode;if("Delete"===t||"Backspace"===t)return"";if("Enter"===t)return this.props.value;var o=t?String.fromCharCode(t):this.props.value;return o},getContainerClass:function(){return s({"has-error":this.state.isInvalid===!0})},commit:function(e){var t=e||{},o=this.getEditor().getValue();if(this.isNewValueValid(o)){this.changeCommitted=!0;var r=this.props.column.key;this.props.cellMetaData.onCommit({cellKey:r,rowIdx:this.props.rowIdx,updated:o,key:t.key})}},isNewValueValid:function(e){if(l(this.getEditor().validate)){var t=this.getEditor().validate(e);return this.setState({isInvalid:!t}),t}return!0},setCaretAtEndOfInput:function(){var e=this.getInputNode(),t=e.value.length;if(e.setSelectionRange)e.setSelectionRange(t,t);else if(e.createTextRange){var o=e.createTextRange();o.moveStart("character",t),o.collapse(),o.select()}},isCaretAtBeginningOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.selectionEnd&&0===e.selectionStart},isCaretAtEndOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.value.length},setTextInputFocus:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode,o=this.getInputNode();o.focus(),"INPUT"===o.tagName&&(this.isKeyPrintable(t)?o.select():(o.focus(),o.select()))},hasEscapeBeenPressed:function(){var e=!1,t=27;return window.event&&(window.event.keyCode===t?e=!0:window.event.which===t&&(e=!0)),e},renderStatusIcon:function(){if(this.state.isInvalid===!0)return r.createElement("span",{className:"glyphicon glyphicon-remove form-control-feedback"})},render:function(){return r.createElement("div",{className:this.getContainerClass(),onKeyDown:this.onKeyDown,commit:this.commit},this.createEditor(),this.renderStatusIcon())}});e.exports=a},function(e,t,o){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var n=o(1),l=o(38),a=function(e){function t(){return r(this,t),s(this,e.apply(this,arguments))}return i(t,e),t.prototype.render=function(){return n.createElement("input",{ref:"input",type:"text",onBlur:this.props.onBlur,className:"form-control",defaultValue:this.props.value})},t}(l);e.exports=a},function(e,t,o){"use strict";var r=o(1),s=r.createClass({displayName:"SimpleCellFormatter",propTypes:{value:r.PropTypes.oneOfType([r.PropTypes.string,r.PropTypes.number,r.PropTypes.object,r.PropTypes.bool]).isRequired},shouldComponentUpdate:function(e){return e.value!==this.props.value},render:function(){return r.createElement("div",{title:this.props.value},this.props.value)}});e.exports=s}])}); |
ajax/libs/flocks.js/1.6.0/flocks.js | tonytomov/cdnjs |
/** @jsx React.DOM */
/* jshint node: true, browser: true, newcap: false */
/* eslint max-statements: 0, no-else-return: 0, brace-style: 0 */
/* eslint-env node,browser */
/**
* The Flocks library module. Load this module and use either the
* flocks <tt>flocks.createClass</tt> wrapper or the <tt>flocks plumbing</tt>
* mixin to create <tt>flocks controls</tt>. Place them into your document
* using <tt>flocks.mount</tt>, and use the returned function or the data and
* method that the mixin provides, <tt>this.fctx</tt> and <tt>this.fset()</tt>
* respectively, to read and write to the <tt>flocks state</tt>.
*
* And suddenly you're done.
*
* Please see the <a href="http://flocks.rocks/what_is_flocks.html" target="_blank">tutorials</a>
* for more information.
*
* @module flocks
* @main createClass
* @class flocks
*/
// if it's in a <script> it's defined already
// otherwise assume commonjs
/* eslint-disable no-use-before-define, vars-on-top */
if (typeof React === "undefined") {
var React = require("react");
}
/* eslint-enable no-use-before-define, vars-on-top */
// wrap the remainder
(function() {
"use strict";
var Mixin,
exports,
initialized = false,
updateBlocks = 0,
tagtype,
/* eslint-disable no-unused-vars */
dirty = false,
handler = function(Ignored) { return true; },
/* eslint-ensable no-unused-vars */
finalizer = function() { return true; },
prevFCtx = {},
nextFCtx = {},
flocks2Ctxs = { "flocks2context" : React.PropTypes.object };
// ... lol
function arrayMember(Item, Array) {
return (!!(~( Array.indexOf(Item, 0) )));
}
function isArray(maybeArray) {
return (Object.prototype.toString.call(maybeArray) === "[object Array]");
}
function isUndefined(maybeUndefined) {
return (typeof maybeUndefined === "undefined");
}
function isStringOfNonNegInt(maybeIntStr) {
if (typeof maybeIntStr !== "string") { return false; }
return /^(0|[1-9]\d*)$/.test(maybeIntStr);
}
function isNonArrayObject(maybeArray) {
if (typeof maybeArray !== "object") { return false; }
if (Object.prototype.toString.call(maybeArray) === "[object Array]") { return false; }
return true;
}
function flocksLog(Level, Message) {
if (typeof Level === "string") {
if (arrayMember(Level, ["warn","debug","error","log","info","exception","assert"])) {
console[Level]("Flocks2 [" + Level + "] " + Message.toString());
} else {
console.log("Flocks2 [Unknown level] " + Message.toString());
}
} else if (isUndefined(nextFCtx.flocks2Config)) {
console.log("Flocks2 pre-config [" + Level.toString() + "] " + Message.toString());
} else if (nextFCtx.flocks2Config.log_level >= Level) {
console.log("Flocks2 [" + Level.toString() + "] " + Message.toString());
}
}
function attemptUpdate() {
flocksLog(3, " - Flocks2 attempting update");
dirty = true;
if (!(initialized)) {
flocksLog(1, " x Flocks2 skipped update: root is not initialized");
return null;
}
if (updateBlocks) {
flocksLog(1, " x Flocks2 skipped update: lock count updateBlocks is non-zero");
return null;
}
/* todo see issue #9 https://github.com/StoneCypher/flocks.js/issues/9
if (deepCompare(nextFCtx, prevFCtx)) {
flocksLog(2, " x Flocks2 skipped update: no update to state");
return true;
}
*/
if (!(handler(nextFCtx))) {
flocksLog(0, " ! Flocks2 rolling back update: handler rejected propset");
nextFCtx = prevFCtx;
dirty = false;
return null;
}
prevFCtx = nextFCtx;
flocksLog(3, " - Flocks2 update passed");
if (prevFCtx.flocks2Config.target === 'detatched') {
flocksLog(3, " - Flocks2 skipping render because explicitly detatched");
} else {
flocksLog(3, " - Flocks2 rendering");
React.render( React.createFactory(tagtype)( { "flocks2context" : nextFCtx } ), prevFCtx.flocks2Config.target );
}
dirty = false;
flocksLog(3, " - Flocks2 update complete; finalizing");
finalizer();
return true;
}
function enforceString(On, Label) {
if (typeof On !== "string") {
throw Label || "Argument must be a string";
}
}
function enforceArray(On, Label) {
if (!isArray(On)) {
throw Label || "Argument must be an array";
}
}
function enforceNonArrayObject(On, Label) {
if (!isNonArrayObject(On)) {
throw Label || "Argument must be a non-array object";
}
}
function setByKey(Key, MaybeValue) {
enforceString(Key, "Flocks2 set/2 must take a string for its key");
nextFCtx[Key] = MaybeValue;
flocksLog(1, " - Flocks2 setByKey \"" + Key + "\"");
attemptUpdate();
}
function setTargetByPath(Path, Target, NewVal) {
var NextPath,
OldVal; // it gets hoisted anyway, so it triggers eslint warnings when inlined
// might as well be explicit about it
if (!(isArray(Path))) { throw "Path must be an array!"; }
if (Path.length === 0) {
OldVal = Target;
Target = NewVal;
return OldVal;
}
if (Path.length === 1) {
OldVal = Target[Path[0]];
Target[Path[0]] = NewVal;
return OldVal;
}
if (["string","number"].indexOf(typeof Path[0]) !== -1) {
NextPath = Path.splice(1, Number.MAX_VALUE);
return setTargetByPath(NextPath, Target[Path[0]], NewVal);
}
}
function setByPath(Path, NewVal) {
enforceArray(Path, "Flocks2 setByPathh/2 must take an array for its key");
flocksLog(1, " - Flocks2 setByPath \"" + Path.join("|") + "\"");
setTargetByPath(Path, nextFCtx, NewVal);
attemptUpdate();
}
// todo
// function setByObject(Key, MaybeValue) {
// flocksLog(0, " - Flocks2 setByObject stub");
// attemptUpdate();
// }
function set(Key, MaybeValue) {
flocksLog(3, " - Flocks2 multi-set");
if (typeof Key === "string") { return setByKey(Key, MaybeValue); }
else if (isArray(Key)) { return setByPath(Key, MaybeValue); }
// else if (isNonArrayObject(Key)) { return setByObject(Key); } // todo
else { throw "Flocks2 set/1,2 key must be a string or an array"; }
}
function getByKey(Key) {
return prevFCtx[Key];
}
function getByPathImpl(Path, Target) {
var NextPath;
if (!(isArray(Path))) { throw "path must be an array!"; }
if (Path.length === 0) {
return Target;
}
if (Path.length === 1) {
return Target[Path[0]];
}
if (["string","number"].indexOf(typeof Path[0]) !== -1) {
NextPath = Path.splice(1, Number.MAX_VALUE);
return getByPathImpl(NextPath, Target[Path[0]]);
}
}
function getByPath(Path) {
return getByPathImpl(Path, prevFCtx);
}
function get(Key) {
flocksLog(3, " - Flocks2 multi-get");
if (typeof Key === "string") { return getByKey(Key); }
else if (isArray(Key)) { return getByPath(Key); }
else { throw "Flocks2 get/1 key must be a string or an array"; }
}
function update(SparseObject) {
// todo
console.log("ERROR: stub called!");
enforceNonArrayObject(SparseObject, "Flocks2 update/1 must take a plain object");
}
function lock() {
++updateBlocks;
}
function unlock() {
if (updateBlocks <= 0) { throw "unlock()ed with no lock!"; }
--updateBlocks;
attemptUpdate();
}
function clone(obj) {
var copy = obj.constructor(),
attr;
if ((obj === null) || (typeof obj !== "object")) { return obj; }
for (attr in obj) {
if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; }
}
return copy;
}
function create(iFlocksConfig, iFlocksData) {
var FlocksConfig = iFlocksConfig || {},
FlocksData = iFlocksData || {},
target = FlocksConfig.target || document.body,
stub = function() { console.log("ERROR: stub called!"); attemptUpdate(); }, // todo
updater = {
"override" : stub, // todo
"clear" : stub, // todo
"get" : get,
"get_key" : getByKey,
"get_path" : getByPath,
"set" : set,
"set_path" : setByPath,
"update" : update,
"lock" : lock,
"unlock" : unlock
};
FlocksConfig.log_level = FlocksConfig.log_level || -1;
tagtype = FlocksConfig.control;
FlocksData.flocks2Config = FlocksConfig;
nextFCtx = FlocksData;
flocksLog(1, "Flocks2 root creation begins");
if (!(tagtype)) {
throw "Flocks2 fatal error: must provide a control in create/2 FlocksConfig";
}
if (FlocksConfig.handler) {
handler = FlocksConfig.handler;
flocksLog(3, " - Flocks2 handler assigned");
}
if (FlocksConfig.finalizer) {
finalizer = FlocksConfig.finalizer;
flocksLog(3, " - Flocks2 finalizer assigned");
}
if (FlocksConfig.preventAutoContext) {
flocksLog(2, " - Flocks2 skipping auto-context");
} else {
flocksLog(2, " - Flocks2 engaging auto-context");
this.fctx = clone(nextFCtx);
}
flocksLog(3, "Flocks2 creation finished; initializing");
initialized = true;
attemptUpdate();
flocksLog(3, "Flocks2 expose updater");
this.fupd = updater;
this.fset = updater.set;
this.fgetkey = updater.get_key;
this.fgetpath = updater.get_path;
this.flock = updater.lock;
this.funlock = updater.unlock;
this.fupdate = updater.update;
flocksLog(3, "Flocks2 initialization finished");
return updater;
}
// because of YUIdoc limitations, the extracted docs for the mixin are far
// below. search for the word "yuibama" to jump between these places.
Mixin = {
"contextTypes" : flocks2Ctxs,
"childContextTypes" : flocks2Ctxs,
"componentWillMount" : function() {
flocksLog(1, " - Flocks2 component will mount: " + this.constructor.displayName);
flocksLog(3, isUndefined(this.props.flocks2context)?
" - No F2 Context Prop"
: " - F2 Context Prop found");
flocksLog(3, isUndefined(this.context.flocks2context)?
" - No F2 Context"
: " - F2 Context found");
if (this.props.flocks2context) {
this.context.flocks2context = this.props.flocks2context;
}
this.fupdate = function(Obj) { return update(Obj); };
this.fget = function(K) { return get(K); };
this.fgetkey = function(K) { return getByKey(K); };
this.fgetpath = function(P) { return getByPath(P); };
this.fset = function(K,V) { return set(K,V); };
this.fsetpath = function(P,V) { return set(P,V); };
this.flock = function() { return lock(); };
this.funlock = function() { return unlock(); };
this.fctx = this.context.flocks2context;
},
"getChildContext" : function() {
return this.context;
}
};
function atLeastFlocks(OriginalList) {
var NewList;
if (isUndefined(OriginalList)) {
return [ Mixin ];
}
if (isArray(OriginalList)) {
if (arrayMember(Mixin, OriginalList)) {
return OriginalList;
} else {
NewList = clone(OriginalList);
NewList.push(Mixin);
return NewList;
}
}
throw "Original mixin list must be an array or undefined!";
}
function createClass(spec) {
spec.mixins = atLeastFlocks(spec.mixins);
return React.createClass(spec);
}
exports = {
/**
* <tt>version</tt> is an exposed string on the <tt>module export</tt>
* which mentions the current library version. This number should
* always be in sync with the <tt>package.json</tt> and <tt>bower.json</tt>
* version, the <tt>github tag</tt>, the <tt>npm version</tt>, and will
* define the paths available on <tt>cdnjs</tt>
*
* @property version
* @type {String}
*/
"version" : "1.6.0",
/**
* <tt>createClass</tt> is a wrapper for <tt>react.createClass</tt> which
* automatically adds the <tt>plumbing</tt> mixin to your control's spec,
* to keep visual noise down. If you prefer, you can add the <tt>plumbing</tt>
* mixin manually, in the standard fashion, instead; that may be more
* convenient in situations where many mixins are in use, or where other
* wrappers of <tt>createClass</tt> are in use.
*
* @method createClass
*/
"createClass" : createClass,
/**
* <tt>mount</tt> accepts a <tt>flocks config</tt> and an initial state,
* and then manages a root control for you. <tt>mount</tt> returns to
* you a function which you can use from outside the control tree to
* update the <tt>flocks state</tt>. From inside the control tree, a
* control decorated with the <tt>flocks plumbing</tt> has a member
* <tt>this.fctx</tt> which contains an up to date copy of the <tt>flocks
* state</tt>, and another member <tt>this.fset()</tt> which you can
* use to update the <tt>flocks state</tt>.
*
* To <tt>mount</tt> a control is to start the process by placing your
* top level control into the document through <tt>flocks</tt>.
*
* @method mount
*/
"mount" : create,
/**
* <tt>clone</tt> recursively deep-copies its argument.
*
* @method clone
*/
"clone" : clone,
/**
* <tt>isArray</tt> produces a boolean regarding whether its argument
* is a javascript <tt>Array</tt>.
*
* @method isArray
*/
"isArray" : isArray,
/**
* <tt>isUndefined</tt> produces a boolean regarding whether its argument
* is the javascript value <tt>undefined</tt>.
*
* @method isUndefined
*/
"isUndefined" : isUndefined,
/**
* <tt>isStringOfNonNegInt</tt> will tell you whether a string contains
* a very strict interpretation of decimal non-negative integers: either
* the single character zero, or a sequence of digits not beginning with
* zero. As such this does not allow alternative radices, scientific
* notation, leading zeroes, empty mantissas, leading plusses, negative
* numbers in general, or other non-strict variants.
*
* @method isStringOfNonNegInt
*/
"isStringOfNonNegInt" : isStringOfNonNegInt,
/**
* <tt>isNonArrayObject</tt> produces a boolean regarding whether its
* argument is a javascript <tt>Object</tt>, but also goes to the effort
* to exclude javascript <tt>Array</tt>s.
*
* @method isNonArrayObject
*/
"isNonArrayObject" : isNonArrayObject,
/**
* <tt>enforceString</tt> accepts a value argument and an optional
* explanation argument, and will throw if the value argument is not of
* type <tt>string</tt>. The throw will be the explanation argument, or
* a default if the explanation is not present.
*
* @method enforceString
*/
"enforceString" : enforceString,
/**
* <tt>enforceArray</tt> accepts a value argument and an optional
* explanation argument, and will throw if the value argument is not of
* type <tt>Array</tt>. The throw will be the explanation argument, or
* a default if the explanation is not present.
*
* @method enforceArray
*/
"enforceArray" : enforceArray,
/**
* <tt>enforceNonArrayObject</tt> accepts a value argument and an optional
* explanation argument, and will throw if the value argument is of
* type <tt>Array</tt>, or not of type <tt>Object</tt>. The throw will be
* the explanation argument, or a default if the explanation is not present.
*
* @method enforceNonArrayObject
*/
"enforceNonArrayObject" : enforceNonArrayObject,
/**
* <tt>atLeastFlocks</tt> accepts a mixin set from a control spec, or
* the value <tt>undefined</tt>, and produces a mixin set in response,
* which contains the old mixin set if any, pre-pended with
* the <tt>flocks plumbing</tt> mixin, or a mixin set with just that
* mixin if the previous mixin set was empty or <tt>undefined</tt>.
* If the mixin set provided already contains flocks, it will be
* returned unaltered, in case the prior mixin set is order sensitive.
*
* This is not a method that the end user should expect to use.
*
* @method atLeastFlocks
*/
"atLeastFlocks" : atLeastFlocks,
/**
* <tt>plumbing</tt> is the <tt>flocks</tt> mixin which handles all of
* the behind-the-scenes work to make <tt>flocks</tt> function. The
* mixin is automatically added by calling <tt>flocks.createClass</tt>,
* or you can add it yourself in the standard mixin fashion if you prefer.
*
* @class plumbing
*/
// grossest doc structure ever. thanks yuibama.
/**
* Describes the context types accepted or required by any given React
* component; mixin hook notes the need for <tt>flocks2context : object</tt>
* as an incoming context to pay attention to.
*
* @property contextTypes
*/
/**
* Describes the context types provided by the React component; mixin
* hook notes that this provides <tt>flocks2context : object</tt> to
* subordinate controls.
*
* @property childContextTypes
*/
/**
* Called when the control is about to mount; mixin hooks this event to
* add the flocks context <tt>this.fctx</tt>, the flocks updater
* <tt>this.fset</tt>, and other flocks methods to the control object.
*
* @event componentWillMount
*/
/**
* Called when the control is about to pass context to children; the
* plumbing mixin hooks this event to do the simple job of passing the
* flocks context data downwards.
*
* @event getChildContext
*/
"plumbing" : Mixin
};
if (typeof module !== "undefined") {
module.exports = exports;
} else {
window.flocks = exports;
}
}());
|
packages/flow-runtime-docs/src/components/docs/TypeInferencePage.js | codemix/flow-runtime | /* @flow */
import React, { Component } from 'react';
import {observer} from 'mobx-react';
import Example from '../Example';
const inferenceCode = `
import t from 'flow-runtime';
const input = {
id: 123,
name: 'Sally',
addresses: [
{
line1: '123 Fake Street',
isActive: true
}
]
};
const inputType = t.typeOf(input);
console.log(String(inputType));
inputType.getProperty('id').unwrap().assert(456); // ok
inputType.getProperty('name').unwrap().assert(false); // throws
`.trim();
@observer
export default class TypeInferencePage extends Component {
render() {
return (
<div>
<header className="jumbotron jumbotron-fluid text-xs-center">
<h1>Type Inference</h1>
</header>
<div className="container">
<p><code>flow-runtime</code> can infer types from JavaScript values. These types can then be inspected just like any other:</p>
<Example code={inferenceCode}
inline
hideOutput
/>
</div>
</div>
);
}
}
|
src/index.js | wework/careday-app | import { Provider } from 'react-redux';
import React from 'react';
import ReactDOM from 'react-dom';
import configureStore from 'common/redux/configureStore';
import 'stroller/core/index.scss';
import Routes from './routes';
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<Routes />
</Provider>,
document.getElementById('root')
);
|
app/assets/scripts/components/testimonials.js | openaq/openaq.github.io | import React, { Component } from 'react';
import { PropTypes as T } from 'prop-types';
import { environment } from '../config';
class Testimonials extends Component {
constructor (props) {
super(props);
this.renderListItem = this.renderListItem.bind(this);
}
renderListItem (testimonial) {
const {
image,
short_quote: shortQuote,
long_quote: longQuote,
name,
title,
affiliation,
location
} = testimonial;
const details = [
title,
affiliation,
location
].filter(Boolean).join(' / ');
const img = image
? `/assets/graphics/content/${image}`
: 'https://use.placeimage.app/960x960';
return (
<li key={testimonial}>
<blockquote className='testimonial'>
<div className='testimonial__media'>
<img src={img} width='960' height='960' alt='Image placeholder' />
</div>
<div className='testimonial__copy'>
<div className='testimonial__quote'>
<p>{shortQuote || longQuote}</p>
</div>
<footer className='testimonial__footer'>
<strong>{name}</strong>
<small>{details}</small>
</footer>
</div>
</blockquote>
</li>
);
}
render () {
return (
<section className='testimonials'>
<div className='inner'>
<h1 className='testimonials__title'>Testimonials</h1>
<ol className='testimonials-list'>
{this.props.items.map(this.renderListItem)}
</ol>
</div>
</section>
);
}
}
if (environment !== 'production') {
Testimonials.propTypes = {
items: T.array
};
}
export default Testimonials;
|
vendor/laravel/framework/src/Illuminate/Foundation/Console/Presets/react-stubs/Example.js | demoxu/blog | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Example extends Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-8 col-md-offset-2">
<div className="panel panel-default">
<div className="panel-heading">Example Component</div>
<div className="panel-body">
I'm an example component!
</div>
</div>
</div>
</div>
</div>
);
}
}
if (document.getElementById('example')) {
ReactDOM.render(<Example />, document.getElementById('example'));
}
|
docs/client/routes.js | draft-js-plugins/draft-js-plugins-v1 | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/wrappers/App';
import Page from './components/wrappers/Page';
import NotFound from './components/pages/NotFound';
import Home from './components/pages/Home';
import Hashtag from './components/pages/Hashtag';
import Emoji from './components/pages/Emoji';
import Linkify from './components/pages/Linkify';
import Sticker from './components/pages/Sticker';
import Undo from './components/pages/Undo';
import Mention from './components/pages/Mention';
import Wysiwyg from './components/pages/Wysiwyg';
import Counter from './components/pages/Counter';
import Playground from './components/pages/Playground';
export const routes = (
<Route path="/" title="App" component={App}>
<IndexRoute component={Home} />
<Route path="/" title="App" component={Page}>
<Route path="plugin/hashtag" title="App - Hashtag" component={Hashtag} />
<Route path="plugin/emoji" title="App - Emoji" component={Emoji} />
<Route path="plugin/linkify" title="App - Linkify" component={Linkify} />
<Route path="plugin/sticker" title="App - Sticker" component={Sticker} />
<Route path="plugin/undo" title="App - Undo" component={Undo} />
<Route path="plugin/mention" title="App - Mention" component={Mention} />
<Route path="plugin/wysiwyg" title="App - Wysiwyg" component={Wysiwyg} />
<Route path="plugin/counter" title="App - Counter" component={Counter} />
</Route>
<Route path="playground" title="App - Development Playground" component={Playground} />
<Route path="*" title="404: Not Found" component={NotFound} />
</Route>
);
export default routes;
|
src/svg-icons/image/view-compact.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageViewCompact = (props) => (
<SvgIcon {...props}>
<path d="M3 19h6v-7H3v7zm7 0h12v-7H10v7zM3 5v6h19V5H3z"/>
</SvgIcon>
);
ImageViewCompact = pure(ImageViewCompact);
ImageViewCompact.displayName = 'ImageViewCompact';
export default ImageViewCompact;
|
ajax/libs/ink/2.2.1/js/ink-all.js | stevermeister/cdnjs |
(function() {
'use strict';
/**
* @module Ink_1
*/
/**
* global object
*
* @class Ink
*/
// skip redefinition of Ink core
if ('Ink' in window) { return; }
// internal data
/*
* NOTE:
* invoke Ink.setPath('Ink', '/Ink/'); before requiring local modules
*/
var paths = {
Ink: ( ('INK_PATH' in window) ? window.INK_PATH : window.location.protocol + '//js.ink.sapo.pt/Ink/' )
};
var modules = {};
var modulesLoadOrder = [];
var modulesRequested = {};
var pendingRMs = [];
// auxiliary fns
var isEmptyObject = function(o) {
/*jshint unused:false */
if (typeof o !== 'object') { return false; }
for (var k in o) {
if (o.hasOwnProperty(k)) {
return false;
}
}
return true;
};
window.Ink = {
_checkPendingRequireModules: function() {
var I, F, o, dep, mod, cb, pRMs = [];
for (I = 0, F = pendingRMs.length; I < F; ++I) {
o = pendingRMs[I];
if (!o) { continue; }
for (dep in o.left) {
if (o.left.hasOwnProperty(dep)) {
mod = modules[dep];
if (mod) {
o.args[o.left[dep] ] = mod;
delete o.left[dep];
--o.remaining;
}
}
}
if (o.remaining > 0) {
pRMs.push(o);
}
else {
cb = o.cb;
if (!cb) { continue; }
delete o.cb; // to make sure I won't call this more than once!
cb.apply(false, o.args);
}
}
pendingRMs = pRMs;
if (pendingRMs.length > 0) {
setTimeout( function() { Ink._checkPendingRequireModules(); }, 0 );
}
},
_modNameToUri: function(modName) {
if (modName.indexOf('/') !== -1) {
return modName;
}
var parts = modName.replace(/_/g, '.').split('.');
var root = parts.shift();
var uriPrefix = paths[root];
if (!uriPrefix) {
uriPrefix = './' + root + '/';
// console.warn('Not sure where to fetch ' + root + ' modules from! Attempting ' + uriPrefix + '...');
}
return [uriPrefix, parts.join('/'), '/lib.js'].join('');
},
getPath: function(key) {
return paths[key || 'Ink'];
},
setPath: function(key, rootURI) {
paths[key] = rootURI;
},
/**
* loads a javascript script in the head.
*
* @method loadScript
* @param {String} uri can be an http URI or a module name
*/
loadScript: function(uri) {
/*jshint evil:true */
var scriptEl = document.createElement('script');
scriptEl.setAttribute('type', 'text/javascript');
scriptEl.setAttribute('src', this._modNameToUri(uri));
// CHECK ON ALL BROWSERS
/*if (document.readyState !== 'complete' && !document.body) {
document.write( scriptEl.outerHTML );
}
else {*/
var aHead = document.getElementsByTagName('head');
if(aHead.length > 0) {
aHead[0].appendChild(scriptEl);
}
//}
},
/**
* defines a namespace.
*
* @method namespace
* @param {String} ns
* @param {Boolean} [returnParentAndKey]
* @return {Array|Object} if returnParentAndKey, returns [parent, lastPart], otherwise return the namespace directly
*/
namespace: function(ns, returnParentAndKey) {
if (!ns || !ns.length) { return null; }
var levels = ns.split('.');
var nsobj = window;
var parent;
for (var i = 0, f = levels.length; i < f; ++i) {
nsobj[ levels[i] ] = nsobj[ levels[i] ] || {};
parent = nsobj;
nsobj = nsobj[ levels[i] ];
}
if (returnParentAndKey) {
return [
parent,
levels[i-1]
];
}
return nsobj;
},
/**
* synchronous. assumes module is loaded already!
*
* @method getModule
* @param {String} mod
* @param {Number} [version]
* @return {Object|Function} module object / function
*/
getModule: function(mod, version) {
var key = version ? [mod, '_', version].join('') : mod;
return modules[key];
},
/**
* must be the wrapper around each Ink lib module for require resolution
*
* @method createModule
* @param {String} mod module name. parts are split with dots
* @param {Number} version
* @param {Array} deps array of module names which are dependencies for the module being created
* @param {Function} modFn its arguments are the resolved dependecies, once all of them are fetched. the body of this function should return the module.
*/
createModule: function(mod, ver, deps, modFn) { // define
var cb = function() {
//console.log(['createModule(', mod, ', ', ver, ', [', deps.join(', '), '], ', !!modFn, ')'].join(''));
if (typeof mod !== 'string') {
throw new Error('module name must be a string!');
}
// validate version correctness
if (typeof ver === 'number' || (typeof ver === 'string' && ver.length > 0)) {
} else {
throw new Error('version number missing!');
}
var modAll = [mod, '_', ver].join('');
// make sure module in not loaded twice
if (modules[modAll]) {
//console.warn(['Ink.createModule ', modAll, ': module has been defined already.'].join(''));
return;
}
// delete related pending tasks
delete modulesRequested[modAll];
delete modulesRequested[mod];
// run module's supplied factory
var args = Array.prototype.slice.call(arguments);
var moduleContent = modFn.apply(window, args);
modulesLoadOrder.push(modAll);
// console.log('** loaded module ' + modAll + '**');
// set version
if (typeof moduleContent === 'object') { // Dom.Css Dom.Event
moduleContent._version = ver;
}
else if (typeof moduleContent === 'function') {
moduleContent.prototype._version = ver; // if constructor
moduleContent._version = ver; // if regular function
}
// add to global namespace...
var isInkModule = mod.indexOf('Ink.') === 0;
var t;
if (isInkModule) {
t = Ink.namespace(mod, true); // for mod 'Ink.Dom.Css', t[0] gets 'Ink.Dom' object and t[1] 'Css'
}
// versioned
modules[ modAll ] = moduleContent; // in modules
if (isInkModule) {
t[0][ t[1] + '_' + ver ] = moduleContent; // in namespace
}
// unversioned
modules[ mod ] = moduleContent; // in modules
if (isInkModule) {
if (isEmptyObject( t[0][ t[1] ] )) {
t[0][ t[1] ] = moduleContent; // in namespace
}
else {
// console.warn(['Ink.createModule ', modAll, ': module has been defined already with a different version!'].join(''));
}
}
if (this) { // there may be pending requires expecting this module, check...
Ink._checkPendingRequireModules();
}
};
this.requireModules(deps, cb);
},
/**
* use this to get depencies, even if they're not loaded yet
*
* @method requireModules
* @param {Array} deps array of module names which are dependencies for the require function body
* @param {Function} cbFn its arguments are the resolved dependecies, once all of them are fetched
*/
requireModules: function(deps, cbFn) { // require
//console.log(['requireModules([', deps.join(', '), '], ', !!cbFn, ')'].join(''));
var i, f, o, dep, mod;
f = deps.length;
o = {
args: new Array(f),
left: {},
remaining: f,
cb: cbFn
};
if (!(typeof deps === 'object' && deps.length !== undefined)) {
throw new Error('Dependency list should be an array!');
}
if (typeof cbFn !== 'function') {
throw new Error('Callback should be a function!');
}
for (i = 0; i < f; ++i) {
dep = deps[i];
mod = modules[dep];
if (mod) {
o.args[i] = mod;
--o.remaining;
continue;
}
else if (modulesRequested[dep]) {
}
else {
modulesRequested[dep] = true;
Ink.loadScript(dep);
}
o.left[dep] = i;
}
if (o.remaining > 0) {
pendingRMs.push(o);
}
else {
cbFn.apply(true, o.args);
}
},
/**
* list or module names, ordered by loaded time
*
* @method getModulesLoadOrder
* @return {Array} returns the order in which modules were resolved and correctly loaded
*/
getModulesLoadOrder: function() {
return modulesLoadOrder.slice();
},
/**
* returns the markup you should have to bundle your JS resources yourself
*
* @return {String} scripts markup
*/
getModuleScripts: function() {
var mlo = this.getModulesLoadOrder();
mlo.unshift('Ink_1');
// console.log(mlo);
mlo = mlo.map(function(m) {
var cutAt = m.indexOf('.');
if (cutAt === -1) { cutAt = m.indexOf('_'); }
var root = m.substring(0, cutAt);
m = m.substring(cutAt + 1);
var rootPath = Ink.getPath(root);
return ['<script type="text/javascript" src="', rootPath, m.replace(/\./g, '/'), '/"></script>'].join('');
});
return mlo.join('\n');
},
/**
* Function.prototype.bind alternative.
* Additional arguments will be sent to the original function as prefix arguments.
*
* @method bind
* @param {Function} fn
* @param {Object} context
* @return {Function}
*/
bind: function(fn, context) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return fn.apply(context, finalArgs);
};
},
/**
* Function.prototype.bind alternative for binding class methods
*
* @method bindMethod
* @param {Object} object
* @param {String} methodName
* @return {Function}
*
* @example
* // Build a function which calls Ink.Dom.Element.remove on an element.
* var removeMyElem = Ink.bindMethod(Ink.Dom.Element, 'remove', someElement);
*
* removeMyElem(); // no arguments, nor Ink.Dom.Element, needed
* @example
* // (comparison with using Ink.bind to the same effect).
* // The following two calls are equivalent
*
* Ink.bind(this.remove, this, myElem);
* Ink.bindMethod(this, 'remove', myElem);
*/
bindMethod: function (object, methodName) {
return this.bind.apply(this,
[object[methodName], object].concat([].slice.call(arguments, 2)));
},
/**
* Function.prototype.bind alternative for event handlers.
* Same as bind but keeps first argument of the call the original event.
* Additional arguments will be sent to the original function as prefix arguments.
*
* @method bindEvent
* @param {Function} fn
* @param {Object} context
* @return {Function}
*/
bindEvent: function(fn, context) {
var args = Array.prototype.slice.call(arguments, 2);
return function(event) {
var finalArgs = args.slice();
finalArgs.unshift(event || window.event);
return fn.apply(context, finalArgs);
};
},
/**
* alias to document.getElementById
*
* @method i
* @param {String} id
*/
i: function(id) {
if(!id) {
throw new Error('Ink.i => id or element must be passed');
}
if(typeof(id) === 'string') {
return document.getElementById(id);
}
return id;
},
/**
* alias to sizzle or querySelector
*
* @method s
* @param {String} rule
* @param {DOMElement} [from]
* @return {DOMElement}
*/
s: function(rule, from)
{
if(typeof(Ink.Dom) === 'undefined' || typeof(Ink.Dom.Selector) === 'undefined') {
throw new Error('This method requires Ink.Dom.Selector');
}
return Ink.Dom.Selector.select(rule, (from || document))[0] || null;
},
/**
* alias to sizzle or querySelectorAll
*
* @method ss
* @param {String} rule
* @param {DOMElement} [from]
* @return {Array} array of DOMElements
*/
ss: function(rule, from)
{
if(typeof(Ink.Dom) === 'undefined' || typeof(Ink.Dom.Selector) === 'undefined') {
throw new Error('This method requires Ink.Dom.Selector');
}
return Ink.Dom.Selector.select(rule, (from || document));
},
/**
* Enriches the destination object with values from source object whenever the key is missing in destination.
*
* More than one object can be passed as source, in which case the rightmost objects have precedence.
*
* @method extendObj
* @param {Object} destination
* @param {Object...} sources
* @return destination object, enriched with defaults from the sources
*/
extendObj: function(destination, source)
{
if (arguments.length > 2) {
source = Ink.extendObj.apply(this, [].slice.call(arguments, 1));
}
if (source) {
for (var property in source) {
if(Object.prototype.hasOwnProperty.call(source, property)) {
destination[property] = source[property];
}
}
}
return destination;
}
};
// TODO for debug - to detect pending stuff
/*
var failCount = {}; // fail count per module name
var maxFails = 3; // times
var checkDelta = 0.5; //seconds
var tmpTmr = setInterval(function() {
var mk = Object.keys(modulesRequested);
var l = mk.length;
if (l > 0) {
// console.log('** waiting for modules: ' + mk.join(', ') + ' **');
for (var i = 0, f = mk.length, k, v; i < f; ++i) {
k = mk[i];
v = failCount[k];
failCount[k] = (v === undefined) ? 1 : ++v;
if (v >= maxFails) {
console.error('** Loading of module ' + k + ' failed! **');
delete modulesRequested[k];
}
}
}
else {
// console.log('** Module loads complete. **');
clearInterval(tmpTmr);
}
}, checkDelta*1000);
*/
})();
/**
* @author inkdev AT sapo.pt
*/
Ink.createModule('Ink.Net.Ajax', '1', [], function() {
'use strict';
/**
* @module Ink.Net.Ajax_1
*/
/**
* Creates a new cross browser XMLHttpRequest object
*
* @class Ink.Net.Ajax
* @constructor
*
* @param {String} url request url
* @param {Object} options request options
* @param {Boolean} [options.asynchronous] if the request should be asynchronous. true by default.
* @param {String} [options.method] HTTP request method. POST by default.
* @param {Object|String} [options.parameters] Request parameters which should be sent with the request
* @param {Number} [options.timeout] Request timeout
* @param {Number} [options.delay] Artificial delay. If request is completed in time lower than this, then wait a bit before calling the callbacks
* @param {String} [options.postBody] POST request body. If not specified, it's filled with the contents from parameters
* @param {String} [options.contentType] Content-type header to be sent. Defaults to 'application/x-www-form-urlencoded'
* @param {Object} [options.requestHeaders] key-value pairs for additional request headers
* @param {Function} [options.onComplete] Callback executed after the request is completed, no matter what happens during the request.
* @param {Function} [options.onSuccess] Callback executed if the request is successful (requests with 2xx status codes)
* @param {Function} [options.onFailure] Callback executed if the request fails (requests with status codes different from 2xx)
* @param {Function} [options.onException] Callback executed if an exception occurs. Receives the exception as a parameter.
* @param {Function} [options.onCreate] Callback executed after object initialization but before the request is made
* @param {Function} [options.onInit] Callback executed before any initialization
* @param {Function} [options.onTimeout] Callback executed if the request times out
* @param {Boolean|String} [options.evalJS] If the request Content-type header is application/json, evaluates the response and populates responseJSON. Use 'force' if you want to force the response evaluation, no matter what Content-type it's using. Defaults to true.
* @param {Boolean} [options.sanitizeJSON] Sanitize the content of responseText before evaluation
* @param {String} [options.xhrProxy] URI for proxy service hosted on the same server as the web app, that can fetch documents from other domains.
* The service must pipe all input and output untouched (some input sanitization is allowed, like clearing cookies).
* e.g., requesting http://example.org/doc can become /proxy/http%3A%2F%2Fexample.org%2Fdoc The proxy service will
* be used for cross-domain requests, if set, else a network error is returned as exception.
*/
var Ajax = function(url, options){
// start of AjaxMock patch - uncomment to enable it
/*var AM = SAPO.Communication.AjaxMock;
if (AM && !options.inMock) {
if (AM.autoRecordThisUrl && AM.autoRecordThisUrl(url)) {
return new AM.Record(url, options);
}
if (AM.mockThisUrl && AM.mockThisUrl(url)) {
return new AM.Play(url, options, true);
}
}*/
// end of AjaxMock patch
this.init(url, options);
};
/**
* Options for all requests. These can then be
* overriden for individual ones.
*/
Ajax.globalOptions = {
parameters: {},
requestHeaders: {}
};
// IE10 does not need XDomainRequest
var xMLHttpRequestWithCredentials = 'XMLHttpRequest' in window && 'withCredentials' in (new XMLHttpRequest());
Ajax.prototype = {
init: function(url, userOptions) {
if (!url) {
throw new Error("WRONG_ARGUMENTS_ERR");
}
var options = Ink.extendObj({
asynchronous: true,
method: 'POST',
parameters: null,
timeout: 0,
delay: 0,
postBody: '',
contentType: 'application/x-www-form-urlencoded',
requestHeaders: null,
onComplete: null,
onSuccess: null,
onFailure: null,
onException: null,
onHeaders: null,
onCreate: null,
onInit: null,
onTimeout: null,
sanitizeJSON: false,
evalJS: true,
xhrProxy: '',
cors: false,
debug: false,
useCredentials: false,
signRequest: false
}, Ajax.globalOptions);
if (userOptions && typeof userOptions === 'object') {
options = Ink.extendObj(options, userOptions);
if (typeof userOptions.parameters === 'object') {
options.parameters = Ink.extendObj(Ink.extendObj({}, Ajax.globalOptions.parameters), userOptions.parameters);
} else if (userOptions.parameters !== null) {
var globalParameters = this.paramsObjToStr(Ajax.globalOptions.parameters);
if (globalParameters) {
options.parameters = userOptions.parameters + '&' + globalParameters;
}
}
options.requestHeaders = Ink.extendObj({}, Ajax.globalOptions.requestHeaders);
options.requestHeaders = Ink.extendObj(options.requestHeaders, userOptions.requestHeaders);
}
this.options = options;
this.safeCall('onInit');
var urlLocation = document.createElementNS ?
document.createElementNS('http://www.w3.org/1999/xhtml', 'a') :
document.createElement('a');
urlLocation.href = url;
this.url = url;
this.isHTTP = urlLocation.protocol.match(/^https?:$/i) && true;
this.requestHasBody = options.method.search(/^get|head$/i) < 0;
if (!this.isHTTP || location.protocol === 'widget:' || typeof window.widget === 'object') {
this.isCrossDomain = false;
} else {
this.isCrossDomain = location.protocol !== urlLocation.protocol || location.host !== urlLocation.host;
}
if(this.options.cors) {
this.isCrossDomain = false;
}
this.transport = this.getTransport();
this.request();
},
/**
* Creates the appropriate XMLHttpRequest object
*
* @method getTransport
* @return {Object} XMLHttpRequest object
*/
getTransport: function()
{
/*global XDomainRequest:false, ActiveXObject:false */
if (!xMLHttpRequestWithCredentials && this.options.cors && 'XDomainRequest' in window) {
this.usingXDomainReq = true;
return new XDomainRequest();
}
else if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
else if (typeof ActiveXObject !== 'undefined') {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
return new ActiveXObject('Microsoft.XMLHTTP');
}
} else {
return null;
}
},
/**
* Set the necessary headers for an ajax request
*
* @method setHeaders
* @param {String} url - url for the request
*/
setHeaders: function()
{
if (this.transport) {
try {
var headers = {
"Accept": "text/javascript,text/xml,application/xml,application/xhtml+xml,text/html,application/json;q=0.9,text/plain;q=0.8,video/x-mng,image/png,image/jpeg,image/gif;q=0.2,*/*;q=0.1",
"Accept-Language": navigator.language,
"X-Requested-With": "XMLHttpRequest",
"X-Ink-Version": "1"
};
if (this.options.cors) {
if (!this.options.signRequest) {
delete headers['X-Requested-With'];
}
delete headers['X-Ink-Version'];
}
if (this.options.requestHeaders && typeof this.options.requestHeaders === 'object') {
for(var headerReqName in this.options.requestHeaders) {
if (this.options.requestHeaders.hasOwnProperty(headerReqName)) {
headers[headerReqName] = this.options.requestHeaders[headerReqName];
}
}
}
if (this.transport.overrideMimeType && (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) {
headers['Connection'] = 'close';
}
for (var headerName in headers) {
if(headers.hasOwnProperty(headerName)) {
this.transport.setRequestHeader(headerName, headers[headerName]);
}
}
} catch(e) {}
}
},
/**
* Converts an object with parameters to a querystring
*
* @method paramsObjToStr
* @param {Object|String} optParams parameters object
* @return {String} querystring
*/
paramsObjToStr: function(optParams) {
var k, m, p, a, params = [];
if (typeof optParams === 'object') {
for (p in optParams){
if (optParams.hasOwnProperty(p)) {
a = optParams[p];
if (Object.prototype.toString.call(a) === '[object Array]' && !isNaN(a.length)) {
for (k = 0, m = a.length; k < m; k++) {
params = params.concat([
encodeURIComponent(p), '[]', '=',
encodeURIComponent(a[k]), '&'
]);
}
}
else {
params = params.concat([
encodeURIComponent(p), '=',
encodeURIComponent(a), '&'
]);
}
}
}
if (params.length > 0) {
params.pop();
}
}
else
{
return optParams;
}
return params.join('');
},
/**
* set the url parameters for a GET request
*
* @method setParams
*/
setParams: function()
{
var params = null, optParams = this.options.parameters;
if(typeof optParams === "object"){
params = this.paramsObjToStr(optParams);
} else {
params = '' + optParams;
}
if(params){
if(this.url.indexOf('?') > -1) {
this.url = this.url.split('#')[0] + '&' + params;
} else {
this.url = this.url.split('#')[0] + '?' + params;
}
}
},
/**
* Retrieves HTTP header from response
*
* @method getHeader
* @param {String} name header name
* @return {String} header content
*/
getHeader: function(name)
{
if (this.usingXDomainReq && name === 'Content-Type') {
return this.transport.contentType;
}
try{
return this.transport.getResponseHeader(name);
} catch(e) {
return null;
}
},
/**
* Returns all http headers from the response
*
* @method getAllHeaders
* @return {String} the headers, each separated by a newline
*/
getAllHeaders: function()
{
try {
return this.transport.getAllResponseHeaders();
} catch(e) {
return null;
}
},
/**
* Setup the response object
*
* @method getResponse
* @return {Object} the response object
*/
getResponse: function(){
// setup our own stuff
var t = this.transport,
r = {
headerJSON: null,
responseJSON: null,
getHeader: this.getHeader,
getAllHeaders: this.getAllHeaders,
request: this,
transport: t,
timeTaken: new Date() - this.startTime,
requestedUrl: this.url
};
// setup things expected from the native object
r.readyState = t.readyState;
try { r.responseText = t.responseText; } catch(e) {}
try { r.responseXML = t.responseXML; } catch(e) {}
try { r.status = t.status; } catch(e) { r.status = 0; }
try { r.statusText = t.statusText; } catch(e) { r.statusText = ''; }
return r;
},
/**
* Aborts the request if still running. No callbacks are called
*
* @method abort
*/
abort: function(){
if (this.transport) {
clearTimeout(this.delayTimeout);
clearTimeout(this.stoTimeout);
try { this.transport.abort(); } catch(ex) {}
this.finish();
}
},
/**
* Executes the state changing phase of an ajax request
*
* @method runStateChange
*/
runStateChange: function()
{
var rs = this.transport.readyState;
if (rs === 3) {
if (this.isHTTP) {
this.safeCall('onHeaders');
}
} else if (rs === 4 || this.usingXDomainReq) {
if (this.options.asynchronous && this.options.delay && (this.startTime + this.options.delay > new Date().getTime())) {
this.delayTimeout = setTimeout(Ink.bind(this.runStateChange, this), this.options.delay + this.startTime - new Date().getTime());
return;
}
var responseJSON,
responseContent = this.transport.responseText,
response = this.getResponse(),
curStatus = this.transport.status;
if (this.isHTTP && !this.options.asynchronous) {
this.safeCall('onHeaders');
}
clearTimeout(this.stoTimeout);
if (curStatus === 0) {
// Status 0 indicates network error for http requests.
// For http less requests, 0 is always returned.
if (this.isHTTP) {
this.safeCall('onException', this.makeError(18, 'NETWORK_ERR'));
} else {
curStatus = responseContent ? 200 : 404;
}
}
else if (curStatus === 304) {
curStatus = 200;
}
var isSuccess = this.usingXDomainReq || 200 <= curStatus && curStatus < 300;
var headerContentType = this.getHeader('Content-Type') || '';
if (this.options.evalJS &&
(headerContentType.indexOf("application/json") >= 0 || this.options.evalJS === 'force')){
try {
responseJSON = this.evalJSON(responseContent, this.sanitizeJSON);
if(responseJSON){
responseContent = response.responseJSON = responseJSON;
}
} catch(e){
if (isSuccess) {
// If the request failed, then this is perhaps an error page
// so don't notify error.
this.safeCall('onException', e);
}
}
}
if (this.usingXDomainReq && headerContentType.indexOf('xml') !== -1 && 'DOMParser' in window) {
// http://msdn.microsoft.com/en-us/library/ie/ff975278(v=vs.85).aspx
var mimeType;
switch (headerContentType) {
case 'application/xml':
case 'application/xhtml+xml':
case 'image/svg+xml':
mimeType = headerContentType;
break;
default:
mimeType = 'text/xml';
}
var xmlDoc = (new DOMParser()).parseFromString( this.transport.responseText, mimeType);
this.transport.responseXML = xmlDoc;
response.responseXML = xmlDoc;
}
if (this.transport.responseXML !== null && response.responseJSON === null && this.transport.responseXML.xml !== ""){
responseContent = this.transport.responseXML;
}
if (curStatus || this.usingXDomainReq) {
if (isSuccess) {
this.safeCall('onSuccess', response, responseContent);
} else {
this.safeCall('onFailure', response, responseContent);
}
this.safeCall('on'+curStatus, response, responseContent);
}
this.finish(response, responseContent);
}
},
/**
* Last step after XHR is complete. Call onComplete and cleanup object
*
* @method finish
* @param {} response
* @param {} responseContent
*/
finish: function(response, responseContent){
if (response) {
this.safeCall('onComplete', response, responseContent);
}
clearTimeout(this.stoTimeout);
if (this.transport) {
// IE6 sometimes barfs on this one
try{ this.transport.onreadystatechange = null; } catch(e){}
if (typeof this.transport.destroy === 'function') {
// Stuff for Samsung.
this.transport.destroy();
}
// Let XHR be collected.
this.transport = null;
}
},
/**
* Safely calls a callback function.
* Verifies that the callback is well defined and traps errors
*
* @method safeCall
* @param {Function} listener
*/
safeCall: function(listener, first/*, second*/) {
function rethrow(exception){
setTimeout(function() {
// Rethrow exception so it'll land in
// the error console, firebug, whatever.
if (exception.message) {
exception.message += '\n'+(exception.stacktrace || exception.stack || '');
}
throw exception;
}, 1);
}
if (typeof this.options[listener] === 'function') {
//SAPO.safeCall(this, this.options[listener], first, second);
//return object[listener].apply(object, [].slice.call(arguments, 2));
try {
this.options[listener].apply(this, [].slice.call(arguments, 1));
} catch(ex) {
rethrow(ex);
}
} else if (first && window.Error && (first instanceof Error)) {
rethrow(first);
}
},
/**
* Sets new request header for the subsequent http request
*
* @method setRequestHeader
* @param {String} name
* @param {String} value
*/
setRequestHeader: function(name, value){
if (!this.options.requestHeaders) {
this.options.requestHeaders = {};
}
this.options.requestHeaders[name] = value;
},
/**
* Execute the request
*
* @method request
*/
request: function()
{
if(this.transport) {
var params = null;
if(this.requestHasBody) {
if(this.options.postBody !== null && this.options.postBody !== '') {
params = this.options.postBody;
this.setParams();
} else if (this.options.parameters !== null && this.options.parameters !== ''){
params = this.options.parameters;
}
if (typeof params === "object" && !params.nodeType) {
params = this.paramsObjToStr(params);
} else if (typeof params !== "object" && params !== null){
params = '' + params;
}
if(this.options.contentType) {
this.setRequestHeader('Content-Type', this.options.contentType);
}
} else {
this.setParams();
}
var url = this.url;
var method = this.options.method;
var crossDomain = this.isCrossDomain;
if (crossDomain && this.options.xhrProxy) {
this.setRequestHeader('X-Url', url);
url = this.options.xhrProxy + encodeURIComponent(url);
crossDomain = false;
}
try {
this.transport.open(method, url, this.options.asynchronous);
} catch(e) {
this.safeCall('onException', e);
return this.finish(this.getResponse(), null);
}
this.setHeaders();
this.safeCall('onCreate');
if(this.options.timeout && !isNaN(this.options.timeout)) {
this.stoTimeout = setTimeout(Ink.bind(function() {
if(this.options.onTimeout) {
this.safeCall('onTimeout');
this.abort();
}
}, this), (this.options.timeout * 1000));
}
if(this.options.useCredentials && !this.usingXDomainReq) {
this.transport.withCredentials = true;
}
if(this.options.asynchronous && !this.usingXDomainReq) {
this.transport.onreadystatechange = Ink.bind(this.runStateChange, this);
}
else if (this.usingXDomainReq) {
this.transport.onload = Ink.bind(this.runStateChange, this);
}
try {
if (crossDomain) {
// Need explicit handling because Mozila aborts
// the script and Chrome fails silently.per the spec
throw this.makeError(18, 'NETWORK_ERR');
} else {
this.startTime = new Date().getTime();
this.transport.send(params);
}
} catch(e) {
this.safeCall('onException', e);
return this.finish(this.getResponse(), null);
}
if(!this.options.asynchronous) {
this.runStateChange();
}
}
},
/**
* Returns new exception object that can be thrown
*
* @method makeError
* @param code
* @param message
* @returns {Object}
*/
makeError: function(code, message){
if (typeof Error !== 'function') {
return {code: code, message: message};
}
var e = new Error(message);
e.code = code;
return e;
},
/**
* Checks if a given string is valid JSON
*
* @method isJSON
* @param {String} str String to be evaluated
* @return {Boolean} True if the string is valid JSON
*/
isJSON: function(str)
{
if (typeof str !== "string" || !str){ return false; }
str = str.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
},
/**
* Evaluates a given string as JSON
*
* @method evalJSON
* @param {String} str String to be evaluated
* @param {Boolean} sanitize whether to sanitize the content or not
* @return {Object} Json content as an object
*/
evalJSON: function(strJSON, sanitize)
{
if (strJSON && (!sanitize || this.isJSON(strJSON))) {
try {
if (typeof JSON !== "undefined" && typeof JSON.parse !== 'undefined'){
return JSON.parse(strJSON);
}
return eval('(' + strJSON + ')');
} catch(e) {
throw new Error('ERROR: Bad JSON string...');
}
}
return null;
}
};
/**
* Loads content from a given url through a XMLHttpRequest.
* Shortcut function for simple AJAX use cases.
*
* @method load
* @param {String} url request url
* @param {Function} callback callback to be executed if the request is successful
* @return {Object} XMLHttpRequest object
*/
Ajax.load = function(url, callback){
return new Ajax(url, {
method: 'GET',
onSuccess: function(response){
callback(response.responseText, response);
}
});
};
/**
* Loads content from a given url through a XMLHttpRequest.
* Shortcut function for simple AJAX use cases.
*
* @method ping
* @param {String} url request url
* @param {Function} callback callback to be executed if the request is successful
* @return {Object} XMLHttpRequest object
*/
Ajax.ping = function(url, callback){
return new Ajax(url, {
method: 'HEAD',
onSuccess: function(response){
if (typeof callback === 'function'){
callback(response);
}
}
});
};
return Ajax;
});
/**
* @author inkdev AT sapo.pt
*/
Ink.createModule('Ink.Net.JsonP', '1', [], function() {
'use strict';
/**
* @module Ink.Net.JsonP_1
*/
/**
* This class takes care of the nitty-gritty details of doing jsonp requests: Storing
* a callback in a globally accessible manner, waiting for the timeout or completion
* of the request, and passing extra GET parameters to the server, is not so complicated
* but it's boring and repetitive to code and tricky to get right.
*
* @class Ink.Net.JsonP
* @constructor
* @param {String} uri
* @param {Object} options
* @param {Function} options.onSuccess success callback
* @param {Function} [options.onFailure] failure callback
* @param {Object} [options.failureObj] object to be passed as argument to failure callback
* @param {Number} [options.timeout] timeout for request fail, in seconds. defaults to 10
* @param {Object} [options.params] object with the parameters and respective values to unfold
* @param {String} [options.callbackParam] parameter to use as callback. defaults to 'jsoncallback'
* @param {String} [options.internalCallback] *Advanced*: name of the callback function stored in the Ink.Net.JsonP object.
*
* @example
* Ink.requireModules(['Ink.Net.JsonP_1'], function (JsonP) {
* var jsonp = new JsonP('http://path.to.jsonp/endpoint', {
* // When the JSONP response arrives, this callback is called:
* onSuccess: function (gameData) {
* game.startGame(gameData);
* },
* // after options.timeout seconds, this callback gets called:
* onFailure: function () {
* game.error('Could not load game data!');
* },
* timeout: 5
* });
* });
*/
var JsonP = function(uri, options) {
this.init(uri, options);
};
JsonP.prototype = {
init: function(uri, options) {
this.options = Ink.extendObj( {
onSuccess: undefined,
onFailure: undefined,
failureObj: {},
timeout: 10,
params: {},
callbackParam: 'jsoncallback',
internalCallback: '_cb',
randVar: false
}, options || {});
if(this.options.randVar !== false) {
this.randVar = this.options.randVar;
} else {
this.randVar = parseInt(Math.random() * 100000, 10);
}
this.options.internalCallback += this.randVar;
this.uri = uri;
// prevent SAPO legacy onComplete - make it onSuccess
if(typeof(this.options.onComplete) === 'function') {
this.options.onSuccess = this.options.onComplete;
}
if (typeof this.uri !== 'string') {
throw 'Please define an URI';
}
if (typeof this.options.onSuccess !== 'function') {
throw 'please define a callback function on option onSuccess!';
}
Ink.Net.JsonP[this.options.internalCallback] = Ink.bind(function() {
window.clearTimeout(this.timeout);
delete window.Ink.Net.JsonP[this.options.internalCallback];
this._removeScriptTag();
this.options.onSuccess(arguments[0]);
}, this);
this._addScriptTag();
},
_addParamsToGet: function(uri, params) {
var hasQuestionMark = uri.indexOf('?') !== -1;
var sep, pKey, pValue, parts = [uri];
for (pKey in params) {
if (params.hasOwnProperty(pKey)) {
if (!hasQuestionMark) { sep = '?'; hasQuestionMark = true; }
else { sep = '&'; }
pValue = params[pKey];
if (typeof pValue !== 'number' && !pValue) { pValue = ''; }
parts = parts.concat([sep, pKey, '=', encodeURIComponent(pValue)]);
}
}
return parts.join('');
},
_getScriptContainer: function() {
var headEls = document.getElementsByTagName('head');
if (headEls.length === 0) {
var scriptEls = document.getElementsByTagName('script');
return scriptEls[0];
}
return headEls[0];
},
_addScriptTag: function() {
// enrich options will callback and random seed
this.options.params[this.options.callbackParam] = 'Ink.Net.JsonP.' + this.options.internalCallback;
this.options.params.rnd_seed = this.randVar;
this.uri = this._addParamsToGet(this.uri, this.options.params);
// create script tag
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = this.uri;
var scriptCtn = this._getScriptContainer();
scriptCtn.appendChild(scriptEl);
this.timeout = setTimeout(Ink.bind(this._requestFailed, this), (this.options.timeout * 1000));
},
_requestFailed : function () {
delete Ink.Net.JsonP[this.options.internalCallback];
this._removeScriptTag();
if(typeof this.options.onFailure === 'function'){
this.options.onFailure(this.options.failureObj);
}
},
_removeScriptTag: function() {
var scriptEl;
var scriptEls = document.getElementsByTagName('script');
var scriptUri;
for (var i = 0, f = scriptEls.length; i < f; ++i) {
scriptEl = scriptEls[i];
scriptUri = scriptEl.getAttribute('src') || scriptEl.src;
if (scriptUri !== null && scriptUri === this.uri) {
scriptEl.parentNode.removeChild(scriptEl);
return;
}
}
}
};
return JsonP;
});
/**
* @author inkdev AT sapo.pt
*/
Ink.createModule( 'Ink.Dom.Css', 1, [], function() {
'use strict';
/**
* @module Ink.Dom.Css_1
*/
/**
* @class Ink.Dom.Css
* @static
*/
var DomCss = {
/**
* adds or removes a class to the given element according to addRemState
*
* @method addRemoveClassName
* @param {DOMElement|string} elm DOM element or element id
* @param {string} className class name to add or remove.
* @param {boolean} addRemState Whether to add or remove. `true` to add, `false` to remove.
*
* @example
* Ink.requireModules(['Ink.Dom.Css_1'], function (Css) {
* Css.addRemoveClassName(myElm, 'classss', true); // Adds the `classss` class.
* Css.addRemoveClassName(myElm, 'classss', false); // Removes the `classss` class.
* });
*/
addRemoveClassName: function(elm, className, addRemState) {
if (addRemState) {
return this.addClassName(elm, className);
}
this.removeClassName(elm, className);
},
/**
* add a class to a given element
*
* @method addClassName
* @param {DOMElement|String} elm DOM element or element id
* @param {String} className
*/
addClassName: function(elm, className) {
elm = Ink.i(elm);
if (elm && className) {
if (typeof elm.classList !== "undefined"){
elm.classList.add(className);
}
else if (!this.hasClassName(elm, className)) {
elm.className += (elm.className ? ' ' : '') + className;
}
}
},
/**
* removes a class from a given element
*
* @method removeClassName
* @param {DOMElement|String} elm DOM element or element id
* @param {String} className
*/
removeClassName: function(elm, className) {
elm = Ink.i(elm);
if (elm && className) {
if (typeof elm.classList !== "undefined"){
elm.classList.remove(className);
} else {
if (typeof elm.className === "undefined") {
return false;
}
var elmClassName = elm.className,
re = new RegExp("(^|\\s+)" + className + "(\\s+|$)");
elmClassName = elmClassName.replace(re, ' ');
elmClassName = elmClassName.replace(/^\s+/, '').replace(/\s+$/, '');
elm.className = elmClassName;
}
}
},
/**
* Alias to addRemoveClassName. Utility function, saves many if/elses.
*
* @method setClassName
* @param {DOMElement|String} elm DOM element or element id
* @param {String} className
* @param {Boolean} add true to add, false to remove
*/
setClassName: function(elm, className, add) {
this.addRemoveClassName(elm, className, add || false);
},
/**
* @method hasClassName
* @param {DOMElement|String} elm DOM element or element id
* @param {String} className
* @return {Boolean} true if a given class is applied to a given element
*/
hasClassName: function(elm, className) {
elm = Ink.i(elm);
if (elm && className) {
if (typeof elm.classList !== "undefined"){
return elm.classList.contains(className);
}
else {
if (typeof elm.className === "undefined") {
return false;
}
var elmClassName = elm.className;
if (typeof elmClassName.length === "undefined") {
return false;
}
if (elmClassName.length > 0) {
if (elmClassName === className) {
return true;
}
else {
var re = new RegExp("(^|\\s)" + className + "(\\s|$)");
if (re.test(elmClassName)) {
return true;
}
}
}
}
}
return false;
},
/**
* Add and removes the class from the element with a timeout, so it blinks
*
* @method blinkClass
* @param {DOMElement|String} elm DOM element or element id
* @param {String} className class name
* @param {Boolean} timeout timeout in ms between adding and removing, default 100 ms
* @param {Boolean} negate is true, class is removed then added
*/
blinkClass: function(element, className, timeout, negate){
element = Ink.i(element);
this.addRemoveClassName(element, className, !negate);
setTimeout(Ink.bind(function() {
this.addRemoveClassName(element, className, negate);
}, this), Number(timeout) || 100);
/*
var _self = this;
setTimeout(function() {
console.log(_self);
_self.addRemoveClassName(element, className, negate);
}, Number(timeout) || 100);
*/
},
/**
* Add or remove a class name from a given element
*
* @method toggleClassName
* @param {DOMElement|String} elm DOM element or element id
* @param {String} className class name
* @param {Boolean} forceAdd forces the addition of the class if it doesn't exists
*/
toggleClassName: function(elm, className, forceAdd) {
if (elm && className){
if (typeof elm.classList !== "undefined"){
elm = Ink.i(elm);
if (elm !== null){
elm.classList.toggle(className);
}
return true;
}
}
if (typeof forceAdd !== 'undefined') {
if (forceAdd === true) {
this.addClassName(elm, className);
}
else if (forceAdd === false) {
this.removeClassName(elm, className);
}
} else {
if (this.hasClassName(elm, className)) {
this.removeClassName(elm, className);
}
else {
this.addClassName(elm, className);
}
}
},
/**
* sets the opacity of given client a given element
*
* @method setOpacity
* @param {DOMElement|String} elm DOM element or element id
* @param {Number} value allows 0 to 1(default mode decimal) or percentage (warning using 0 or 1 will reset to default mode)
*/
setOpacity: function(elm, value) {
elm = Ink.i(elm);
if (elm !== null){
var val = 1;
if (!isNaN(Number(value))){
if (value <= 0) { val = 0; }
else if (value <= 1) { val = value; }
else if (value <= 100) { val = value / 100; }
else { val = 1; }
}
if (typeof elm.style.opacity !== 'undefined') {
elm.style.opacity = val;
}
else {
elm.style.filter = "alpha(opacity:"+(val*100|0)+")";
}
}
},
/**
* Converts a css property name to a string in camelcase to be used with CSSStyleDeclaration.
* @method _camelCase
* @private
* @param {String} str String to convert
* @return {String} Converted string
*/
_camelCase: function(str) {
return str ? str.replace(/-(\w)/g, function (_, $1){
return $1.toUpperCase();
}) : str;
},
/**
* Gets the value for an element's style attribute
*
* @method getStyle
* @param {DOMElement|String} elm DOM element or element id
* @param {String} style Which css attribute to fetch
* @return Style value
*/
getStyle: function(elm, style) {
elm = Ink.i(elm);
if (elm !== null) {
style = style === 'float' ? 'cssFloat': this._camelCase(style);
var value = elm.style[style];
if (window.getComputedStyle && (!value || value === 'auto')) {
var css = window.getComputedStyle(elm, null);
value = css ? css[style] : null;
}
else if (!value && elm.currentStyle) {
value = elm.currentStyle[style];
if (value === 'auto' && (style === 'width' || style === 'height')) {
value = elm["offset" + style.charAt(0).toUpperCase() + style.slice(1)] + "px";
}
}
if (style === 'opacity') {
return value ? parseFloat(value, 10) : 1.0;
}
else if (style === 'borderTopWidth' || style === 'borderBottomWidth' ||
style === 'borderRightWidth' || style === 'borderLeftWidth' ) {
if (value === 'thin') { return '1px'; }
else if (value === 'medium') { return '3px'; }
else if (value === 'thick') { return '5px'; }
}
return value === 'auto' ? null : value;
}
},
/**
* Adds CSS rules to an element's style attribute.
*
* @method setStyle
* @param {DOMElement|String} elm DOM element or element id
* @param {String} style Which css attribute to set
*
* @example
* <a href="#" class="change-color">Change his color</a>
* <p class="him">"He" is me</p>
* <script type="text/javascript">
* Ink.requireModules(['Ink.Dom.Css_1', 'Ink.Dom.Event_1', 'Ink.Dom.Selector_1'], function (Css, InkEvent, Selector) {
* var btn = Selector.select('.change-color')[0];
* var other = Selector.select('.him')[0];
* InkEvent.observe(btn, 'click', function () {
* Css.setStyle(other, 'background-color: black');
* Css.setStyle(other, 'color: white');
* });
* });
* </script>
*
*/
setStyle: function(elm, style) {
elm = Ink.i(elm);
if (elm !== null) {
if (typeof style === 'string') {
elm.style.cssText += '; '+style;
if (style.indexOf('opacity') !== -1) {
this.setOpacity(elm, style.match(/opacity:\s*(\d?\.?\d*)/)[1]);
}
}
else {
for (var prop in style) {
if (style.hasOwnProperty(prop)){
if (prop === 'opacity') {
this.setOpacity(elm, style[prop]);
}
else {
if (prop === 'float' || prop === 'cssFloat') {
if (typeof elm.style.styleFloat === 'undefined') {
elm.style.cssFloat = style[prop];
}
else {
elm.style.styleFloat = style[prop];
}
} else {
elm.style[prop] = style[prop];
}
}
}
}
}
}
},
/**
* Makes an element visible
*
* @method show
* @param {DOMElement|String} elm DOM element or element id
* @param {String} forceDisplayProperty Css display property to apply on show
*/
show: function(elm, forceDisplayProperty) {
elm = Ink.i(elm);
if (elm !== null) {
elm.style.display = (forceDisplayProperty) ? forceDisplayProperty : '';
}
},
/**
* Hides an element
*
* @method hide
* @param {DOMElement|String} elm DOM element or element id
*/
hide: function(elm) {
elm = Ink.i(elm);
if (elm !== null) {
elm.style.display = 'none';
}
},
/**
* shows or hides according to param show
*
* @method showHide
* @param {DOMElement|String} elm DOM element or element id
* @param {boolean} [show=false] Whether to show or hide `elm`.
*/
showHide: function(elm, show) {
elm = Ink.i(elm);
if (elm) {
elm.style.display = show ? '' : 'none';
}
},
/**
* Shows or hides an element depending on current state
* @method toggle
* @param {DOMElement|String} elm DOM element or element id
* @param {Boolean} forceShow Forces showing if element is hidden
*/
toggle: function(elm, forceShow) {
elm = Ink.i(elm);
if (elm !== null) {
if (typeof forceShow !== 'undefined') {
if (forceShow === true) {
this.show(elm);
} else {
this.hide(elm);
}
} else {
if (elm.style.display === 'none') {
this.show(elm);
}
else {
this.hide(elm);
}
}
}
},
_getRefTag: function(head){
if (head.firstElementChild) {
return head.firstElementChild;
}
for (var child = head.firstChild; child; child = child.nextSibling){
if (child.nodeType === 1){
return child;
}
}
return null;
},
/**
* Adds css style tags to the head section of a page
*
* @method appendStyleTag
* @param {String} selector The css selector for the rule
* @param {String} style The content of the style rule
* @param {Object} options Options for the tag
* @param {String} [options.type] file type
* @param {Boolean} [options.force] if true, style tag will be appended to end of head
*/
appendStyleTag: function(selector, style, options){
options = Ink.extendObj({
type: 'text/css',
force: false
}, options || {});
var styles = document.getElementsByTagName("style"),
oldStyle = false, setStyle = true, i, l;
for (i=0, l=styles.length; i<l; i++) {
oldStyle = styles[i].innerHTML;
if (oldStyle.indexOf(selector) >= 0) {
setStyle = false;
}
}
if (setStyle) {
var defStyle = document.createElement("style"),
head = document.getElementsByTagName("head")[0],
refTag = false, styleStr = '';
defStyle.type = options.type;
styleStr += selector +" {";
styleStr += style;
styleStr += "} ";
if (typeof defStyle.styleSheet !== "undefined") {
defStyle.styleSheet.cssText = styleStr;
} else {
defStyle.appendChild(document.createTextNode(styleStr));
}
if (options.force){
head.appendChild(defStyle);
} else {
refTag = this._getRefTag(head);
if (refTag){
head.insertBefore(defStyle, refTag);
}
}
}
},
/**
* Adds a link tag for a stylesheet to the head section of a page
*
* @method appendStylesheet
* @param {String} path File path
* @param {Object} options Options for the tag
* @param {String} [options.media='screen'] media type
* @param {String} [options.type='text/css'] file type
* @param {Boolean} [options.force=false] if true, tag will be appended to end of head
*/
appendStylesheet: function(path, options){
options = Ink.extendObj({
media: 'screen',
type: 'text/css',
force: false
}, options || {});
var refTag,
style = document.createElement("link"),
head = document.getElementsByTagName("head")[0];
style.media = options.media;
style.type = options.type;
style.href = path;
style.rel = "Stylesheet";
if (options.force){
head.appendChild(style);
}
else {
refTag = this._getRefTag(head);
if (refTag){
head.insertBefore(style, refTag);
}
}
},
/**
* Loads CSS via LINK element inclusion in HEAD (skips append if already there)
*
* Works similarly to appendStylesheet but:
* a) supports all browsers;
* b) supports optional callback which gets invoked once the CSS has been applied
*
* @method appendStylesheetCb
* @param {String} cssURI URI of the CSS to load, if empty ignores and just calls back directly
* @param {Function(cssURI)} [callback] optional callback which will be called once the CSS is loaded
*/
_loadingCSSFiles: {},
_loadedCSSFiles: {},
appendStylesheetCb: function(url, callback) {
if (!url) {
return callback(url);
}
if (this._loadedCSSFiles[url]) {
return callback(url);
}
var cbs = this._loadingCSSFiles[url];
if (cbs) {
return cbs.push(callback);
}
this._loadingCSSFiles[url] = [callback];
var linkEl = document.createElement('link');
linkEl.type = 'text/css';
linkEl.rel = 'stylesheet';
linkEl.href = url;
var headEl = document.getElementsByTagName('head')[0];
headEl.appendChild(linkEl);
var imgEl = document.createElement('img');
/*
var _self = this;
(function(_url) {
imgEl.onerror = function() {
//var url = this;
var url = _url;
_self._loadedCSSFiles[url] = true;
var callbacks = _self._loadingCSSFiles[url];
for (var i = 0, f = callbacks.length; i < f; ++i) {
callbacks[i](url);
}
delete _self._loadingCSSFiles[url];
};
})(url);
*/
imgEl.onerror = Ink.bindEvent(function(event, _url) {
//var url = this;
var url = _url;
this._loadedCSSFiles[url] = true;
var callbacks = this._loadingCSSFiles[url];
for (var i = 0, f = callbacks.length; i < f; ++i) {
callbacks[i](url);
}
delete this._loadingCSSFiles[url];
}, this, url);
imgEl.src = url;
},
/**
* Converts decimal to hexadecimal values, for use with colors
*
* @method decToHex
* @param {String} dec Either a single decimal value,
* an rgb(r, g, b) string or an Object with r, g and b properties
* @return Hexadecimal value
*/
decToHex: function(dec) {
var normalizeTo2 = function(val) {
if (val.length === 1) {
val = '0' + val;
}
val = val.toUpperCase();
return val;
};
if (typeof dec === 'object') {
var rDec = normalizeTo2(parseInt(dec.r, 10).toString(16));
var gDec = normalizeTo2(parseInt(dec.g, 10).toString(16));
var bDec = normalizeTo2(parseInt(dec.b, 10).toString(16));
return rDec+gDec+bDec;
}
else {
dec += '';
var rgb = dec.match(/\((\d+),\s?(\d+),\s?(\d+)\)/);
if (rgb !== null) {
return normalizeTo2(parseInt(rgb[1], 10).toString(16)) +
normalizeTo2(parseInt(rgb[2], 10).toString(16)) +
normalizeTo2(parseInt(rgb[3], 10).toString(16));
}
else {
return normalizeTo2(parseInt(dec, 10).toString(16));
}
}
},
/**
* Converts hexadecimal values to decimal, for use with colors
*
* @method hexToDec
* @param {String} hex hexadecimal value with 6, 3, 2 or 1 characters
* @return {Number} Object with properties r, g, b if length of number is >= 3 or decimal value instead.
*/
hexToDec: function(hex){
if (hex.indexOf('#') === 0) {
hex = hex.substr(1);
}
if (hex.length === 6) { // will return object RGB
return {
r: parseInt(hex.substr(0,2), 16),
g: parseInt(hex.substr(2,2), 16),
b: parseInt(hex.substr(4,2), 16)
};
}
else if (hex.length === 3) { // will return object RGB
return {
r: parseInt(hex.charAt(0) + hex.charAt(0), 16),
g: parseInt(hex.charAt(1) + hex.charAt(1), 16),
b: parseInt(hex.charAt(2) + hex.charAt(2), 16)
};
}
else if (hex.length <= 2) { // will return int
return parseInt(hex, 16);
}
},
/**
* use this to obtain the value of a CSS property (searched from loaded CSS documents)
*
* @method getPropertyFromStylesheet
* @param {String} selector a CSS rule. must be an exact match
* @param {String} property a CSS property
* @return {String} value of the found property, or null if it wasn't matched
*/
getPropertyFromStylesheet: function(selector, property) {
var rule = this.getRuleFromStylesheet(selector);
if (rule) {
return rule.style[property];
}
return null;
},
getPropertyFromStylesheet2: function(selector, property) {
var rules = this.getRulesFromStylesheet(selector);
/*
rules.forEach(function(rule) {
var x = rule.style[property];
if (x !== null && x !== undefined) {
return x;
}
});
*/
var x;
for(var i=0, t=rules.length; i < t; i++) {
x = rules[i].style[property];
if (x !== null && x !== undefined) {
return x;
}
}
return null;
},
getRuleFromStylesheet: function(selector) {
var sheet, rules, ri, rf, rule;
var s = document.styleSheets;
if (!s) {
return null;
}
for (var si = 0, sf = document.styleSheets.length; si < sf; ++si) {
sheet = document.styleSheets[si];
rules = sheet.rules ? sheet.rules : sheet.cssRules;
if (!rules) { return null; }
for (ri = 0, rf = rules.length; ri < rf; ++ri) {
rule = rules[ri];
if (!rule.selectorText) { continue; }
if (rule.selectorText === selector) {
return rule;
}
}
}
return null;
},
getRulesFromStylesheet: function(selector) {
var res = [];
var sheet, rules, ri, rf, rule;
var s = document.styleSheets;
if (!s) { return res; }
for (var si = 0, sf = document.styleSheets.length; si < sf; ++si) {
sheet = document.styleSheets[si];
rules = sheet.rules ? sheet.rules : sheet.cssRules;
if (!rules) {
return null;
}
for (ri = 0, rf = rules.length; ri < rf; ++ri) {
rule = rules[ri];
if (!rule.selectorText) { continue; }
if (rule.selectorText === selector) {
res.push(rule);
}
}
}
return res;
},
getPropertiesFromRule: function(selector) {
var rule = this.getRuleFromStylesheet(selector);
var props = {};
var prop, i, f;
/*if (typeof rule.style.length === 'snumber') {
for (i = 0, f = rule.style.length; i < f; ++i) {
prop = this._camelCase( rule.style[i] );
props[prop] = rule.style[prop];
}
}
else { // HANDLES IE 8, FIREFOX RULE JOINING... */
rule = rule.style.cssText;
var parts = rule.split(';');
var steps, val, pre, pos;
for (i = 0, f = parts.length; i < f; ++i) {
if (parts[i].charAt(0) === ' ') {
parts[i] = parts[i].substring(1);
}
steps = parts[i].split(':');
prop = this._camelCase( steps[0].toLowerCase() );
val = steps[1];
if (val) {
val = val.substring(1);
if (prop === 'padding' || prop === 'margin' || prop === 'borderWidth') {
if (prop === 'borderWidth') { pre = 'border'; pos = 'Width'; }
else { pre = prop; pos = ''; }
if (val.indexOf(' ') !== -1) {
val = val.split(' ');
props[pre + 'Top' + pos] = val[0];
props[pre + 'Bottom'+ pos] = val[0];
props[pre + 'Left' + pos] = val[1];
props[pre + 'Right' + pos] = val[1];
}
else {
props[pre + 'Top' + pos] = val;
props[pre + 'Bottom'+ pos] = val;
props[pre + 'Left' + pos] = val;
props[pre + 'Right' + pos] = val;
}
}
else if (prop === 'borderRadius') {
if (val.indexOf(' ') !== -1) {
val = val.split(' ');
props.borderTopLeftRadius = val[0];
props.borderBottomRightRadius = val[0];
props.borderTopRightRadius = val[1];
props.borderBottomLeftRadius = val[1];
}
else {
props.borderTopLeftRadius = val;
props.borderTopRightRadius = val;
props.borderBottomLeftRadius = val;
props.borderBottomRightRadius = val;
}
}
else {
props[prop] = val;
}
}
}
//}
//console.log(props);
return props;
},
/**
* Changes the font size of the elements which match the given CSS rule
* For this function to work, the CSS file must be in the same domain than the host page, otherwise JS can't access it.
*
* @method changeFontSize
* @param {String} selector CSS selector rule
* @param {Number} delta number of pixels to change on font-size
* @param {String} [op] supported operations are '+' and '*'. defaults to '+'
* @param {Number} [minVal] if result gets smaller than minVal, change does not occurr
* @param {Number} [maxVal] if result gets bigger than maxVal, change does not occurr
*/
changeFontSize: function(selector, delta, op, minVal, maxVal) {
var that = this;
Ink.requireModules(['Ink.Dom.Selector_1'], function(Selector) {
var e;
if (typeof selector !== 'string') { e = '1st argument must be a CSS selector rule.'; }
else if (typeof delta !== 'number') { e = '2nd argument must be a number.'; }
else if (op !== undefined && op !== '+' && op !== '*') { e = '3rd argument must be one of "+", "*".'; }
else if (minVal !== undefined && (typeof minVal !== 'number' || minVal <= 0)) { e = '4th argument must be a positive number.'; }
else if (maxVal !== undefined && (typeof maxVal !== 'number' || maxVal < maxVal)) { e = '5th argument must be a positive number greater than minValue.'; }
if (e) { throw new TypeError(e); }
var val, el, els = Selector.select(selector);
if (minVal === undefined) { minVal = 1; }
op = (op === '*') ? function(a,b){return a*b;} : function(a,b){return a+b;};
for (var i = 0, f = els.length; i < f; ++i) {
el = els[i];
val = parseFloat( that.getStyle(el, 'fontSize'));
val = op(val, delta);
if (val < minVal) { continue; }
if (typeof maxVal === 'number' && val > maxVal) { continue; }
el.style.fontSize = val + 'px';
}
});
}
};
return DomCss;
});
/**
* @author inkdev AT sapo.pt
*/
Ink.createModule('Ink.Dom.Element', 1, [], function() {
'use strict';
/**
* @module Ink.Dom.Element_1
*/
/**
* @class Ink.Dom.Element
*/
var Element = {
/**
* Shortcut for `document.getElementById`
*
* @method get
* @param {String|DOMElement} elm Either an ID of an element, or an element.
* @return {DOMElement|null} The DOM element with the given id or null when it was not found
*/
get: function(elm) {
if(typeof elm !== 'undefined') {
if(typeof elm === 'string') {
return document.getElementById(elm);
}
return elm;
}
return null;
},
/**
* Creates a DOM element
*
* @method create
* @param {String} tag tag name
* @param {Object} properties object with properties to be set on the element
*/
create: function(tag, properties) {
var el = document.createElement(tag);
//Ink.extendObj(el, properties);
for(var property in properties) {
if(properties.hasOwnProperty(property)) {
if(property === 'className') {
property = 'class';
}
el.setAttribute(property, properties[property]);
}
}
return el;
},
/**
* Removes a DOM Element from the DOM
*
* @method remove
* @param {DOMElement} elm The element to remove
*/
remove: function(el) {
var parEl;
if (el && (parEl = el.parentNode)) {
parEl.removeChild(el);
}
},
/**
* Scrolls the window to an element
*
* @method scrollTo
* @param {DOMElement|String} elm Element where to scroll
*/
scrollTo: function(elm) {
elm = this.get(elm);
if(elm) {
if (elm.scrollIntoView) {
return elm.scrollIntoView();
}
var elmOffset = {},
elmTop = 0, elmLeft = 0;
do {
elmTop += elm.offsetTop || 0;
elmLeft += elm.offsetLeft || 0;
elm = elm.offsetParent;
} while(elm);
elmOffset = {x: elmLeft, y: elmTop};
window.scrollTo(elmOffset.x, elmOffset.y);
}
},
/**
* Gets the top cumulative offset for an element
*
* Requires Ink.Dom.Browser
*
* @method offsetTop
* @param {DOMElement|String} elm target element
* @return {Number} Offset from the target element to the top of the document
*/
offsetTop: function(elm) {
return this.offset(elm)[1];
},
/**
* Gets the left cumulative offset for an element
*
* Requires Ink.Dom.Browser
*
* @method offsetLeft
* @param {DOMElement|String} elm target element
* @return {Number} Offset from the target element to the left of the document
*/
offsetLeft: function(elm) {
return this.offset(elm)[0];
},
/**
* Gets the element offset relative to its closest positioned ancestor
*
* @method positionedOffset
* @param {DOMElement|String} elm target element
* @return {Array} Array with the element offsetleft and offsettop relative to the closest positioned ancestor
*/
positionedOffset: function(element) {
var valueTop = 0, valueLeft = 0;
element = this.get(element);
do {
valueTop += element.offsetTop || 0;
valueLeft += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
if (element.tagName.toLowerCase() === 'body') { break; }
var value = element.style.position;
if (!value && element.currentStyle) {
value = element.currentStyle.position;
}
if ((!value || value === 'auto') && typeof getComputedStyle !== 'undefined') {
var css = getComputedStyle(element, null);
value = css ? css.position : null;
}
if (value === 'relative' || value === 'absolute') { break; }
}
} while (element);
return [valueLeft, valueTop];
},
/**
* Gets the cumulative offset for an element
*
* Returns the top left position of the element on the page
*
* Requires Ink.Dom.Browser
*
* @method offset
* @param {DOMElement|String} elm Target element
* @return {[Number, Number]} Array with pixel distance from the target element to the top left corner of the document
*/
offset: function(el) {
/*jshint boss:true */
el = Ink.i(el);
var bProp = ['border-left-width', 'border-top-width'];
var res = [0, 0];
var dRes, bRes, parent, cs;
var getPropPx = this._getPropPx;
var InkBrowser = Ink.getModule('Ink.Dom.Browser', 1);
do {
cs = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
dRes = [el.offsetLeft | 0, el.offsetTop | 0];
bRes = [getPropPx(cs, bProp[0]), getPropPx(cs, bProp[1])];
if( InkBrowser.OPERA ){
res[0] += dRes[0];
res[1] += dRes[1];
} else {
res[0] += dRes[0] + bRes[0];
res[1] += dRes[1] + bRes[1];
}
parent = el.offsetParent;
} while (el = parent);
bRes = [getPropPx(cs, bProp[0]), getPropPx(cs, bProp[1])];
if (InkBrowser.GECKO) {
res[0] += bRes[0];
res[1] += bRes[1];
}
else if( !InkBrowser.OPERA ) {
res[0] -= bRes[0];
res[1] -= bRes[1];
}
return res;
},
/**
* Gets the scroll of the element
*
* @method scroll
* @param {DOMElement|String} [elm] target element or document.body
* @returns {Array} offset values for x and y scroll
*/
scroll: function(elm) {
elm = elm ? Ink.i(elm) : document.body;
return [
( ( !window.pageXOffset ) ? elm.scrollLeft : window.pageXOffset ),
( ( !window.pageYOffset ) ? elm.scrollTop : window.pageYOffset )
];
},
_getPropPx: function(cs, prop) {
var n, c;
var val = cs.getPropertyValue ? cs.getPropertyValue(prop) : cs[prop];
if (!val) { n = 0; }
else {
c = val.indexOf('px');
if (c === -1) { n = 0; }
else {
n = parseInt(val, 10);
}
}
//console.log([prop, ' "', val, '" ', n].join(''));
return n;
},
/**
* Alias for offset()
*
* @method offset2
* @deprecated Kept for historic reasons. Use offset() instead.
*/
offset2: function(el) {
return this.offset(el);
},
/**
* Verifies the existence of an attribute
*
* @method hasAttribute
* @param {Object} elm target element
* @param {String} attr attribute name
* @return {Boolean} Boolean based on existance of attribute
*/
hasAttribute: function(elm, attr){
return elm.hasAttribute ? elm.hasAttribute(attr) : !!elm.getAttribute(attr);
},
/**
* Inserts a element immediately after a target element
*
* @method insertAfter
* @param {DOMElement} newElm element to be inserted
* @param {DOMElement|String} targetElm key element
*/
insertAfter: function(newElm, targetElm) {
/*jshint boss:true */
if (targetElm = this.get(targetElm)) {
targetElm.parentNode.insertBefore(newElm, targetElm.nextSibling);
}
},
/**
* Inserts a element at the top of the childNodes of a target element
*
* @method insertTop
* @param {DOMElement} newElm element to be inserted
* @param {DOMElement|String} targetElm key element
*/
insertTop: function(newElm,targetElm) { // TODO check first child exists
/*jshint boss:true */
if (targetElm = this.get(targetElm)) {
targetElm.insertBefore(newElm, targetElm.firstChild);
}
},
/**
* Retreives textContent from node
*
* @method textContent
* @param {DOMNode} node from which to retreive text from. Can be any node type.
* @return {String} the text
*/
textContent: function(node){
node = Ink.i(node);
var text, k, cs, m;
switch(node && node.nodeType) {
case 9: /*DOCUMENT_NODE*/
// IE quirks mode does not have documentElement
return this.textContent(node.documentElement || node.body && node.body.parentNode || node.body);
case 1: /*ELEMENT_NODE*/
text = node.innerText;
if (typeof text !== 'undefined') {
return text;
}
/* falls through */
case 11: /*DOCUMENT_FRAGMENT_NODE*/
text = node.textContent;
if (typeof text !== 'undefined') {
return text;
}
if (node.firstChild === node.lastChild) {
// Common case: 0 or 1 children
return this.textContent(node.firstChild);
}
text = [];
cs = node.childNodes;
for (k = 0, m = cs.length; k < m; ++k) {
text.push( this.textContent( cs[k] ) );
}
return text.join('');
case 3: /*TEXT_NODE*/
case 4: /*CDATA_SECTION_NODE*/
return node.nodeValue;
}
return '';
},
/**
* Removes all nodes children and adds the text
*
* @method setTextContent
* @param {DOMNode} node node to add the text to. Can be any node type.
* @param {String} text text to be appended to the node.
*/
setTextContent: function(node, text){
node = Ink.i(node);
switch(node && node.nodeType)
{
case 1: /*ELEMENT_NODE*/
if ('innerText' in node) {
node.innerText = text;
break;
}
/* falls through */
case 11: /*DOCUMENT_FRAGMENT_NODE*/
if ('textContent' in node) {
node.textContent = text;
break;
}
/* falls through */
case 9: /*DOCUMENT_NODE*/
while(node.firstChild) {
node.removeChild(node.firstChild);
}
if (text !== '') {
var doc = node.ownerDocument || node;
node.appendChild(doc.createTextNode(text));
}
break;
case 3: /*TEXT_NODE*/
case 4: /*CDATA_SECTION_NODE*/
node.nodeValue = text;
break;
}
},
/**
* Tells if element is a clickable link
*
* @method isLink
* @param {DOMNode} node node to check if it's link
* @return {Boolean}
*/
isLink: function(element){
var b = element && element.nodeType === 1 && ((/^a|area$/i).test(element.tagName) ||
element.hasAttributeNS && element.hasAttributeNS('http://www.w3.org/1999/xlink','href'));
return !!b;
},
/**
* Tells if ancestor is ancestor of node
*
* @method isAncestorOf
* @param {DOMNode} ancestor ancestor node
* @param {DOMNode} node descendant node
* @return {Boolean}
*/
isAncestorOf: function(ancestor, node){
/*jshint boss:true */
if (!node || !ancestor) {
return false;
}
if (node.compareDocumentPosition) {
return (ancestor.compareDocumentPosition(node) & 0x10) !== 0;/*Node.DOCUMENT_POSITION_CONTAINED_BY*/
}
while (node = node.parentNode){
if (node === ancestor){
return true;
}
}
return false;
},
/**
* Tells if descendant is descendant of node
*
* @method descendantOf
* @param {DOMNode} node the ancestor
* @param {DOMNode} descendant the descendant
* @return {Boolean} true if 'descendant' is descendant of 'node'
*/
descendantOf: function(node, descendant){
return node !== descendant && this.isAncestorOf(node, descendant);
},
/**
* Get first child in document order of node type 1
* @method firstElementChild
* @param {DOMNode} elm parent node
* @return {DOMNode} the element child
*/
firstElementChild: function(elm){
if(!elm) {
return null;
}
if ('firstElementChild' in elm) {
return elm.firstElementChild;
}
var child = elm.firstChild;
while(child && child.nodeType !== 1) {
child = child.nextSibling;
}
return child;
},
/**
* Get last child in document order of node type 1
* @method lastElementChild
* @param {DOMNode} elm parent node
* @return {DOMNode} the element child
*/
lastElementChild: function(elm){
if(!elm) {
return null;
}
if ('lastElementChild' in elm) {
return elm.lastElementChild;
}
var child = elm.lastChild;
while(child && child.nodeType !== 1) {
child = child.previousSibling;
}
return child;
},
/**
* Get the first element sibling after the node
*
* @method nextElementSibling
* @param {DOMNode} node current node
* @return {DOMNode|Null} the first element sibling after node or null if none is found
*/
nextElementSibling: function(node){
var sibling = null;
if(!node){ return sibling; }
if("nextElementSibling" in node){
return node.nextElementSibling;
} else {
sibling = node.nextSibling;
// 1 === Node.ELEMENT_NODE
while(sibling && sibling.nodeType !== 1){
sibling = sibling.nextSibling;
}
return sibling;
}
},
/**
* Get the first element sibling before the node
*
* @method previousElementSibling
* @param {DOMNode} node current node
* @return {DOMNode|Null} the first element sibling before node or null if none is found
*/
previousElementSibling: function(node){
var sibling = null;
if(!node){ return sibling; }
if("previousElementSibling" in node){
return node.previousElementSibling;
} else {
sibling = node.previousSibling;
// 1 === Node.ELEMENT_NODE
while(sibling && sibling.nodeType !== 1){
sibling = sibling.previousSibling;
}
return sibling;
}
},
/**
* Returns the width of the given element, in pixels
*
* @method elementWidth
* @param {DOMElement|string} element target DOM element or target ID
* @return {Number} the element's width
*/
elementWidth: function(element) {
if(typeof element === "string") {
element = document.getElementById(element);
}
return element.offsetWidth;
},
/**
* Returns the height of the given element, in pixels
*
* @method elementHeight
* @param {DOMElement|string} element target DOM element or target ID
* @return {Number} the element's height
*/
elementHeight: function(element) {
if(typeof element === "string") {
element = document.getElementById(element);
}
return element.offsetHeight;
},
/**
* Returns the element's left position in pixels
*
* @method elementLeft
* @param {DOMElement|string} element target DOM element or target ID
* @return {Number} element's left position
*/
elementLeft: function(element) {
if(typeof element === "string") {
element = document.getElementById(element);
}
return element.offsetLeft;
},
/**
* Returns the element's top position in pixels
*
* @method elementTop
* @param {DOMElement|string} element target DOM element or target ID
* @return {Number} element's top position
*/
elementTop: function(element) {
if(typeof element === "string") {
element = document.getElementById(element);
}
return element.offsetTop;
},
/**
* Returns the dimensions of the given element, in pixels
*
* @method elementDimensions
* @param {element} element target element
* @return {Array} array with element's width and height
*/
elementDimensions: function(element) {
element = Ink.i(element);
return [element.offsetWidth, element.offsetHeight];
},
/**
* Returns the outer (width + margin + padding included) dimensions of an element, in pixels.
*
* Requires Ink.Dom.Css
*
* @method uterDimensions
* @param {DOMElement} element Target element
* @return {Array} Array with element width and height.
*/
outerDimensions: function (element) {
var bbox = Element.elementDimensions(element);
var Css = Ink.getModule('Ink.Dom.Css_1');
return [
bbox[0] + parseFloat(Css.getStyle(element, 'marginLeft') || 0) + parseFloat(Css.getStyle(element, 'marginRight') || 0), // w
bbox[1] + parseFloat(Css.getStyle(element, 'marginTop') || 0) + parseFloat(Css.getStyle(element, 'marginBottom') || 0) // h
];
},
/**
* Check whether an element is inside the viewport
*
* @method inViewport
* @param {DOMElement} element Element to check
* @param {Boolean} [partial=false] Return `true` even if it is only partially visible.
* @return {Boolean}
*/
inViewport: function (element, partial) {
var rect = Ink.i(element).getBoundingClientRect();
if (partial) {
return rect.bottom > 0 && // from the top
rect.left < Element.viewportWidth() && // from the right
rect.top < Element.viewportHeight() && // from the bottom
rect.right > 0; // from the left
} else {
return rect.top > 0 && // from the top
rect.right < Element.viewportWidth() && // from the right
rect.bottom < Element.viewportHeight() && // from the bottom
rect.left > 0; // from the left
}
},
/**
* Applies the cloneFrom's dimensions to cloneTo
*
* @method clonePosition
* @param {DOMElement} cloneTo element to be position cloned
* @param {DOMElement} cloneFrom element to get the cloned position
* @return {DOMElement} the element with positionClone
*/
clonePosition: function(cloneTo, cloneFrom){
var pos = this.offset(cloneFrom);
cloneTo.style.left = pos[0]+'px';
cloneTo.style.top = pos[1]+'px';
return cloneTo;
},
/**
* Slices off a piece of text at the end of the element and adds the ellipsis
* so all text fits in the element.
*
* @method ellipsizeText
* @param {DOMElement} element which text is to add the ellipsis
* @param {String} [ellipsis] String to append to the chopped text
*/
ellipsizeText: function(element, ellipsis){
/*jshint boss:true */
if (element = Ink.i(element)){
while (element && element.scrollHeight > (element.offsetHeight + 8)) {
element.textContent = element.textContent.replace(/(\s+\S+)\s*$/, ellipsis || '\u2026');
}
}
},
/**
* Searches up the DOM tree for an element fulfilling the boolTest function (returning trueish)
*
* @method findUpwardsHaving
* @param {HtmlElement} element
* @param {Function} boolTest
* @return {HtmlElement|false} the matched element or false if did not match
*/
findUpwardsHaving: function(element, boolTest) {
while (element && element.nodeType === 1) {
if (boolTest(element)) {
return element;
}
element = element.parentNode;
}
return false;
},
/**
* Śearches up the DOM tree for an element of specified class name
*
* @method findUpwardsByClass
* @param {HtmlElement} element
* @param {String} className
* @returns {HtmlElement|false} the matched element or false if did not match
*/
findUpwardsByClass: function(element, className) {
var re = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tst = function(el) {
var cls = el.className;
return cls && re.test(cls);
};
return this.findUpwardsHaving(element, tst);
},
/**
* Śearches up the DOM tree for an element of specified tag
*
* @method findUpwardsByTag
* @param {HtmlElement} element
* @param {String} tag
* @returns {HtmlElement|false} the matched element or false if did not match
*/
findUpwardsByTag: function(element, tag) {
tag = tag.toUpperCase();
var tst = function(el) {
return el.nodeName && el.nodeName.toUpperCase() === tag;
};
return this.findUpwardsHaving(element, tst);
},
/**
* Śearches up the DOM tree for an element of specified id
*
* @method findUpwardsById
* @param {HtmlElement} element
* @param {String} id
* @returns {HtmlElement|false} the matched element or false if did not match
*/
findUpwardsById: function(element, id) {
var tst = function(el) {
return el.id === id;
};
return this.findUpwardsHaving(element, tst);
},
/**
* Śearches up the DOM tree for an element matching the given selector
*
* @method findUpwardsBySelector
* @param {HtmlElement} element
* @param {String} sel
* @returns {HtmlElement|false} the matched element or false if did not match
*/
findUpwardsBySelector: function(element, sel) {
if (typeof Ink.Dom === 'undefined' || typeof Ink.Dom.Selector === 'undefined') {
throw new Error('This method requires Ink.Dom.Selector');
}
var tst = function(el) {
return Ink.Dom.Selector.matchesSelector(el, sel);
};
return this.findUpwardsHaving(element, tst);
},
/**
* Returns trimmed text content of descendants
*
* @method getChildrenText
* @param {DOMElement} el element being seeked
* @param {Boolean} [removeIt] whether to remove the found text nodes or not
* @return {String} text found
*/
getChildrenText: function(el, removeIt) {
var node,
j,
part,
nodes = el.childNodes,
jLen = nodes.length,
text = '';
if (!el) {
return text;
}
for (j = 0; j < jLen; ++j) {
node = nodes[j];
if (!node) { continue; }
if (node.nodeType === 3) { // TEXT NODE
part = this._trimString( String(node.data) );
if (part.length > 0) {
text += part;
if (removeIt) { el.removeChild(node); }
}
else { el.removeChild(node); }
}
}
return text;
},
/**
* String trim implementation
* Used by getChildrenText
*
* function _trimString
* param {String} text
* return {String} trimmed text
*/
_trimString: function(text) {
return (String.prototype.trim) ? text.trim() : text.replace(/^\s*/, '').replace(/\s*$/, '');
},
/**
* Returns the values of a select element
*
* @method getSelectValues
* @param {DomElement|String} select element
* @return {Array} selected values
*/
getSelectValues: function (select) {
var selectEl = Ink.i(select);
var values = [];
for (var i = 0; i < selectEl.options.length; ++i) {
values.push( selectEl.options[i].value );
}
return values;
},
/* used by fills */
_normalizeData: function(data) {
var d, data2 = [];
for (var i = 0, f = data.length; i < f; ++i) {
d = data[i];
if (!(d instanceof Array)) { // if not array, wraps primitive twice: val -> [val, val]
d = [d, d];
}
else if (d.length === 1) { // if 1 element array: [val] -> [val, val]
d.push(d[0]);
}
data2.push(d);
}
return data2;
},
/**
* Fills select element with choices
*
* @method fillSelect
* @param {DomElement|String} container select element which will get filled
* @param {Array} data data which will populate the component
* @param {Boolean} [skipEmpty] true to skip empty option
* @param {String|Number} [defaultValue] primitive value to select at beginning
*/
fillSelect: function(container, data, skipEmpty, defaultValue) {
var containerEl = Ink.i(container);
if (!containerEl) { return; }
containerEl.innerHTML = '';
var d, optionEl;
if (!skipEmpty) {
// add initial empty option
optionEl = document.createElement('option');
optionEl.setAttribute('value', '');
containerEl.appendChild(optionEl);
}
data = this._normalizeData(data);
for (var i = 0, f = data.length; i < f; ++i) {
d = data[i];
optionEl = document.createElement('option');
optionEl.setAttribute('value', d[0]);
if (d.length > 2) {
optionEl.setAttribute('extra', d[2]);
}
optionEl.appendChild( document.createTextNode(d[1]) );
if (d[0] === defaultValue) {
optionEl.setAttribute('selected', 'selected');
}
containerEl.appendChild(optionEl);
}
},
/**
* Select element on steroids - allows the creation of new values
*
* @method fillSelect2
* @param {DomElement|String} ctn select element which will get filled
* @param {Object} opts
* @param {Array} [opts.data] data which will populate the component
* @param {Boolean} [opts.skipEmpty] if true empty option is not created (defaults to false)
* @param {String} [opts.emptyLabel] label to display on empty option
* @param {String} [opts.createLabel] label to display on create option
* @param {String} [opts.optionsGroupLabel] text to display on group surrounding value options
* @param {String} [opts.defaultValue] option to select initially
* @param {Function(selEl, addOptFn)} [opts.onCreate] callback that gets called once user selects the create option
*/
fillSelect2: function(ctn, opts) {
ctn = Ink.i(ctn);
ctn.innerHTML = '';
var defs = {
skipEmpty: false,
skipCreate: false,
emptyLabel: 'none',
createLabel: 'create',
optionsGroupLabel: 'groups',
emptyOptionsGroupLabel: 'none exist',
defaultValue: ''
};
if (!opts) { throw 'param opts is a requirement!'; }
if (!opts.data) { throw 'opts.data is a requirement!'; }
opts = Ink.extendObj(defs, opts);
var optionEl, d;
var optGroupValuesEl = document.createElement('optgroup');
optGroupValuesEl.setAttribute('label', opts.optionsGroupLabel);
opts.data = this._normalizeData(opts.data);
if (!opts.skipCreate) {
opts.data.unshift(['$create$', opts.createLabel]);
}
if (!opts.skipEmpty) {
opts.data.unshift(['', opts.emptyLabel]);
}
for (var i = 0, f = opts.data.length; i < f; ++i) {
d = opts.data[i];
optionEl = document.createElement('option');
optionEl.setAttribute('value', d[0]);
optionEl.appendChild( document.createTextNode(d[1]) );
if (d[0] === opts.defaultValue) { optionEl.setAttribute('selected', 'selected'); }
if (d[0] === '' || d[0] === '$create$') {
ctn.appendChild(optionEl);
}
else {
optGroupValuesEl.appendChild(optionEl);
}
}
var lastValIsNotOption = function(data) {
var lastVal = data[data.length-1][0];
return (lastVal === '' || lastVal === '$create$');
};
if (lastValIsNotOption(opts.data)) {
optionEl = document.createElement('option');
optionEl.setAttribute('value', '$dummy$');
optionEl.setAttribute('disabled', 'disabled');
optionEl.appendChild( document.createTextNode(opts.emptyOptionsGroupLabel) );
optGroupValuesEl.appendChild(optionEl);
}
ctn.appendChild(optGroupValuesEl);
var addOption = function(v, l) {
var optionEl = ctn.options[ctn.options.length - 1];
if (optionEl.getAttribute('disabled')) {
optionEl.parentNode.removeChild(optionEl);
}
// create it
optionEl = document.createElement('option');
optionEl.setAttribute('value', v);
optionEl.appendChild( document.createTextNode(l) );
optGroupValuesEl.appendChild(optionEl);
// select it
ctn.options[ctn.options.length - 1].setAttribute('selected', true);
};
if (!opts.skipCreate) {
ctn.onchange = function() {
if ((ctn.value === '$create$') && (typeof opts.onCreate === 'function')) { opts.onCreate(ctn, addOption); }
};
}
},
/**
* Creates set of radio buttons, returns wrapper
*
* @method fillRadios
* @param {DomElement|String} insertAfterEl element which will precede the input elements
* @param {String} name name to give to the form field ([] is added if not as suffix already)
* @param {Array} data data which will populate the component
* @param {Boolean} [skipEmpty] true to skip empty option
* @param {String|Number} [defaultValue] primitive value to select at beginning
* @param {String} [splitEl] name of element to add after each input element (example: 'br')
* @return {DOMElement} wrapper element around radio buttons
*/
fillRadios: function(insertAfterEl, name, data, skipEmpty, defaultValue, splitEl) {
var afterEl = Ink.i(insertAfterEl);
afterEl = afterEl.nextSibling;
while (afterEl && afterEl.nodeType !== 1) {
afterEl = afterEl.nextSibling;
}
var containerEl = document.createElement('span');
if (afterEl) {
afterEl.parentNode.insertBefore(containerEl, afterEl);
} else {
Ink.i(insertAfterEl).appendChild(containerEl);
}
data = this._normalizeData(data);
if (name.substring(name.length - 1) !== ']') {
name += '[]';
}
var d, inputEl;
if (!skipEmpty) {
// add initial empty option
inputEl = document.createElement('input');
inputEl.setAttribute('type', 'radio');
inputEl.setAttribute('name', name);
inputEl.setAttribute('value', '');
containerEl.appendChild(inputEl);
if (splitEl) { containerEl.appendChild( document.createElement(splitEl) ); }
}
for (var i = 0; i < data.length; ++i) {
d = data[i];
inputEl = document.createElement('input');
inputEl.setAttribute('type', 'radio');
inputEl.setAttribute('name', name);
inputEl.setAttribute('value', d[0]);
containerEl.appendChild(inputEl);
containerEl.appendChild( document.createTextNode(d[1]) );
if (splitEl) { containerEl.appendChild( document.createElement(splitEl) ); }
if (d[0] === defaultValue) {
inputEl.checked = true;
}
}
return containerEl;
},
/**
* Creates set of checkbox buttons, returns wrapper
*
* @method fillChecks
* @param {DomElement|String} insertAfterEl element which will precede the input elements
* @param {String} name name to give to the form field ([] is added if not as suffix already)
* @param {Array} data data which will populate the component
* @param {Boolean} [skipEmpty] true to skip empty option
* @param {String|Number} [defaultValue] primitive value to select at beginning
* @param {String} [splitEl] name of element to add after each input element (example: 'br')
* @return {DOMElement} wrapper element around checkboxes
*/
fillChecks: function(insertAfterEl, name, data, defaultValue, splitEl) {
var afterEl = Ink.i(insertAfterEl);
afterEl = afterEl.nextSibling;
while (afterEl && afterEl.nodeType !== 1) {
afterEl = afterEl.nextSibling;
}
var containerEl = document.createElement('span');
if (afterEl) {
afterEl.parentNode.insertBefore(containerEl, afterEl);
} else {
Ink.i(insertAfterEl).appendChild(containerEl);
}
data = this._normalizeData(data);
if (name.substring(name.length - 1) !== ']') {
name += '[]';
}
var d, inputEl;
for (var i = 0; i < data.length; ++i) {
d = data[i];
inputEl = document.createElement('input');
inputEl.setAttribute('type', 'checkbox');
inputEl.setAttribute('name', name);
inputEl.setAttribute('value', d[0]);
containerEl.appendChild(inputEl);
containerEl.appendChild( document.createTextNode(d[1]) );
if (splitEl) { containerEl.appendChild( document.createElement(splitEl) ); }
if (d[0] === defaultValue) {
inputEl.checked = true;
}
}
return containerEl;
},
/**
* Returns index of element from parent, -1 if not child of parent...
*
* @method parentIndexOf
* @param {DOMElement} parentEl Element to parse
* @param {DOMElement} childEl Child Element to look for
* @return {Number}
*/
parentIndexOf: function(parentEl, childEl) {
var node, idx = 0;
for (var i = 0, f = parentEl.childNodes.length; i < f; ++i) {
node = parentEl.childNodes[i];
if (node.nodeType === 1) { // ELEMENT
if (node === childEl) { return idx; }
++idx;
}
}
return -1;
},
/**
* Returns an array of elements - the next siblings
*
* @method nextSiblings
* @param {String|DomElement} elm element
* @return {Array} Array of next sibling elements
*/
nextSiblings: function(elm) {
if(typeof(elm) === "string") {
elm = document.getElementById(elm);
}
if(typeof(elm) === 'object' && elm !== null && elm.nodeType && elm.nodeType === 1) {
var elements = [],
siblings = elm.parentNode.children,
index = this.parentIndexOf(elm.parentNode, elm);
for(var i = ++index, len = siblings.length; i<len; i++) {
elements.push(siblings[i]);
}
return elements;
}
return [];
},
/**
* Returns an array of elements - the previous siblings
*
* @method previousSiblings
* @param {String|DomElement} elm element
* @return {Array} Array of previous sibling elements
*/
previousSiblings: function(elm) {
if(typeof(elm) === "string") {
elm = document.getElementById(elm);
}
if(typeof(elm) === 'object' && elm !== null && elm.nodeType && elm.nodeType === 1) {
var elements = [],
siblings = elm.parentNode.children,
index = this.parentIndexOf(elm.parentNode, elm);
for(var i = 0, len = index; i<len; i++) {
elements.push(siblings[i]);
}
return elements;
}
return [];
},
/**
* Returns an array of elements - its siblings
*
* @method siblings
* @param {String|DomElement} elm element
* @return {Array} Array of sibling elements
*/
siblings: function(elm) {
if(typeof(elm) === "string") {
elm = document.getElementById(elm);
}
if(typeof(elm) === 'object' && elm !== null && elm.nodeType && elm.nodeType === 1) {
var elements = [],
siblings = elm.parentNode.children;
for(var i = 0, len = siblings.length; i<len; i++) {
if(elm !== siblings[i]) {
elements.push(siblings[i]);
}
}
return elements;
}
return [];
},
/**
* fallback to elem.childElementCount
*
* @method childElementCount
* @param {String|DomElement} elm element
* @return {Number} number of child elements
*/
childElementCount: function(elm) {
elm = Ink.i(elm);
if ('childElementCount' in elm) {
return elm.childElementCount;
}
if (!elm) { return 0; }
return this.siblings(elm).length + 1;
},
/**
* parses and appends an html string to a container, not destroying its contents
*
* @method appendHTML
* @param {String|DomElement} elm element
* @param {String} html markup string
*/
appendHTML: function(elm, html){
var temp = document.createElement('div');
temp.innerHTML = html;
var tempChildren = temp.children;
for (var i = 0; i < tempChildren.length; i++){
elm.appendChild(tempChildren[i]);
}
},
/**
* parses and prepends an html string to a container, not destroying its contents
*
* @method prependHTML
* @param {String|DomElement} elm element
* @param {String} html markup string
*/
prependHTML: function(elm, html){
var temp = document.createElement('div');
temp.innerHTML = html;
var first = elm.firstChild;
var tempChildren = temp.children;
for (var i = tempChildren.length - 1; i >= 0; i--){
elm.insertBefore(tempChildren[i], first);
first = elm.firstChild;
}
},
/**
* Removes direct children on type text.
* Useful to remove nasty layout gaps generated by whitespace on the markup.
*
* @method removeTextNodeChildren
* @param {DOMElement} el
*/
removeTextNodeChildren: function(el) {
var prevEl, toRemove, parent = el;
el = el.firstChild;
while (el) {
toRemove = (el.nodeType === 3);
prevEl = el;
el = el.nextSibling;
if (toRemove) {
parent.removeChild(prevEl);
}
}
},
/**
* Pass an HTML string and receive a documentFragment with the corresponding elements
* @method htmlToFragment
* @param {String} html html string
* @return {DocumentFragment} DocumentFragment containing all of the elements from the html string
*/
htmlToFragment: function(html){
/*jshint boss:true */
/*global Range:false */
if(typeof document.createRange === 'function' && typeof Range.prototype.createContextualFragment === 'function'){
this.htmlToFragment = function(html){
var range;
if(typeof html !== 'string'){ return document.createDocumentFragment(); }
range = document.createRange();
// set the context to document.body (firefox does this already, webkit doesn't)
range.selectNode(document.body);
return range.createContextualFragment(html);
};
} else {
this.htmlToFragment = function(html){
var fragment = document.createDocumentFragment(),
tempElement,
current;
if(typeof html !== 'string'){ return fragment; }
tempElement = document.createElement('div');
tempElement.innerHTML = html;
// append child removes elements from the original parent
while(current = tempElement.firstChild){ // intentional assignment
fragment.appendChild(current);
}
return fragment;
};
}
return this.htmlToFragment.call(this, html);
},
_camelCase: function(str)
{
return str ? str.replace(/-(\w)/g, function (_, $1){
return $1.toUpperCase();
}) : str;
},
/**
* Gets all of the data attributes from an element
*
* @method data
* @param {String|DomElement} selector Element or CSS selector
* @return {Object} Object with the data-* properties. If no data-attributes are present, an empty object is returned.
*/
data: function(selector) {
var el;
if (typeof selector !== 'object' && typeof selector !== 'string') {
throw '[Ink.Dom.Element.data] :: Invalid selector defined';
}
if (typeof selector === 'object') {
el = selector;
}
else {
var InkDomSelector = Ink.getModule('Ink.Dom.Selector', 1);
if (!InkDomSelector) {
throw "[Ink.Dom.Element.data] :: This method requires Ink.Dom.Selector - v1";
}
el = InkDomSelector.select(selector);
if (el.length <= 0) {
throw "[Ink.Dom.Element.data] :: Can't find any element with the specified selector";
}
el = el[0];
}
var dataset = {};
var attrs = el.attributes || [];
var curAttr, curAttrName, curAttrValue;
if (attrs) {
for (var i = 0, total = attrs.length; i < total; ++i) {
curAttr = attrs[i];
curAttrName = curAttr.name;
curAttrValue = curAttr.value;
if (curAttrName && curAttrName.indexOf('data-') === 0) {
dataset[this._camelCase(curAttrName.replace('data-', ''))] = curAttrValue;
}
}
}
return dataset;
},
/**
* @method moveCursorTo
* @param {Input|Textarea} el
* @param {Number} t
*/
moveCursorTo: function(el, t) {
if (el.setSelectionRange) {
el.setSelectionRange(t, t);
//el.focus();
}
else {
var range = el.createTextRange();
range.collapse(true);
range.moveEnd( 'character', t);
range.moveStart('character', t);
range.select();
}
},
/**
* @method pageWidth
* @return {Number} page width
*/
pageWidth: function() {
var xScroll;
if (window.innerWidth && window.scrollMaxX) {
xScroll = window.innerWidth + window.scrollMaxX;
} else if (document.body.scrollWidth > document.body.offsetWidth){
xScroll = document.body.scrollWidth;
} else {
xScroll = document.body.offsetWidth;
}
var windowWidth;
if (window.self.innerWidth) {
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = window.self.innerWidth;
}
} else if (document.documentElement && document.documentElement.clientWidth) {
windowWidth = document.documentElement.clientWidth;
} else if (document.body) {
windowWidth = document.body.clientWidth;
}
if(xScroll < windowWidth){
return xScroll;
} else {
return windowWidth;
}
},
/**
* @method pageHeight
* @return {Number} page height
*/
pageHeight: function() {
var yScroll;
if (window.innerHeight && window.scrollMaxY) {
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){
yScroll = document.body.scrollHeight;
} else {
yScroll = document.body.offsetHeight;
}
var windowHeight;
if (window.self.innerHeight) {
windowHeight = window.self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
} else if (document.body) {
windowHeight = document.body.clientHeight;
}
if(yScroll < windowHeight){
return windowHeight;
} else {
return yScroll;
}
},
/**
* @method viewportWidth
* @return {Number} viewport width
*/
viewportWidth: function() {
if(typeof window.innerWidth !== "undefined") {
return window.innerWidth;
}
if (document.documentElement && typeof document.documentElement.offsetWidth !== "undefined") {
return document.documentElement.offsetWidth;
}
},
/**
* @method viewportHeight
* @return {Number} viewport height
*/
viewportHeight: function() {
if (typeof window.innerHeight !== "undefined") {
return window.innerHeight;
}
if (document.documentElement && typeof document.documentElement.offsetHeight !== "undefined") {
return document.documentElement.offsetHeight;
}
},
/**
* @method scrollWidth
* @return {Number} scroll width
*/
scrollWidth: function() {
if (typeof window.self.pageXOffset !== 'undefined') {
return window.self.pageXOffset;
}
if (typeof document.documentElement !== 'undefined' && typeof document.documentElement.scrollLeft !== 'undefined') {
return document.documentElement.scrollLeft;
}
return document.body.scrollLeft;
},
/**
* @method scrollHeight
* @return {Number} scroll height
*/
scrollHeight: function() {
if (typeof window.self.pageYOffset !== 'undefined') {
return window.self.pageYOffset;
}
if (typeof document.documentElement !== 'undefined' && typeof document.documentElement.scrollTop !== 'undefined') {
return document.documentElement.scrollTop;
}
return document.body.scrollTop;
}
};
return Element;
});
/**
* @author inkdev AT sapo.pt
*/
Ink.createModule('Ink.Dom.Event', 1, [], function() {
'use strict';
/**
* @module Ink.Dom.Event_1
*/
/**
* @class Ink.Dom.Event
*/
var Event = {
KEY_BACKSPACE: 8,
KEY_TAB: 9,
KEY_RETURN: 13,
KEY_ESC: 27,
KEY_LEFT: 37,
KEY_UP: 38,
KEY_RIGHT: 39,
KEY_DOWN: 40,
KEY_DELETE: 46,
KEY_HOME: 36,
KEY_END: 35,
KEY_PAGEUP: 33,
KEY_PAGEDOWN: 34,
KEY_INSERT: 45,
/**
* Returns a function which calls `func`, waiting at least `wait`
* milliseconds between calls. This is useful for events such as `scroll`
* or `resize`, which can be triggered too many times per second, slowing
* down the browser with needless function calls.
*
* *note:* This does not delay the first function call to the function.
*
* @method throttle
* @param {Function} func Function to call. Arguments and context are both passed.
* @param {Number} [wait=0] Milliseconds to wait between calls.
*
* @example
*
* // BEFORE
* InkEvent.observe(window, 'scroll', function () {
* ...
* }); // When scrolling on mobile devices or on firefox's smooth scroll
* // this is expensive because onscroll is called many times
*
* // AFTER
* InkEvent.observe(window, 'scroll', InkEvent.throttle(function () {
* ...
* }, 100)); // The event handler is called only every 100ms. Problem solved.
*
* @example
* var handler = InkEvent.throttle(function () {
* ...
* }, 100);
*
* InkEvent.observe(window, 'scroll', handler);
* InkEvent.observe(window, 'resize', handler);
*
* // on resize, both the "scroll" and the "resize" events are triggered
* // a LOT of times. This prevents both of them being called a lot of
* // times when the window is being resized by a user.
*
**/
throttle: function (func, wait) {
wait = wait || 0;
var lastCall = 0; // Warning: This breaks on Jan 1st 1970 0:00
var timeout;
var throttled = function () {
var now = +new Date();
var timeDiff = now - lastCall;
if (timeDiff >= wait) {
lastCall = now;
return func.apply(this, [].slice.call(arguments));
} else {
var that = this;
var args = [].slice.call(arguments);
clearTimeout(timeout);
timeout = setTimeout(function () {
return throttled.apply(that, args);
});
}
};
return throttled;
},
/**
* Returns the target of the event object
*
* @method element
* @param {Object} ev event object
* @return {Node} The target
*/
element: function(ev)
{
var node = ev.target ||
// IE stuff
(ev.type === 'mouseout' && ev.fromElement) ||
(ev.type === 'mouseleave' && ev.fromElement) ||
(ev.type === 'mouseover' && ev.toElement) ||
(ev.type === 'mouseenter' && ev.toElement) ||
ev.srcElement ||
null;
return node && (node.nodeType === 3 || node.nodeType === 4) ? node.parentNode : node;
},
/**
* Returns the related target of the event object
*
* @method relatedTarget
* @param {Object} ev event object
* @return {Node} The related target
*/
relatedTarget: function(ev){
var node = ev.relatedTarget ||
// IE stuff
(ev.type === 'mouseout' && ev.toElement) ||
(ev.type === 'mouseleave' && ev.toElement) ||
(ev.type === 'mouseover' && ev.fromElement) ||
(ev.type === 'mouseenter' && ev.fromElement) ||
null;
return node && (node.nodeType === 3 || node.nodeType === 4) ? node.parentNode : node;
},
/**
* Navigate up the DOM tree, looking for a tag with the name `elmTagName`.
*
* If such tag is not found, `document` is returned.
*
* @method findElement
* @param {Object} ev event object
* @param {String} elmTagName tag name to find
* @param {Boolean} [force=false] If this is true, never return `document`, and returns `false` instead.
* @return {DOMElement} the first element which matches given tag name or the document element if the wanted tag is not found
*/
findElement: function(ev, elmTagName, force)
{
var node = this.element(ev);
while(true) {
if(node.nodeName.toLowerCase() === elmTagName.toLowerCase()) {
return node;
} else {
node = node.parentNode;
if(!node) {
if(force) {
return false;
}
return document;
}
if(!node.parentNode){
if(force){ return false; }
return document;
}
}
}
},
/**
* Dispatches an event to element
*
* @method fire
* @param {DOMElement|String} element element id or element
* @param {String} eventName event name
* @param {Object} [memo] metadata for the event
*/
fire: function(element, eventName, memo)
{
element = Ink.i(element);
var ev, nativeEvents;
if(document.createEvent){
nativeEvents = {
"DOMActivate": true, "DOMFocusIn": true, "DOMFocusOut": true,
"focus": true, "focusin": true, "focusout": true,
"blur": true, "load": true, "unload": true, "abort": true,
"error": true, "select": true, "change": true, "submit": true,
"reset": true, "resize": true, "scroll": true,
"click": true, "dblclick": true, "mousedown": true,
"mouseenter": true, "mouseleave": true, "mousemove": true, "mouseover": true,
"mouseout": true, "mouseup": true, "mousewheel": true, "wheel": true,
"textInput": true, "keydown": true, "keypress": true, "keyup": true,
"compositionstart": true, "compositionupdate": true, "compositionend": true,
"DOMSubtreeModified": true, "DOMNodeInserted": true, "DOMNodeRemoved": true,
"DOMNodeInsertedIntoDocument": true, "DOMNodeRemovedFromDocument": true,
"DOMAttrModified": true, "DOMCharacterDataModified": true,
"DOMAttributeNameChanged": true, "DOMElementNameChanged": true,
"hashchange": true
};
} else {
nativeEvents = {
"onabort": true, "onactivate": true, "onafterprint": true, "onafterupdate": true,
"onbeforeactivate": true, "onbeforecopy": true, "onbeforecut": true,
"onbeforedeactivate": true, "onbeforeeditfocus": true, "onbeforepaste": true,
"onbeforeprint": true, "onbeforeunload": true, "onbeforeupdate": true, "onblur": true,
"onbounce": true, "oncellchange": true, "onchange": true, "onclick": true,
"oncontextmenu": true, "oncontrolselect": true, "oncopy": true, "oncut": true,
"ondataavailable": true, "ondatasetchanged": true, "ondatasetcomplete": true,
"ondblclick": true, "ondeactivate": true, "ondrag": true, "ondragend": true,
"ondragenter": true, "ondragleave": true, "ondragover": true, "ondragstart": true,
"ondrop": true, "onerror": true, "onerrorupdate": true,
"onfilterchange": true, "onfinish": true, "onfocus": true, "onfocusin": true,
"onfocusout": true, "onhashchange": true, "onhelp": true, "onkeydown": true,
"onkeypress": true, "onkeyup": true, "onlayoutcomplete": true,
"onload": true, "onlosecapture": true, "onmessage": true, "onmousedown": true,
"onmouseenter": true, "onmouseleave": true, "onmousemove": true, "onmouseout": true,
"onmouseover": true, "onmouseup": true, "onmousewheel": true, "onmove": true,
"onmoveend": true, "onmovestart": true, "onoffline": true, "ononline": true,
"onpage": true, "onpaste": true, "onprogress": true, "onpropertychange": true,
"onreadystatechange": true, "onreset": true, "onresize": true,
"onresizeend": true, "onresizestart": true, "onrowenter": true, "onrowexit": true,
"onrowsdelete": true, "onrowsinserted": true, "onscroll": true, "onselect": true,
"onselectionchange": true, "onselectstart": true, "onstart": true,
"onstop": true, "onstorage": true, "onstoragecommit": true, "onsubmit": true,
"ontimeout": true, "onunload": true
};
}
if(element !== null && element !== undefined){
if (element === document && document.createEvent && !element.dispatchEvent) {
element = document.documentElement;
}
if (document.createEvent) {
ev = document.createEvent("HTMLEvents");
if(typeof nativeEvents[eventName] === "undefined"){
ev.initEvent("dataavailable", true, true);
} else {
ev.initEvent(eventName, true, true);
}
} else {
ev = document.createEventObject();
if(typeof nativeEvents["on"+eventName] === "undefined"){
ev.eventType = "ondataavailable";
} else {
ev.eventType = "on"+eventName;
}
}
ev.eventName = eventName;
ev.memo = memo || { };
try {
if (document.createEvent) {
element.dispatchEvent(ev);
} else if(element.fireEvent){
element.fireEvent(ev.eventType, ev);
} else {
return;
}
} catch(ex) {}
return ev;
}
},
_callbackForCustomEvents: function (element, eventName, callBack) {
var isHashChangeInIE = eventName === "hashchange" && element.attachEvent && !window.onhashchange;
var isCustomEvent = eventName.indexOf(':') !== -1;
if (isHashChangeInIE || isCustomEvent) {
/**
*
* prevent that each custom event fire without any test
* This prevents that if you have multiple custom events
* on dataavailable to trigger the callback event if it
* is a different custom event
*
*/
var argCallback = callBack;
return Ink.bindEvent(function(ev, eventName, cb){
//tests if it is our event and if not
//check if it is IE and our dom:loaded was overrided (IE only supports one ondatavailable)
//- fix /opera also supports attachEvent and was firing two events
// if(ev.eventName === eventName || (Ink.Browser.IE && eventName === 'dom:loaded')){
if(ev.eventName === eventName){
//fix for FF since it loses the event in case of using a second binObjEvent
if(window.addEventListener){
window.event = ev;
}
cb();
}
}, this, eventName, argCallback);
} else {
return null;
}
},
/**
* Attaches an event to element
*
* @method observe
* @param {DOMElement|String} element Element id or element
* @param {String} eventName Event name
* @param {Function} callBack Receives event object as a
* parameter. If you're manually firing custom events, check the
* eventName property of the event object to make sure you're handling
* the right event.
* @param {Boolean} [useCapture] Set to true to change event listening from bubbling to capture.
* @return {Function} The event handler used. Hang on to this if you want to `stopObserving` later.
*/
observe: function(element, eventName, callBack, useCapture)
{
element = Ink.i(element);
if(element !== null && element !== undefined) {
/* rare corner case: some events need a different callback to be generated */
var callbackForCustomEvents = this._callbackForCustomEvents(element, eventName, callBack);
if (callbackForCustomEvents) {
callBack = callbackForCustomEvents;
eventName = 'dataavailable';
}
if(element.addEventListener) {
element.addEventListener(eventName, callBack, !!useCapture);
} else {
element.attachEvent('on' + eventName, callBack);
}
return callBack;
}
},
/**
* Attaches an event to a selector or array of elements.
*
* Requires Ink.Dom.Selector or a browser with Element.querySelectorAll.
*
* Ink.Dom.Event.observe
*
* @method observeMulti
* @param {Array|String} elements
* @param ... See the `observe` function.
* @return {Function} The used callback.
*/
observeMulti: function (elements, eventName, callBack, useCapture) {
if (typeof elements === 'string') {
elements = Ink.ss(elements);
} else if (elements instanceof Element) {
elements = [elements];
}
if (!elements[0]) { return false; }
var callbackForCustomEvents = this._callbackForCustomEvents(elements[0], eventName, callBack);
if (callbackForCustomEvents) {
callBack = callbackForCustomEvents;
eventName = 'dataavailable';
}
for (var i = 0, len = elements.length; i < len; i++) {
this.observe(elements[i], eventName, callBack, useCapture);
}
return callBack;
},
/**
* Remove an event attached to an element
*
* @method stopObserving
* @param {DOMElement|String} element element id or element
* @param {String} eventName event name
* @param {Function} callBack callback function
* @param {Boolean} [useCapture] set to true if the event was being observed with useCapture set to true as well.
*/
stopObserving: function(element, eventName, callBack, useCapture)
{
element = Ink.i(element);
if(element !== null && element !== undefined) {
if(element.removeEventListener) {
element.removeEventListener(eventName, callBack, !!useCapture);
} else {
element.detachEvent('on' + eventName, callBack);
}
}
},
/**
* Stops event propagation and bubbling
*
* @method stop
* @param {Object} event event handle
*/
stop: function(event)
{
if(event.cancelBubble !== null) {
event.cancelBubble = true;
}
if(event.stopPropagation) {
event.stopPropagation();
}
if(event.preventDefault) {
event.preventDefault();
}
if(window.attachEvent) {
event.returnValue = false;
}
if(event.cancel !== null) {
event.cancel = true;
}
},
/**
* Stops event propagation
*
* @method stopPropagation
* @param {Object} event event handle
*/
stopPropagation: function(event) {
if(event.cancelBubble !== null) {
event.cancelBubble = true;
}
if(event.stopPropagation) {
event.stopPropagation();
}
},
/**
* Stops event default behaviour
*
* @method stopDefault
* @param {Object} event event handle
*/
stopDefault: function(event)
{
if(event.preventDefault) {
event.preventDefault();
}
if(window.attachEvent) {
event.returnValue = false;
}
if(event.cancel !== null) {
event.cancel = true;
}
},
/**
* @method pointer
* @param {Object} ev event object
* @return {Object} an object with the mouse X and Y position
*/
pointer: function(ev)
{
return {
x: ev.pageX || (ev.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)),
y: ev.pageY || (ev.clientY + (document.documentElement.scrollTop || document.body.scrollTop))
};
},
/**
* @method pointerX
* @param {Object} ev event object
* @return {Number} mouse X position
*/
pointerX: function(ev)
{
return ev.pageX || (ev.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
},
/**
* @method pointerY
* @param {Object} ev event object
* @return {Number} mouse Y position
*/
pointerY: function(ev)
{
return ev.pageY || (ev.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
},
/**
* @method isLeftClick
* @param {Object} ev event object
* @return {Boolean} True if the event is a left mouse click
*/
isLeftClick: function(ev) {
if (window.addEventListener) {
if(ev.button === 0){
return true;
}
else if(ev.type.substring(0,5) === 'touch' && ev.button === null){
return true;
}
}
else {
if(ev.button === 1){ return true; }
}
return false;
},
/**
* @method isRightClick
* @param {Object} ev event object
* @return {Boolean} True if there is a right click on the event
*/
isRightClick: function(ev) {
return (ev.button === 2);
},
/**
* @method isMiddleClick
* @param {Object} ev event object
* @return {Boolean} True if there is a middle click on the event
*/
isMiddleClick: function(ev) {
if (window.addEventListener) {
return (ev.button === 1);
}
else {
return (ev.button === 4);
}
return false;
},
/**
* Work in Progress.
* Used in SAPO.Component.MaskedInput
*
* @method getCharFromKeyboardEvent
* @param {KeyboardEvent} event keyboard event
* @param {optional Boolean} [changeCasing] if true uppercases, if false lowercases, otherwise keeps casing
* @return {String} character representation of pressed key combination
*/
getCharFromKeyboardEvent: function(event, changeCasing) {
var k = event.keyCode;
var c = String.fromCharCode(k);
var shiftOn = event.shiftKey;
if (k >= 65 && k <= 90) { // A-Z
if (typeof changeCasing === 'boolean') {
shiftOn = changeCasing;
}
return (shiftOn) ? c : c.toLowerCase();
}
else if (k >= 96 && k <= 105) { // numpad digits
return String.fromCharCode( 48 + (k-96) );
}
switch (k) {
case 109: case 189: return '-';
case 107: case 187: return '+';
}
return c;
},
debug: function(){}
};
return Event;
});
/**
* @module Ink.Dom.FormSerialize
* @author inkdev AT sapo.pt
*/
Ink.createModule('Ink.Dom.FormSerialize', 1, [], function () {
'use strict';
/**
* Supports serialization of form data to/from javascript Objects.
*
* Valid applications are ad hoc AJAX/syndicated submission of forms, restoring form values from server side state, etc.
*
* @class Ink.Dom.FormSerialize
*
*/
var FormSerialize = {
/**
* Serializes a form into an object, turning field names into keys, and field values into values.
*
* note: Multi-select and checkboxes with multiple values will yield arrays
*
* @method serialize
* @return {Object} map of fieldName -> String|String[]|Boolean
* @param {DomElement|String} form form element from which the extraction is to occur
*
* @example
* <form id="frm">
* <input type="text" name="field1">
* <button type="submit">Submit</button>
* </form>
* <script type="text/javascript">
* Ink.requireModules(['Ink.Dom.FormSerialize_1', 'Ink.Dom.Event_1'], function (FormSerialize, InkEvent) {
* InkEvent.observe('frm', 'submit', function (event) {
* var formData = FormSerialize.serialize('frm'); // -> {field1:"123"}
* InkEvent.stop(event);
* });
* });
* </script>
*/
serialize: function(form) {
form = Ink.i(form);
var map = this._getFieldNameInputsMap(form);
var map2 = {};
for (var k in map) if (map.hasOwnProperty(k)) {
if(k !== null) {
var tmpK = k.replace(/\[\]$/, '');
map2[tmpK] = this._getValuesOfField( map[k] );
} else {
map2[k] = this._getValuesOfField( map[k] );
}
}
delete map2['null']; // this can occur. if so, delete it...
return map2;
},
/**
* Sets form elements's values with values given from object
*
* One cannot restore the values of an input with `type="file"` (browser prohibits it)
*
* @method fillIn
* @param {DomElement|String} form form element which is to be populated
* @param {Object} map2 map of fieldName -> String|String[]|Boolean
* @example
* <form id="frm">
* <input type="text" name="field1">
* <button type="submit">Submit</button>
* </form>
* <script type="text/javascript">
* Ink.requireModules(['Ink.Dom.FormSerialize_1'], function (FormSerialize) {
* var values = {field1: 'CTHULHU'};
* FormSerialize.fillIn('frm', values);
* // At this point the form is pre-filled with the values above.
* });
* </script>
*/
fillIn: function(form, map2) {
form = Ink.i(form);
var map = this._getFieldNameInputsMap(form);
delete map['null']; // this can occur. if so, delete it...
for (var k in map2) if (map2.hasOwnProperty(k)) {
this._setValuesOfField( map[k], map2[k] );
}
},
_getFieldNameInputsMap: function(formEl) {
var name, nodeName, el, map = {};
for (var i = 0, f = formEl.elements.length; i < f; ++i) {
el = formEl.elements[i];
name = el.getAttribute('name');
nodeName = el.nodeName.toLowerCase();
if (nodeName === 'fieldset') {
continue;
} else if (map[name] === undefined) {
map[name] = [el];
} else {
map[name].push(el);
}
}
return map;
},
_getValuesOfField: function(fieldInputs) {
var nodeName = fieldInputs[0].nodeName.toLowerCase();
var type = fieldInputs[0].getAttribute('type');
var value = fieldInputs[0].value;
var i, f, j, o, el, m, res = [];
switch(nodeName) {
case 'select':
for (i = 0, f = fieldInputs.length; i < f; ++i) {
res[i] = [];
m = fieldInputs[i].getAttribute('multiple');
for (j = 0, o = fieldInputs[i].options.length; j < o; ++j) {
el = fieldInputs[i].options[j];
if (el.selected) {
if (m) {
res[i].push(el.value);
} else {
res[i] = el.value;
break;
}
}
}
}
return ((fieldInputs.length > 0 && /\[[^\]]*\]$/.test(fieldInputs[0].getAttribute('name'))) ? res : res[0]);
case 'textarea':
case 'input':
if (type === 'checkbox' || type === 'radio') {
for (i = 0, f = fieldInputs.length; i < f; ++i) {
el = fieldInputs[i];
if (el.checked) {
res.push( el.value );
}
}
if (type === 'checkbox') {
return (fieldInputs.length > 1) ? res : !!(res.length);
}
return (fieldInputs.length > 1) ? res[0] : !!(res.length); // on radios only 1 option is selected at most
}
else {
//if (fieldInputs.length > 1) { throw 'Got multiple input elements with same name!'; }
if(fieldInputs.length > 0 && /\[[^\]]*\]$/.test(fieldInputs[0].getAttribute('name'))) {
var tmpValues = [];
for(i=0, f = fieldInputs.length; i < f; ++i) {
tmpValues.push(fieldInputs[i].value);
}
return tmpValues;
} else {
return value;
}
}
break; // to keep JSHint happy... (reply to this comment by gamboa: - ROTFL)
default:
//throw 'Unsupported element: "' + nodeName + '"!';
return undefined;
}
},
_valInArray: function(val, arr) {
for (var i = 0, f = arr.length; i < f; ++i) {
if (arr[i] === val) { return true; }
}
return false;
},
_setValuesOfField: function(fieldInputs, fieldValues) {
if (!fieldInputs) { return; }
var nodeName = fieldInputs[0].nodeName.toLowerCase();
var type = fieldInputs[0].getAttribute('type');
var i, f, el;
switch(nodeName) {
case 'select':
if (fieldInputs.length > 1) { throw 'Got multiple select elements with same name!'; }
for (i = 0, f = fieldInputs[0].options.length; i < f; ++i) {
el = fieldInputs[0].options[i];
el.selected = (fieldValues instanceof Array) ? this._valInArray(el.value, fieldValues) : el.value === fieldValues;
}
break;
case 'textarea':
case 'input':
if (type === 'checkbox' || type === 'radio') {
for (i = 0, f = fieldInputs.length; i < f; ++i) {
el = fieldInputs[i];
//el.checked = (fieldValues instanceof Array) ? this._valInArray(el.value, fieldValues) : el.value === fieldValues;
el.checked = (fieldValues instanceof Array) ? this._valInArray(el.value, fieldValues) : (fieldInputs.length > 1 ? el.value === fieldValues : !!fieldValues);
}
}
else {
if (fieldInputs.length > 1) { throw 'Got multiple input elements with same name!'; }
if (type !== 'file') {
fieldInputs[0].value = fieldValues;
}
}
break;
default:
throw 'Unsupported element: "' + nodeName + '"!';
}
}
};
return FormSerialize;
});
/**
* @module Ink.Dom.Loaded_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Dom.Loaded', 1, [], function() {
'use strict';
/**
* The Loaded class provides a method that allows developers to queue functions to run when
* the page is loaded (document is ready).
*
* @class Ink.Dom.Loaded
* @version 1
* @static
*/
var Loaded = {
/**
* Callbacks and their contexts. Array of 2-arrays.
*
* []
*
* @attribute _contexts Array
* @private
*
*/
_contexts: [], // Callbacks' queue
/**
* Adds a new function that will be invoked once the document is ready
*
* @method run
* @param {Object} [win=window] Window object to attach/add the event
* @param {Function} fn Callback function to be run after the page is loaded
* @public
* @example
* Ink.requireModules(['Ink.Dom.Loaded_1'], function(Loaded){
* Loaded.run(function(){
* console.log('This will run when the page/document is ready/loaded');
* });
* });
*/
run: function(win, fn) {
if (!fn) {
fn = win;
win = window;
}
var context;
for (var i = 0, len = this._contexts.length; i < len; i++) {
if (this._contexts[i][0] === win) {
context = this._contexts[i][1];
break;
}
}
if (!context) {
context = {
cbQueue: [],
win: win,
doc: win.document,
root: win.document.documentElement,
done: false,
top: true
};
context.handlers = {
checkState: Ink.bindEvent(this._checkState, this, context),
poll: Ink.bind(this._poll, this, context)
};
this._contexts.push(
[win, context] // Javascript Objects cannot map different windows to
// different values.
);
}
var ael = context.doc.addEventListener;
context.add = ael ? 'addEventListener' : 'attachEvent';
context.rem = ael ? 'removeEventListener' : 'detachEvent';
context.pre = ael ? '' : 'on';
context.det = ael ? 'DOMContentLoaded' : 'onreadystatechange';
context.wet = context.pre + 'load';
var csf = context.handlers.checkState;
var alreadyLoaded = (
context.doc.readyState === 'complete' &&
context.win.location.toString() !== 'about:blank'); // https://code.google.com/p/chromium/issues/detail?id=32357
if (alreadyLoaded){
setTimeout(Ink.bind(function () {
fn.call(context.win, 'lazy');
}, this), 0);
} else {
context.cbQueue.push(fn);
context.doc[context.add]( context.det , csf );
context.win[context.add]( context.wet , csf );
var frameElement = 1;
try{
frameElement = context.win.frameElement;
} catch(e) {}
if ( !ael && context.root && context.root.doScroll ) { // IE HACK
try {
context.top = !frameElement;
} catch(e) { }
if (context.top) {
this._poll(context);
}
}
}
},
/**
* Function that will be running the callbacks after the page is loaded
*
* @method _checkState
* @param {Event} event Triggered event
* @private
*/
_checkState: function(event, context) {
if ( !event || (event.type === 'readystatechange' && context.doc.readyState !== 'complete')) {
return;
}
var where = (event.type === 'load') ? context.win : context.doc;
where[context.rem](context.pre+event.type, context.handlers.checkState, false);
this._ready(context);
},
/**
* Polls the load progress of the page to see if it has already loaded or not
*
* @method _poll
* @private
*/
/**
*
* function _poll
*/
_poll: function(context) {
try {
context.root.doScroll('left');
} catch(e) {
return setTimeout(context.handlers.poll, 50);
}
this._ready(context);
},
/**
* Function that runs the callbacks from the queue when the document is ready.
*
* @method _ready
* @private
*/
_ready: function(context) {
if (!context.done) {
context.done = true;
for (var i = 0; i < context.cbQueue.length; ++i) {
context.cbQueue[i].call(context.win);
}
context.cbQueue = [];
}
}
};
return Loaded;
});
/**
* @module Ink.Dom.Selector_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Dom.Selector', 1, [], function() {
/*jshint forin:false, eqnull:true*/
'use strict';
/**
* @class Ink.Dom.Selector
* @static
* @version 1
*/
/*!
* Sizzle CSS Selector Engine
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
recompare,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function() { return 0; },
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /^[^{]+\{\s*\[native code/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
/*
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/*
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/*
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/*
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/*
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/*
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementsByName privileges form controls or returns elements by ID
// If so, assume (for broader support) that getElementById returns elements by name
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
// Support: Windows 8 Native Apps
// Assigning innerHTML with "name" attributes throws uncatchable exceptions
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx
div.appendChild( document.createElement("a") ).setAttribute( "name", expando );
div.appendChild( document.createElement("i") ).setAttribute( "name", expando );
docElem.appendChild( div );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
// Cleanup
docElem.removeChild( div );
return pass;
});
// Support: Webkit<537.32
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
return div1.compareDocumentPosition &&
// Should return 1, but Webkit returns 4 (following)
(div1.compareDocumentPosition( document.createElement("div") ) & 1);
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getByName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(recompare && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( documentIsHTML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( !documentIsHTML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
// Compensate for sort limitations
recompare = !support.sortDetached;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/*
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns Returns -1 if a precedes b, 1 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/*
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
// Check sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Initialize with the default document
setDocument();
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
// EXPOSE
/*if ( typeof define === "function" && define.amd ) {
define(function() { return Sizzle; });
} else {
window.Sizzle = Sizzle;
}*/
// EXPOSE
/**
* Alias for the Sizzle selector engine
*
* @method select
* @param {String} selector CSS selector to search for elements
* @param {DOMElement} [context] By default the search is done in the document element. However, you can specify an element as search context
* @param {Array} [results] By default this is considered an empty array. But if you want to merge it with other searches you did, pass their result array through here.
* @param {Object} [seed]
* @return {Array} Array of resulting DOM Elements
*/
/**
* Returns elements which match with the second argument to the function.
*
* @method matches
* @param {String} selector CSS selector to search for elements
* @param {Array} matches Elements to be 'matched' with
* @return {Array} Elements that matched
*/
/**
* Returns true iif element matches given selector
*
* @method matchesSelector
* @param {DOMElement} element to test
* @param {String} selector CSS selector to test the element with
* @return {Boolean} true iif element matches the CSS selector
*/
return {
select: Sizzle,
matches: Sizzle.matches,
matchesSelector: Sizzle.matchesSelector
};
}); //( window );
/**
* @module Ink.Dom.Browser_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Dom.Browser', '1', [], function() {
'use strict';
/**
* @class Ink.Dom.Browser
* @version 1
* @static
* @example
* <input type="text" id="dPicker" />
* <script>
* Ink.requireModules(['Ink.Dom.Browser_1'],function( InkBrowser ){
* if( InkBrowser.CHROME ){
* console.log( 'This is a CHROME browser.' );
* }
* });
* </script>
*/
var Browser = {
/**
* True if the browser is Internet Explorer
*
* @property IE
* @type {Boolean}
* @public
* @static
*/
IE: false,
/**
* True if the browser is Gecko based
*
* @property GECKO
* @type {Boolean}
* @public
* @static
*/
GECKO: false,
/**
* True if the browser is Opera
*
* @property OPERA
* @type {Boolean}
* @public
* @static
*/
OPERA: false,
/**
* True if the browser is Safari
*
* @property SAFARI
* @type {Boolean}
* @public
* @static
*/
SAFARI: false,
/**
* True if the browser is Konqueror
*
* @property KONQUEROR
* @type {Boolean}
* @public
* @static
*/
KONQUEROR: false,
/**
* True if browser is Chrome
*
* @property CHROME
* @type {Boolean}
* @public
* @static
*/
CHROME: false,
/**
* The specific browser model. False if it is unavailable.
*
* @property model
* @type {Boolean|String}
* @public
* @static
*/
model: false,
/**
* The browser version. False if it is unavailable.
*
* @property version
* @type {Boolean|String}
* @public
* @static
*/
version: false,
/**
* The user agent string. False if it is unavailable.
*
* @property userAgent
* @type {Boolean|String}
* @public
* @static
*/
userAgent: false,
/**
* Initialization function for the Browser object.
*
* Is called automatically when this module is loaded, and calls setDimensions, setBrowser and setReferrer.
*
* @method init
* @public
*/
init: function()
{
this.detectBrowser();
this.setDimensions();
this.setReferrer();
},
/**
* Retrieves and stores window dimensions in this object. Called automatically when this module is loaded.
*
* @method setDimensions
* @public
*/
setDimensions: function()
{
//this.windowWidth=window.innerWidth !== null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body !== null ? document.body.clientWidth : null;
//this.windowHeight=window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
var myWidth = 0, myHeight = 0;
if ( typeof window.innerWidth=== 'number' ) {
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
this.windowWidth = myWidth;
this.windowHeight = myHeight;
},
/**
* Stores the referrer. Called automatically when this module is loaded.
*
* @method setReferrer
* @public
*/
setReferrer: function()
{
this.referrer = document.referrer !== undefined? document.referrer.length > 0 ? window.escape(document.referrer) : false : false;
},
/**
* Detects the browser and stores the found properties. Called automatically when this module is loaded.
*
* @method detectBrowser
* @public
*/
detectBrowser: function()
{
var sAgent = navigator.userAgent;
this.userAgent = sAgent;
sAgent = sAgent.toLowerCase();
if((new RegExp("applewebkit\/")).test(sAgent)) {
if((new RegExp("chrome\/")).test(sAgent)) {
// Chrome
this.CHROME = true;
this.model = 'chrome';
this.version = sAgent.replace(new RegExp("(.*)chrome\/([^\\s]+)(.*)"), "$2");
this.cssPrefix = '-webkit-';
this.domPrefix = 'Webkit';
} else {
// Safari
this.SAFARI = true;
this.model = 'safari';
this.version = sAgent.replace(new RegExp("(.*)applewebkit\/([^\\s]+)(.*)"), "$2");
this.cssPrefix = '-webkit-';
this.domPrefix = 'Webkit';
}
} else if((new RegExp("opera")).test(sAgent)) {
// Opera
this.OPERA = true;
this.model = 'opera';
this.version = sAgent.replace(new RegExp("(.*)opera.([^\\s$]+)(.*)"), "$2");
this.cssPrefix = '-o-';
this.domPrefix = 'O';
} else if((new RegExp("konqueror")).test(sAgent)) {
// Konqueror
this.KONQUEROR = true;
this.model = 'konqueror';
this.version = sAgent.replace(new RegExp("(.*)konqueror\/([^;]+);(.*)"), "$2");
this.cssPrefix = '-khtml-';
this.domPrefix = 'Khtml';
} else if((new RegExp("msie\\ ")).test(sAgent)) {
// MSIE
this.IE = true;
this.model = 'ie';
this.version = sAgent.replace(new RegExp("(.*)\\smsie\\s([^;]+);(.*)"), "$2");
this.cssPrefix = '-ms-';
this.domPrefix = 'ms';
} else if((new RegExp("gecko")).test(sAgent)) {
// GECKO
// Supports only:
// Camino, Chimera, Epiphany, Minefield (firefox 3), Firefox, Firebird, Phoenix, Galeon,
// Iceweasel, K-Meleon, SeaMonkey, Netscape, Songbird, Sylera,
this.GECKO = true;
var re = new RegExp("(camino|chimera|epiphany|minefield|firefox|firebird|phoenix|galeon|iceweasel|k\\-meleon|seamonkey|netscape|songbird|sylera)");
if(re.test(sAgent)) {
this.model = sAgent.match(re)[1];
this.version = sAgent.replace(new RegExp("(.*)"+this.model+"\/([^;\\s$]+)(.*)"), "$2");
this.cssPrefix = '-moz-';
this.domPrefix = 'Moz';
} else {
// probably is mozilla
this.model = 'mozilla';
var reVersion = new RegExp("(.*)rv:([^)]+)(.*)");
if(reVersion.test(sAgent)) {
this.version = sAgent.replace(reVersion, "$2");
}
this.cssPrefix = '-moz-';
this.domPrefix = 'Moz';
}
}
},
/**
* Debug function which displays browser (and Ink.Dom.Browser) information as an alert message.
*
* @method debug
* @public
*
* @example
*
* The following code
*
* Ink.requireModules(['Ink.Dom.Browser_1'], function (Browser) {
* Browser.debug();
* });
*
* Alerts (On Firefox 22):
*
* known browsers: (ie, gecko, opera, safari, konqueror)
* false,true,false,false,false
* model -> firefox
* version -> 22.0
*
* original UA -> Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0
*/
debug: function()
{
/*global alert:false */
var str = "known browsers: (ie, gecko, opera, safari, konqueror) \n";
str += [this.IE, this.GECKO, this.OPERA, this.SAFARI, this.KONQUEROR] +"\n";
str += "model -> "+this.model+"\n";
str += "version -> "+this.version+"\n";
str += "\n";
str += "original UA -> "+this.userAgent;
alert(str);
}
};
Browser.init();
return Browser;
});
/**
* @module Ink.Util.Url_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Util.Url', '1', [], function() {
'use strict';
/**
* Utility functions to use with URLs
*
* @class Ink.Util.Url
* @version 1
* @static
*/
var Url = {
/**
* Auxiliary string for encoding
*
* @property _keyStr
* @type {String}
* @readOnly
* @private
*/
_keyStr : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
/**
* Get current URL of page
*
* @method getUrl
* @return {String} Current URL
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){
* console.log( InkUrl.getUrl() ); // Will return it's window URL
* });
*/
getUrl: function()
{
return window.location.href;
},
/**
* Generates an uri with query string based on the parameters object given
*
* @method genQueryString
* @param {String} uri
* @param {Object} params
* @return {String} URI with query string set
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){
* var queryString = InkUrl.genQueryString( 'http://www.sapo.pt/', {
* 'param1': 'valueParam1',
* 'param2': 'valueParam2'
* });
*
* console.log( queryString ); // Result: http://www.sapo.pt/?param1=valueParam1¶m2=valueParam2
* });
*/
genQueryString: function(uri, params) {
var hasQuestionMark = uri.indexOf('?') !== -1;
var sep, pKey, pValue, parts = [uri];
for (pKey in params) {
if (params.hasOwnProperty(pKey)) {
if (!hasQuestionMark) {
sep = '?';
hasQuestionMark = true;
} else {
sep = '&';
}
pValue = params[pKey];
if (typeof pValue !== 'number' && !pValue) {
pValue = '';
}
parts = parts.concat([sep, encodeURIComponent(pKey), '=', encodeURIComponent(pValue)]);
}
}
return parts.join('');
},
/**
* Get query string of current or passed URL
*
* @method getQueryString
* @param {String} [str] URL String. When not specified it uses the current URL.
* @return {Object} Key-Value object with the pairs variable: value
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){
* var queryStringParams = InkUrl.getQueryString( 'http://www.sapo.pt/?var1=valueVar1&var2=valueVar2' );
* console.log( queryStringParams );
* // Result:
* // {
* // var1: 'valueVar1',
* // var2: 'valueVar2'
* // }
* });
*/
getQueryString: function(str)
{
var url;
if(str && typeof(str) !== 'undefined') {
url = str;
} else {
url = this.getUrl();
}
var aParams = {};
if(url.match(/\?(.+)/i)) {
var queryStr = url.replace(/^(.*)\?([^\#]+)(\#(.*))?/g, "$2");
if(queryStr.length > 0) {
var aQueryStr = queryStr.split(/[;&]/);
for(var i=0; i < aQueryStr.length; i++) {
var pairVar = aQueryStr[i].split('=');
aParams[decodeURIComponent(pairVar[0])] = (typeof(pairVar[1]) !== 'undefined' && pairVar[1]) ? decodeURIComponent(pairVar[1]) : false;
}
}
}
return aParams;
},
/**
* Get URL hash
*
* @method getAnchor
* @param {String} [str] URL String. If not set, it will get the current URL.
* @return {String|Boolean} Hash in the URL. If there's no hash, returns false.
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){
* var anchor = InkUrl.getAnchor( 'http://www.sapo.pt/page.php#TEST' );
* console.log( anchor ); // Result: TEST
* });
*/
getAnchor: function(str)
{
var url;
if(str && typeof(str) !== 'undefined') {
url = str;
} else {
url = this.getUrl();
}
var anchor = false;
if(url.match(/#(.+)/)) {
anchor = url.replace(/([^#]+)#(.*)/, "$2");
}
return anchor;
},
/**
* Get anchor string of current or passed URL
*
* @method getAnchorString
* @param {String} [string] If not provided it uses the current URL.
* @return {Object} Returns a key-value object of the 'variables' available in the hashtag of the URL
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){
* var hashParams = InkUrl.getAnchorString( 'http://www.sapo.pt/#var1=valueVar1&var2=valueVar2' );
* console.log( hashParams );
* // Result:
* // {
* // var1: 'valueVar1',
* // var2: 'valueVar2'
* // }
* });
*/
getAnchorString: function(string)
{
var url;
if(string && typeof(string) !== 'undefined') {
url = string;
} else {
url = this.getUrl();
}
var aParams = {};
if(url.match(/#(.+)/i)) {
var anchorStr = url.replace(/^([^#]+)#(.*)?/g, "$2");
if(anchorStr.length > 0) {
var aAnchorStr = anchorStr.split(/[;&]/);
for(var i=0; i < aAnchorStr.length; i++) {
var pairVar = aAnchorStr[i].split('=');
aParams[decodeURIComponent(pairVar[0])] = (typeof(pairVar[1]) !== 'undefined' && pairVar[1]) ? decodeURIComponent(pairVar[1]) : false;
}
}
}
return aParams;
},
/**
* Parse passed URL
*
* @method parseUrl
* @param {String} url URL to be parsed
* @return {Object} Parsed URL as a key-value object.
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){
* var parsedURL = InkUrl.parseUrl( 'http://www.sapo.pt/index.html?var1=value1#anchor' )
* console.log( parsedURL );
* // Result:
* // {
* // 'scheme' => 'http',
* // 'host' => 'www.sapo.pt',
* // 'path' => '/index.html',
* // 'query' => 'var1=value1',
* // 'fragment' => 'anchor'
* // }
* });
*
*/
parseUrl: function(url)
{
var aURL = {};
if(url && typeof(url) !== 'undefined' && typeof(url) === 'string') {
if(url.match(/^([^:]+):\/\//i)) {
var re = /^([^:]+):\/\/([^\/]*)\/?([^\?#]*)\??([^#]*)#?(.*)/i;
if(url.match(re)) {
aURL.scheme = url.replace(re, "$1");
aURL.host = url.replace(re, "$2");
aURL.path = '/'+url.replace(re, "$3");
aURL.query = url.replace(re, "$4") || false;
aURL.fragment = url.replace(re, "$5") || false;
}
} else {
var re1 = new RegExp("^([^\\?]+)\\?([^#]+)#(.*)", "i");
var re2 = new RegExp("^([^\\?]+)\\?([^#]+)#?", "i");
var re3 = new RegExp("^([^\\?]+)\\??", "i");
if(url.match(re1)) {
aURL.scheme = false;
aURL.host = false;
aURL.path = url.replace(re1, "$1");
aURL.query = url.replace(re1, "$2");
aURL.fragment = url.replace(re1, "$3");
} else if(url.match(re2)) {
aURL.scheme = false;
aURL.host = false;
aURL.path = url.replace(re2, "$1");
aURL.query = url.replace(re2, "$2");
aURL.fragment = false;
} else if(url.match(re3)) {
aURL.scheme = false;
aURL.host = false;
aURL.path = url.replace(re3, "$1");
aURL.query = false;
aURL.fragment = false;
}
}
if(aURL.host) {
var regPort = new RegExp("^(.*)\\:(\\d+)$","i");
// check for port
if(aURL.host.match(regPort)) {
var tmpHost1 = aURL.host;
aURL.host = tmpHost1.replace(regPort, "$1");
aURL.port = tmpHost1.replace(regPort, "$2");
} else {
aURL.port = false;
}
// check for user and pass
if(aURL.host.match(/@/i)) {
var tmpHost2 = aURL.host;
aURL.host = tmpHost2.split('@')[1];
var tmpUserPass = tmpHost2.split('@')[0];
if(tmpUserPass.match(/\:/)) {
aURL.user = tmpUserPass.split(':')[0];
aURL.pass = tmpUserPass.split(':')[1];
} else {
aURL.user = tmpUserPass;
aURL.pass = false;
}
}
}
}
return aURL;
},
/**
* Get last loaded script element
*
* @method currentScriptElement
* @param {String} [match] String to match against the script src attribute
* @return {DOMElement|Boolean} Returns the <script> DOM Element or false if unable to find it.
* @public
* @static
*/
currentScriptElement: function(match)
{
var aScripts = document.getElementsByTagName('script');
if(typeof(match) === 'undefined') {
if(aScripts.length > 0) {
return aScripts[(aScripts.length - 1)];
} else {
return false;
}
} else {
var curScript = false;
var re = new RegExp(""+match+"", "i");
for(var i=0, total = aScripts.length; i < total; i++) {
curScript = aScripts[i];
if(re.test(curScript.src)) {
return curScript;
}
}
return false;
}
},
/*
base64Encode: function(string)
{
/**
* --function {String} ?
* --Convert a string to BASE 64
* @param {String} string - string to convert
* @return base64 encoded string
*
*
if(!SAPO.Utility.String || typeof(SAPO.Utility.String) === 'undefined') {
throw "SAPO.Utility.Url.base64Encode depends of SAPO.Utility.String, which has not been referred.";
}
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
var input = SAPO.Utility.String.utf8Encode(string);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
base64Decode: function(string)
{
* --function {String} ?
* Decode a BASE 64 encoded string
* --param {String} string base64 encoded string
* --return string decoded
if(!SAPO.Utility.String || typeof(SAPO.Utility.String) === 'undefined') {
throw "SAPO.Utility.Url.base64Decode depends of SAPO.Utility.String, which has not been referred.";
}
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
var input = string.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 !== 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output = output + String.fromCharCode(chr3);
}
}
output = SAPO.Utility.String.utf8Decode(output);
return output;
},
*/
/**
* Debug function ?
*
* @method _debug
* @private
* @static
*/
_debug: function() {}
};
return Url;
});
/**
* @module Ink.Util.Swipe_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Util.Swipe', '1', ['Ink.Dom.Event_1'], function(Event) {
'use strict';
/**
* Subscribe swipe gestures!
* Supports filtering swipes be any combination of the criteria supported in the options.
*
* @class Ink.Util.Swipe
* @constructor
* @version 1
*
* @param {String|DOMElement} selector
* @param {Object} [options] Options for the Swipe detection
* @param {Function} [options.callback] Function to be called when a swipe is detected. Default is undefined.
* @param {Number} [options.forceAxis] Specify in which axis the swipe will be detected (x or y). Default is both.
* @param {Number} [options.maxDist] maximum allowed distance, in pixels
* @param {Number} [options.maxDuration] maximum allowed duration, in seconds
* @param {Number} [options.minDist] minimum allowed distance, in pixels
* @param {Number} [options.minDuration] minimum allowed duration, in seconds
* @param {Boolean} [options.stopEvents] Flag that specifies if it should stop events. Default is true.
* @param {Boolean} [options.storeGesture] Stores the gesture to be used for other purposes.
*/
var Swipe = function(el, options) {
this._options = Ink.extendObj({
callback: undefined,
forceAxis: undefined, // x | y
maxDist: undefined,
maxDuration: undefined,
minDist: undefined, // in pixels
minDuration: undefined, // in seconds
stopEvents: true,
storeGesture: false
}, options || {});
this._handlers = {
down: Ink.bindEvent(this._onDown, this),
move: Ink.bindEvent(this._onMove, this),
up: Ink.bindEvent(this._onUp, this)
};
this._element = Ink.i(el);
this._init();
};
Swipe._supported = ('ontouchstart' in document.documentElement);
Swipe.prototype = {
/**
* Initialization function. Called by the constructor.
*
* @method _init
* @private
*/
_init: function() {
var db = document.body;
Event.observe(db, 'touchstart', this._handlers.down);
if (this._options.storeGesture) {
Event.observe(db, 'touchmove', this._handlers.move);
}
Event.observe(db, 'touchend', this._handlers.up);
this._isOn = false;
},
/**
* Function to compare/get the parent of an element.
*
* @method _isMeOrParent
* @param {DOMElement} el Element to be compared with its parent
* @param {DOMElement} parentEl Element to be compared used as reference
* @return {DOMElement|Boolean} ParentElement of el or false in case it can't.
* @private
*/
_isMeOrParent: function(el, parentEl) {
if (!el) {
return;
}
do {
if (el === parentEl) {
return true;
}
el = el.parentNode;
} while (el);
return false;
},
/**
* MouseDown/TouchStart event handler
*
* @method _onDown
* @param {EventObject} ev window.event object
* @private
*/
_onDown: function(ev) {
if (event.changedTouches.length !== 1) { return; }
if (!this._isMeOrParent(ev.target, this._element)) { return; }
if( this._options.stopEvents === true ){
Event.stop(ev);
}
ev = ev.changedTouches[0];
this._isOn = true;
this._target = ev.target;
this._t0 = new Date().valueOf();
this._p0 = [ev.pageX, ev.pageY];
if (this._options.storeGesture) {
this._gesture = [this._p0];
this._time = [0];
}
},
/**
* MouseMove/TouchMove event handler
*
* @method _onMove
* @param {EventObject} ev window.event object
* @private
*/
_onMove: function(ev) {
if (!this._isOn || event.changedTouches.length !== 1) { return; }
if( this._options.stopEvents === true ){
Event.stop(ev);
}
ev = ev.changedTouches[0];
var t1 = new Date().valueOf();
var dt = (t1 - this._t0) * 0.001;
this._gesture.push([ev.pageX, ev.pageY]);
this._time.push(dt);
},
/**
* MouseUp/TouchEnd event handler
*
* @method _onUp
* @param {EventObject} ev window.event object
* @private
*/
_onUp: function(ev) {
if (!this._isOn || event.changedTouches.length !== 1) { return; }
if (this._options.stopEvents) {
Event.stop(ev);
}
ev = ev.changedTouches[0]; // TODO SHOULD CHECK IT IS THE SAME TOUCH
this._isOn = false;
var t1 = new Date().valueOf();
var p1 = [ev.pageX, ev.pageY];
var dt = (t1 - this._t0) * 0.001;
var dr = [
p1[0] - this._p0[0],
p1[1] - this._p0[1]
];
var dist = Math.sqrt(dr[0]*dr[0] + dr[1]*dr[1]);
var axis = Math.abs(dr[0]) > Math.abs(dr[1]) ? 'x' : 'y';
var o = this._options;
if (o.minDist && dist < o.minDist) { return; }
if (o.maxDist && dist > o.maxDist) { return; }
if (o.minDuration && dt < o.minDuration) { return; }
if (o.maxDuration && dt > o.maxDuration) { return; }
if (o.forceAxis && axis !== o.forceAxis) { return; }
var O = {
upEvent: ev,
elementId: this._element.id,
duration: dt,
dr: dr,
dist: dist,
axis: axis,
target: this._target
};
if (this._options.storeGesture) {
O.gesture = this._gesture;
O.time = this._time;
}
this._options.callback(this, O);
}
};
return Swipe;
});
/**
* @module Ink.Util.String_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Util.String', '1', [], function() {
'use strict';
/**
* String Manipulation Utilities
*
* @class Ink.Util.String
* @version 1
* @static
*/
var InkUtilString = {
/**
* List of special chars
*
* @property _chars
* @type {Array}
* @private
* @readOnly
* @static
*/
_chars: ['&','à','á','â','ã','ä','å','æ','ç','è','é',
'ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô',
'õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À',
'Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë',
'Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö',
'Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<',
'>','¢','£','¤','¥','¦','§','¨','©','ª','«',
'¬','\xad','®','¯','°','±','²','³','´','µ','¶',
'·','¸','¹','º','»','¼','½','¾'],
/**
* List of the special characters' html entities
*
* @property _entities
* @type {Array}
* @private
* @readOnly
* @static
*/
_entities: ['amp','agrave','aacute','acirc','atilde','auml','aring',
'aelig','ccedil','egrave','eacute','ecirc','euml','igrave',
'iacute','icirc','iuml','eth','ntilde','ograve','oacute',
'ocirc','otilde','ouml','oslash','ugrave','uacute','ucirc',
'uuml','yacute','thorn','yuml','Agrave','Aacute','Acirc',
'Atilde','Auml','Aring','AElig','Ccedil','Egrave','Eacute',
'Ecirc','Euml','Igrave','Iacute','Icirc','Iuml','ETH','Ntilde',
'Ograve','Oacute','Ocirc','Otilde','Ouml','Oslash','Ugrave',
'Uacute','Ucirc','Uuml','Yacute','THORN','euro','quot','szlig',
'lt','gt','cent','pound','curren','yen','brvbar','sect','uml',
'copy','ordf','laquo','not','shy','reg','macr','deg','plusmn',
'sup2','sup3','acute','micro','para','middot','cedil','sup1',
'ordm','raquo','frac14','frac12','frac34'],
/**
* List of accented chars
*
* @property _accentedChars
* @type {Array}
* @private
* @readOnly
* @static
*/
_accentedChars:['à','á','â','ã','ä','å',
'è','é','ê','ë',
'ì','í','î','ï',
'ò','ó','ô','õ','ö',
'ù','ú','û','ü',
'ç','ñ',
'À','Á','Â','Ã','Ä','Å',
'È','É','Ê','Ë',
'Ì','Í','Î','Ï',
'Ò','Ó','Ô','Õ','Ö',
'Ù','Ú','Û','Ü',
'Ç','Ñ'],
/**
* List of the accented chars (above), but without the accents
*
* @property _accentedRemovedChars
* @type {Array}
* @private
* @readOnly
* @static
*/
_accentedRemovedChars:['a','a','a','a','a','a',
'e','e','e','e',
'i','i','i','i',
'o','o','o','o','o',
'u','u','u','u',
'c','n',
'A','A','A','A','A','A',
'E','E','E','E',
'I','I','I','I',
'O','O','O','O','O',
'U','U','U','U',
'C','N'],
/**
* Object that contains the basic HTML unsafe chars, as keys, and their HTML entities as values
*
* @property _htmlUnsafeChars
* @type {Object}
* @private
* @readOnly
* @static
*/
_htmlUnsafeChars:{'<':'<','>':'>','&':'&','"':'"',"'":'''},
/**
* Convert first letter of a word to upper case <br />
* If param as more than one word, it converts first letter of all words that have more than 2 letters
*
* @method ucFirst
* @param {String} string
* @param {Boolean} [firstWordOnly=false] capitalize only first word.
* @return {String} string camel cased
* @public
* @static
*
* @example
* InkString.ucFirst('hello world'); // -> 'Hello World'
* InkString.ucFirst('hello world', true); // -> 'Hello world'
*/
ucFirst: function(string, firstWordOnly) {
var replacer = firstWordOnly ? /(^|\s)(\w)(\S{2,})/ : /(^|\s)(\w)(\S{2,})/g;
return string ? String(string).replace(replacer, function(_, $1, $2, $3){
return $1 + $2.toUpperCase() + $3.toLowerCase();
}) : string;
},
/**
* Remove spaces and new line from biggin and ends of string
*
* @method trim
* @param {String} string
* @return {String} string trimmed
* @public
* @static
*/
trim: function(string)
{
if (typeof string === 'string') {
return string.replace(/^\s+|\s+$|\n+$/g, '');
}
return string;
},
/**
* Removes HTML tags of string
*
* @method stripTags
* @param {String} string
* @param {String} allowed
* @return {String} String stripped from HTML tags, leaving only the allowed ones (if any)
* @public
* @static
* @example
* <script>
* var myvar='isto e um texto <b>bold</b> com imagem <img src=""> e br <br /> um <p>paragrafo</p>';
* SAPO.Utility.String.stripTags(myvar, 'b,u');
* </script>
*/
stripTags: function(string, allowed)
{
if (allowed && typeof allowed === 'string') {
var aAllowed = InkUtilString.trim(allowed).split(',');
var aNewAllowed = [];
var cleanedTag = false;
for(var i=0; i < aAllowed.length; i++) {
if(InkUtilString.trim(aAllowed[i]) !== '') {
cleanedTag = InkUtilString.trim(aAllowed[i].replace(/(\<|\>)/g, '').replace(/\s/, ''));
aNewAllowed.push('(<'+cleanedTag+'\\s[^>]+>|<(\\s|\\/)?(\\s|\\/)?'+cleanedTag+'>)');
}
}
var strAllowed = aNewAllowed.join('|');
var reAllowed = new RegExp(strAllowed, "i");
var aFoundTags = string.match(new RegExp("<[^>]*>", "g"));
for(var j=0; j < aFoundTags.length; j++) {
if(!aFoundTags[j].match(reAllowed)) {
string = string.replace((new RegExp(aFoundTags[j], "gm")), '');
}
}
return string;
} else {
return string.replace(/\<[^\>]+\>/g, '');
}
},
/**
* Convert listed characters to HTML entities
*
* @method htmlEntitiesEncode
* @param {String} string
* @return {String} string encoded
* @public
* @static
*/
htmlEntitiesEncode: function(string)
{
if (string && string.replace) {
var re = false;
for (var i = 0; i < InkUtilString._chars.length; i++) {
re = new RegExp(InkUtilString._chars[i], "gm");
string = string.replace(re, '&' + InkUtilString._entities[i] + ';');
}
}
return string;
},
/**
* Convert listed HTML entities to character
*
* @method htmlEntitiesDecode
* @param {String} string
* @return {String} string decoded
* @public
* @static
*/
htmlEntitiesDecode: function(string)
{
if (string && string.replace) {
var re = false;
for (var i = 0; i < InkUtilString._entities.length; i++) {
re = new RegExp("&"+InkUtilString._entities[i]+";", "gm");
string = string.replace(re, InkUtilString._chars[i]);
}
string = string.replace(/&#[^;]+;?/g, function($0){
if ($0.charAt(2) === 'x') {
return String.fromCharCode(parseInt($0.substring(3), 16));
}
else {
return String.fromCharCode(parseInt($0.substring(2), 10));
}
});
}
return string;
},
/**
* Encode a string to UTF8
*
* @method utf8Encode
* @param {String} string
* @return {String} string utf8 encoded
* @public
* @static
*/
utf8Encode: function(string)
{
string = string.replace(/\r\n/g,"\n");
var utfstring = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utfstring += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utfstring += String.fromCharCode((c >> 6) | 192);
utfstring += String.fromCharCode((c & 63) | 128);
}
else {
utfstring += String.fromCharCode((c >> 12) | 224);
utfstring += String.fromCharCode(((c >> 6) & 63) | 128);
utfstring += String.fromCharCode((c & 63) | 128);
}
}
return utfstring;
},
/**
* Make a string shorter without cutting words
*
* @method shortString
* @param {String} str
* @param {Number} n - number of chars of the short string
* @return {String} string shortened
* @public
* @static
*/
shortString: function(str,n) {
var words = str.split(' ');
var resultstr = '';
for(var i = 0; i < words.length; i++ ){
if((resultstr + words[i] + ' ').length>=n){
resultstr += '…';
break;
}
resultstr += words[i] + ' ';
}
return resultstr;
},
/**
* Truncates a string, breaking words and adding ... at the end
*
* @method truncateString
* @param {String} str
* @param {Number} length - length limit for the string. String will be
* at most this big, ellipsis included.
* @return {String} string truncated
* @public
* @static
*/
truncateString: function(str, length) {
if(str.length - 1 > length) {
return str.substr(0, length - 1) + "\u2026";
} else {
return str;
}
},
/**
* Decode a string from UTF8
*
* @method utf8Decode
* @param {String} string
* @return {String} string utf8 decoded
* @public
* @static
*/
utf8Decode: function(utfstring)
{
var string = "";
var i = 0, c = 0, c2 = 0, c3 = 0;
while ( i < utfstring.length ) {
c = utfstring.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utfstring.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utfstring.charCodeAt(i+1);
c3 = utfstring.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
},
/**
* Convert all accented chars to char without accent.
*
* @method removeAccentedChars
* @param {String} string
* @return {String} string without accented chars
* @public
* @static
*/
removeAccentedChars: function(string)
{
var newString = string;
var re = false;
for (var i = 0; i < InkUtilString._accentedChars.length; i++) {
re = new RegExp(InkUtilString._accentedChars[i], "gm");
newString = newString.replace(re, '' + InkUtilString._accentedRemovedChars[i] + '');
}
return newString;
},
/**
* Count the number of occurrences of a specific needle in a haystack
*
* @method substrCount
* @param {String} haystack
* @param {String} needle
* @return {Number} Number of occurrences
* @public
* @static
*/
substrCount: function(haystack,needle)
{
return haystack ? haystack.split(needle).length - 1 : 0;
},
/**
* Eval a JSON string to a JS object
*
* @method evalJSON
* @param {String} strJSON
* @param {Boolean} sanitize
* @return {Object} JS Object
* @public
* @static
*/
evalJSON: function(strJSON, sanitize) {
/* jshint evil:true */
if( (typeof sanitize === 'undefined' || sanitize === null) || InkUtilString.isJSON(strJSON)) {
try {
if(typeof(JSON) !== "undefined" && typeof(JSON.parse) !== 'undefined'){
return JSON.parse(strJSON);
}
return eval('('+strJSON+')');
} catch(e) {
throw new Error('ERROR: Bad JSON string...');
}
}
},
/**
* Checks if a string is a valid JSON object (string encoded)
*
* @method isJSON
* @param {String} str
* @return {Boolean}
* @public
* @static
*/
isJSON: function(str)
{
str = str.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
},
/**
* Escapes unsafe html chars to their entities
*
* @method htmlEscapeUnsafe
* @param {String} str String to escape
* @return {String} Escaped string
* @public
* @static
*/
htmlEscapeUnsafe: function(str){
var chars = InkUtilString._htmlUnsafeChars;
return str != null ? String(str).replace(/[<>&'"]/g,function(c){return chars[c];}) : str;
},
/**
* Normalizes whitespace in string.
* String is trimmed and sequences of many
* Whitespaces are collapsed.
*
* @method normalizeWhitespace
* @param {String} str String to normalize
* @return {String} string normalized
* @public
* @static
*/
normalizeWhitespace: function(str){
return str != null ? InkUtilString.trim(String(str).replace(/\s+/g,' ')) : str;
},
/**
* Converts string to unicode
*
* @method toUnicode
* @param {String} str
* @return {String} string unicoded
* @public
* @static
*/
toUnicode: function(str)
{
if (typeof str === 'string') {
var unicodeString = '';
var inInt = false;
var theUnicode = false;
var total = str.length;
var i=0;
while(i < total)
{
inInt = str.charCodeAt(i);
if( (inInt >= 32 && inInt <= 126) ||
inInt == 8 ||
inInt == 9 ||
inInt == 10 ||
inInt == 12 ||
inInt == 13 ||
inInt == 32 ||
inInt == 34 ||
inInt == 47 ||
inInt == 58 ||
inInt == 92) {
/*
if(inInt == 34 || inInt == 92 || inInt == 47) {
theUnicode = '\\'+str.charAt(i);
} else {
}
*/
if(inInt == 8) {
theUnicode = '\\b';
} else if(inInt == 9) {
theUnicode = '\\t';
} else if(inInt == 10) {
theUnicode = '\\n';
} else if(inInt == 12) {
theUnicode = '\\f';
} else if(inInt == 13) {
theUnicode = '\\r';
} else {
theUnicode = str.charAt(i);
}
} else {
theUnicode = str.charCodeAt(i).toString(16)+''.toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
}
unicodeString += theUnicode;
i++;
}
return unicodeString;
}
},
/**
* Escapes a unicode character. returns \xXX if hex smaller than 0x100, otherwise \uXXXX
*
* @method escape
* @param {String} c Char
* @return {String} escaped char
* @public
* @static
*/
/**
* @param {String} c char
*/
escape: function(c) {
var hex = (c).charCodeAt(0).toString(16).split('');
if (hex.length < 3) {
while (hex.length < 2) { hex.unshift('0'); }
hex.unshift('x');
}
else {
while (hex.length < 4) { hex.unshift('0'); }
hex.unshift('u');
}
hex.unshift('\\');
return hex.join('');
},
/**
* Unescapes a unicode character escape sequence
*
* @method unescape
* @param {String} es Escape sequence
* @return {String} String des-unicoded
* @public
* @static
*/
unescape: function(es) {
var idx = es.lastIndexOf('0');
idx = idx === -1 ? 2 : Math.min(idx, 2);
//console.log(idx);
var hexNum = es.substring(idx);
//console.log(hexNum);
var num = parseInt(hexNum, 16);
return String.fromCharCode(num);
},
/**
* Escapes a string to unicode characters
*
* @method escapeText
* @param {String} txt
* @param {Array} [whiteList]
* @return {String} Escaped to Unicoded string
* @public
* @static
*/
escapeText: function(txt, whiteList) {
if (whiteList === undefined) {
whiteList = ['[', ']', '\'', ','];
}
var txt2 = [];
var c, C;
for (var i = 0, f = txt.length; i < f; ++i) {
c = txt[i];
C = c.charCodeAt(0);
if (C < 32 || C > 126 && whiteList.indexOf(c) === -1) {
c = InkUtilString.escape(c);
}
txt2.push(c);
}
return txt2.join('');
},
/**
* Regex to check escaped strings
*
* @property escapedCharRegex
* @type {Regex}
* @public
* @readOnly
* @static
*/
escapedCharRegex: /(\\x[0-9a-fA-F]{2})|(\\u[0-9a-fA-F]{4})/g,
/**
* Unescapes a string
*
* @method unescapeText
* @param {String} txt
* @return {String} Unescaped string
* @public
* @static
*/
unescapeText: function(txt) {
/*jshint boss:true */
var m;
while (m = InkUtilString.escapedCharRegex.exec(txt)) {
m = m[0];
txt = txt.replace(m, InkUtilString.unescape(m));
InkUtilString.escapedCharRegex.lastIndex = 0;
}
return txt;
},
/**
* Compares two strings
*
* @method strcmp
* @param {String} str1
* @param {String} str2
* @return {Number}
* @public
* @static
*/
strcmp: function(str1, str2) {
return ((str1 === str2) ? 0 : ((str1 > str2) ? 1 : -1));
},
/**
* Splits long string into string of, at most, maxLen (that is, all but last have length maxLen,
* last can measure maxLen or less)
*
* @method packetize
* @param {String} string string to divide
* @param {Number} maxLen packet size
* @return {Array} string divided
* @public
* @static
*/
packetize: function(str, maxLen) {
var len = str.length;
var parts = new Array( Math.ceil(len / maxLen) );
var chars = str.split('');
var sz, i = 0;
while (len) {
sz = Math.min(maxLen, len);
parts[i++] = chars.splice(0, sz).join('');
len -= sz;
}
return parts;
}
};
return InkUtilString;
});
/**
* @module Ink.Util.Json_1
*
* @author inkdev AT sapo.pt
*/
Ink.createModule('Ink.Util.Json', '1', [], function() {
'use strict';
var function_call = Function.prototype.call;
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
function twoDigits(n) {
var r = '' + n;
if (r.length === 1) {
return '0' + r;
} else {
return r;
}
}
var date_toISOString = Date.prototype.toISOString ?
Ink.bind(function_call, Date.prototype.toISOString) :
function(date) {
// Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
return date.getUTCFullYear()
+ '-' + twoDigits( date.getUTCMonth() + 1 )
+ '-' + twoDigits( date.getUTCDate() )
+ 'T' + twoDigits( date.getUTCHours() )
+ ':' + twoDigits( date.getUTCMinutes() )
+ ':' + twoDigits( date.getUTCSeconds() )
+ '.' + String( (date.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
+ 'Z';
};
/**
* Use this class to convert JSON strings to JavaScript objects
* `(Json.parse)` and also to do the opposite operation `(Json.stringify)`.
* Internally, the standard JSON implementation is used if available
* Otherwise, the functions mimic the standard implementation.
*
* Here's how to produce JSON from an existing object:
*
* Ink.requireModules(['Ink.Util.Json_1'], function (Json) {
* var obj = {
* key1: 'value1',
* key2: 'value2',
* keyArray: ['arrayValue1', 'arrayValue2', 'arrayValue3']
* };
* Json.stringify(obj); // The above object as a JSON string
* });
*
* And here is how to parse JSON:
*
* Ink.requireModules(['Ink.Util.Json_1'], function (Json) {
* var source = '{"key": "value", "array": [true, null, false]}';
* Json.parse(source); // The above JSON string as an object
* });
* @class Ink.Util.Json
* @static
*
*/
var InkJson = {
_nativeJSON: window.JSON || null,
_convertToUnicode: false,
// Escape characters so as to embed them in JSON strings
_escape: function (theString) {
var _m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' };
if (/["\\\x00-\x1f]/.test(theString)) {
theString = theString.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = _m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
});
}
return theString;
},
// A character conversion map
_toUnicode: function (theString)
{
if(!this._convertToUnicode) {
return this._escape(theString);
} else {
var unicodeString = '';
var inInt = false;
var theUnicode = false;
var i = 0;
var total = theString.length;
while(i < total) {
inInt = theString.charCodeAt(i);
if( (inInt >= 32 && inInt <= 126) ||
//(inInt >= 48 && inInt <= 57) ||
//(inInt >= 65 && inInt <= 90) ||
//(inInt >= 97 && inInt <= 122) ||
inInt === 8 ||
inInt === 9 ||
inInt === 10 ||
inInt === 12 ||
inInt === 13 ||
inInt === 32 ||
inInt === 34 ||
inInt === 47 ||
inInt === 58 ||
inInt === 92) {
if(inInt === 34 || inInt === 92 || inInt === 47) {
theUnicode = '\\'+theString.charAt(i);
} else if(inInt === 8) {
theUnicode = '\\b';
} else if(inInt === 9) {
theUnicode = '\\t';
} else if(inInt === 10) {
theUnicode = '\\n';
} else if(inInt === 12) {
theUnicode = '\\f';
} else if(inInt === 13) {
theUnicode = '\\r';
} else {
theUnicode = theString.charAt(i);
}
} else {
if(this._convertToUnicode) {
theUnicode = theString.charCodeAt(i).toString(16)+''.toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
} else {
theUnicode = theString.charAt(i);
}
}
unicodeString += theUnicode;
i++;
}
return unicodeString;
}
},
_stringifyValue: function(param) {
if (typeof param === 'string') {
return '"' + this._toUnicode(param) + '"';
} else if (typeof param === 'number' && (isNaN(param) || !isFinite(param))) { // Unusable numbers go null
return 'null';
} else if (typeof param === 'undefined' || param === null) { // And so does undefined
return 'null';
} else if (typeof param.toJSON === 'function') {
var t = param.toJSON();
if (typeof t === 'string') {
return '"' + this._escape(t) + '"';
} else {
return this._escape(t.toString());
}
} else if (typeof param === 'number' || typeof param === 'boolean') { // These ones' toString methods return valid JSON.
return '' + param;
} else if (typeof param === 'function') {
return 'null'; // match JSON.stringify
} else if (param.constructor === Date) {
throw ''
return '"' + this._escape(date_toISOString(param)) + '"';
} else if (param.constructor === Array) {
var arrayString = '';
for (var i = 0, len = param.length; i < len; i++) {
if (i > 0) {
arrayString += ',';
}
arrayString += this._stringifyValue(param[i]);
}
return '[' + arrayString + ']';
} else { // Object
var objectString = '';
for (var k in param) {
if ({}.hasOwnProperty.call(param, k)) {
if (objectString !== '') {
objectString += ',';
}
objectString += '"' + this._escape(k) + '": ' + this._stringifyValue(param[k]);
}
}
return '{' + objectString + '}';
}
},
/**
* serializes a JSON object into a string.
*
* @method stringify
* @param {Object} input Data to be serialized into JSON
* @param {Boolean} convertToUnicode When `true`, converts string contents to unicode \uXXXX
* @return {String} serialized string
*
* @example
* Json.stringify({a:1.23}); // -> string: '{"a": 1.23}'
*/
stringify: function(input, convertToUnicode) {
this._convertToUnicode = !!convertToUnicode;
if(!this._convertToUnicode && this._nativeJSON) {
return this._nativeJSON.stringify(input);
}
return this._stringifyValue(input); // And recurse.
},
/**
* @method parse
* @param text {String} Input string
* @param reviver {Function} Function receiving `(key, value)`, and `this`=(containing object), used to walk objects.
*
* @example
* Simple example:
*
* Json.parse('{"a": "3","numbers":false}',
* function (key, value) {
* if (!this.numbers && key === 'a') {
* return "NO NUMBERS";
* } else {
* return value;
* }
* }); // -> object: {a: 'NO NUMBERS', numbers: false}
*/
/* From https://github.com/douglascrockford/JSON-js/blob/master/json.js */
parse: function (text, reviver) {
/*jshint evil:true*/
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
}
};
return InkJson;
});
/**
* @module Ink.Util.I18n_1
* @author inkdev AT sapo.pt
*/
Ink.createModule('Ink.Util.I18n', '1', [], function () {
'use strict';
var pattrText = /\{(?:(\{.*?})|(?:%s:)?(\d+)|(?:%s)?|([\w-]+))}/g;
var funcOrVal = function( ret , args ) {
if ( typeof ret === 'function' ) {
return ret.apply(this, args);
} else if (typeof ret !== undefined) {
return ret;
} else {
return '';
}
};
/**
* Creates a new internationalization helper object
*
* @class Ink.Util.I18n
* @constructor
*
* @param {Object} dict object mapping language codes (in the form of `pt_PT`, `pt_BR`, `fr`, `en_US`, etc.) to their Object dictionaries.
* @param {Object} dict.(dictionaries...)
* @param {String} [lang='pt_PT'] language code of the target language
*
* @example
* var dictionaries = { // This could come from a JSONP request from your server
* 'pt_PT': {
* 'hello': 'olá',
* 'me': 'eu',
* 'i have a {} for you': 'tenho um {} para ti' // Old syntax using `{%s}` tokens still available
* },
* 'pt_BR': {
* 'hello': 'oi',
* 'me': 'eu',
* 'i have a {} for you': 'tenho um {} para você'
* }
* };
* Ink.requireModules(['Ink.Util.I18n_1'], function (I18n) {
* var i18n = new I18n(dictionaries, 'pt_PT');
* i18n.text('hello'); // returns 'olá'
* i18n.text('i have a {} for you', 'IRON SWORD'); // returns 'tenho um IRON SWORD' para ti
*
* i18n.lang('pt_BR'); // Changes language. pt_BR dictionary is loaded
* i18n.text('hello'); // returns 'oi'
*
* i18n.lang('en_US'); // Missing language.
* i18n.text('hello'); // returns 'hello'. If testMode is on, returns '[hello]'
* });
*
* @example
* // The old {%s} syntax from libsapo's i18n is still supported
* i18n.text('hello, {%s}!', 'someone'); // -> 'olá, someone!'
*/
var I18n = function( dict , lang , testMode ) {
if ( !( this instanceof I18n ) ) { return new I18n( dict , lang , testMode ); }
this.reset( )
.lang( lang )
.testMode( testMode )
.append( dict || { } , lang );
};
I18n.prototype = {
reset: function( ) {
this._dicts = [ ];
this._dict = { };
this._testMode = false;
this._lang = this._gLang;
return this;
},
/**
* Adds translation strings for this helper to use.
*
* @method append
* @param {Object} dict object containing language objects identified by their language code
* @example
* var i18n = new I18n({}, 'pt_PT');
* i18n.append({'pt_PT': {
* 'sfraggles': 'braggles'
* }});
* i18n.text('sfraggles') // -> 'braggles'
*/
append: function( dict ) {
this._dicts.push( dict );
this._dict = Ink.extendObj(this._dict , dict[ this._lang ] );
return this;
},
/**
* Get the language code
*
* @returns {String} the language code for this instance
* @method {String} lang
*/
/**
* Set the language. If there are more dictionaries available in cache, they will be loaded.
*
* @method lang
* @param lang {String} Language code to set this instance to.
*/
lang: function( lang ) {
if ( !arguments.length ) { return this._lang; }
if ( lang && this._lang !== lang ) {
this._lang = lang;
this._dict = { };
for ( var i = 0, l = this._dicts.length; i < l; i++ ) {
this._dict = Ink.extendObj( this._dict , this._dicts[ i ][ lang ] || { } );
}
}
return this;
},
/**
* Get the testMode
*
* @returns {Boolean} the testMode for this instance
* @method {Boolean} testMode
*/
/**
* Sets or unsets test mode. In test mode, unknown strings are wrapped
* in `[ ... ]`. This is useful for debugging your application and
* making sure all your translation keys are in place.
*
* @method testMode
* @param {Boolean} bool boolean value to set the test mode to.
*/
testMode: function( bool ) {
if ( !arguments.length ) { return !!this._testMode; }
if ( bool !== undefined ) { this._testMode = !!bool; }
return this;
},
/**
* Return an arbitrary key from the current language dictionary
*
* @method getKey
* @param {String} key
* @return {Any} The object which happened to be in the current language dictionary on the given key.
*
* @example
* _.getKey('astring'); // -> 'a translated string'
* _.getKey('anobject'); // -> {'a': 'translated object'}
* _.getKey('afunction'); // -> function () { return 'this is a localized function' }
*/
getKey: function( key ) {
var ret;
var gLang = this._gLang;
var lang = this._lang;
if ( key in this._dict ) {
ret = this._dict[ key ];
} else {
I18n.lang( lang );
ret = this._gDict[ key ];
I18n.lang( gLang );
}
return ret;
},
/**
* Given a translation key, return a translated string, with replaced parameters.
* When a translated string is not available, the original string is returned unchanged.
*
* @method {String} text
* @param {String} str key to look for in i18n dictionary (which is returned verbatim if unknown)
* @param {Object} [namedParms] named replacements. Replaces {named} with values in this object.
* @param {String} [arg1] replacement #1 (replaces first {} and all {1})
* @param {String} [arg2] replacement #2 (replaces second {} and all {2})
* @param {String} [argn...] replacement #n (replaces nth {} and all {n})
*
* @example
* _('Gosto muito de {} e o céu é {}.', 'carros', 'azul');
* // returns 'Gosto muito de carros e o céu é azul.'
*
* @example
* _('O {1} é {2} como {2} é a cor do {3}.', 'carro', 'azul', 'FCP');
* // returns 'O carro é azul como azul é o FCP.'
*
* @example
* _('O {person1} dava-se com a {person2}', {person1: 'coisinho', person2: 'coisinha'});
* // -> 'O coisinho dava-se com a coisinha'
*
* @example
* // This is a bit more complex
* var i18n = make().lang('pt_PT').append({
* pt_PT: {
* array: [1, 2],
* object: {'a': '-a-', 'b': '-b-'},
* func: function (a, b) {return '[[' + a + ',' + b + ']]';}
* }
* });
* i18n.text('array', 0); // -> '1'
* i18n.text('object', 'a'); // -> '-a-'
* i18n.text('func', 'a', 'b'); // -> '[[a,b]]'
*/
text: function( str /*, replacements...*/ ) {
if ( typeof str !== 'string' ) { return; } // Backwards-compat
var pars = Array.prototype.slice.call( arguments , 1 );
var idx = 0;
var isObj = typeof pars[ 0 ] === 'object';
var original = this.getKey( str );
if ( original === undefined ) { original = this._testMode ? '[' + str + ']' : str; }
if ( typeof original === 'number' ) { original += ''; }
if (typeof original === 'string') {
original = original.replace( pattrText , function( m , $1 , $2 , $3 ) {
var ret =
$1 ? $1 :
$2 ? pars[ $2 - ( isObj ? 0 : 1 ) ] :
$3 ? pars[ 0 ][ $3 ] || '' :
pars[ (idx++) + ( isObj ? 1 : 0 ) ]
return funcOrVal( ret , [idx].concat(pars) );
});
return original;
}
return (
typeof original === 'function' ? original.apply( this , pars ) :
original instanceof Array ? funcOrVal( original[ pars[ 0 ] ] , pars ) :
typeof original === 'object' ? funcOrVal( original[ pars[ 0 ] ] , pars ) :
'');
},
/**
* Given a singular string, a plural string, and a number, translates
* either the singular or plural string.
*
* @method ntext
* @return {String}
*
* @param {String} strSin word to use when count is 1
* @param {String} strPlur word to use otherwise
* @param {Number} count number which defines which word to use
* @param [...] extra arguments, to be passed to `text()`
*
* @example
* i18n.ntext('platypus', 'platypuses', 1); // returns 'ornitorrinco'
* i18n.ntext('platypus', 'platypuses', 2); // returns 'ornitorrincos'
*
* @example
* // The "count" argument is passed to text()
* i18n.ntext('{} platypus', '{} platypuses', 1); // returns '1 ornitorrinco'
* i18n.ntext('{} platypus', '{} platypuses', 2); // returns '2 ornitorrincos'
*/
ntext: function( strSin , strPlur , count ) {
var pars = Array.prototype.slice.apply( arguments );
var original;
if ( pars.length === 2 && typeof strPlur === 'number' ) {
original = this.getKey( strSin );
if ( !( original instanceof Array ) ) { return ''; }
pars.splice( 0 , 1 );
original = original[ strPlur === 1 ? 0 : 1 ];
} else {
pars.splice( 0 , 2 );
original = count === 1 ? strSin : strPlur;
}
return this.text.apply( this , [ original ].concat( pars ) );
},
/**
* Returns the ordinal suffix of `num` (For example, 1 > 'st', 2 > 'nd', 5 > 'th', ...).
*
* This works by using transforms (in the form of Objects or Functions) passed into the
* function or found in the special key `_ordinals` in the active language dictionary.
*
* @method ordinal
*
* @param {Number} num Input number
*
* @param {Object|Function} [options={}]
*
* Maps for translating. Each of these options' fallback is found in the current
* language's dictionary. The lookup order is the following:
*
* 1. `exceptions`
* 2. `byLastDigit`
* 3. `default`
*
* Each of these may be either an `Object` or a `Function`. If it's a function, it
* is called (with `number` and `digit` for any function except for byLastDigit,
* which is called with the `lastDigit` of the number in question), and if the
* function returns a string, that is used. If it's an object, the property is
* looked up using `[...]`. If what is found is a string, it is used.
*
* @param {Object|Function} [options.byLastDigit={}]
* If the language requires the last digit to be considered, mappings of last digits
* to ordinal suffixes can be created here.
*
* @param {Object|Function} [options.exceptions={}]
* Map unique, special cases to their ordinal suffixes.
*
* @returns {String} Ordinal suffix for `num`.
*
* @example
* var i18n = new I18n({
* pt_PT: { // 1º, 2º, 3º, 4º, ...
* _ordinal: { // The _ordinals key each translation dictionary is special.
* 'default': "º" // Usually the suffix is "º" in portuguese...
* }
* },
* fr: { // 1er, 2e, 3e, 4e, ...
* _ordinal: { // The _ordinals key is special.
* 'default': "e", // Usually the suffix is "e" in french...
* exceptions: {
* 1: "er" // ... Except for the number one.
* }
* }
* },
* en_US: { // 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 21st, 22nd...
* _ordinal: {
* 'default': "th",// Usually the digit is "th" in english...
* byLastDigit: {
* 1: "st", // When the last digit is 1, use "th"...
* 2: "nd", // When the last digit is 2, use "nd"...
* 3: "rd" // When the last digit is 3, use "rd"...
* },
* exceptions: { // But these numbers are special
* 0: "",
* 11: "th",
* 12: "th",
* 13: "th"
* }
* }
* }
* }, 'pt_PT');
*
* i18n.ordinal(1); // returns 'º'
* i18n.ordinal(2); // returns 'º'
* i18n.ordinal(11); // returns 'º'
*
* i18n.lang('fr');
* i18n.ordinal(1); // returns 'er'
* i18n.ordinal(2); // returns 'e'
* i18n.ordinal(11); // returns 'e'
*
* i18n.lang('en_US');
* i18n.ordinal(1); // returns 'st'
* i18n.ordinal(2); // returns 'nd'
* i18n.ordinal(12); // returns 'th'
* i18n.ordinal(22); // returns 'nd'
* i18n.ordinal(3); // returns 'rd'
* i18n.ordinal(4); // returns 'th'
* i18n.ordinal(5); // returns 'th'
*
**/
ordinal: function( num ) {
if ( num === undefined ) { return ''; }
var lastDig = +num.toString( ).slice( -1 );
var ordDict = this.getKey( '_ordinals' );
if ( ordDict === undefined ) { return ''; }
if ( typeof ordDict === 'string' ) { return ordDict; }
var ret;
if ( typeof ordDict === 'function' ) {
ret = ordDict( num , lastDig );
if ( typeof ret === 'string' ) { return ret; }
}
if ( 'exceptions' in ordDict ) {
ret = typeof ordDict.exceptions === 'function' ? ordDict.exceptions( num , lastDig ) :
num in ordDict.exceptions ? funcOrVal( ordDict.exceptions[ num ] , [num , lastDig] ) :
undefined;
if ( typeof ret === 'string' ) { return ret; }
}
if ( 'byLastDigit' in ordDict ) {
ret = typeof ordDict.byLastDigit === 'function' ? ordDict.byLastDigit( lastDig , num ) :
lastDig in ordDict.byLastDigit ? funcOrVal( ordDict.byLastDigit[ lastDig ] , [lastDig , num] ) :
undefined;
if ( typeof ret === 'string' ) { return ret; }
}
if ( 'default' in ordDict ) {
ret = funcOrVal( ordDict['default'] , [ num , lastDig ] );
if ( typeof ret === 'string' ) { return ret; }
}
return '';
},
/**
* Returns an alias to `text()`, for convenience. The resulting function is
* traditionally assigned to "_".
*
* @method alias
* @returns {Function} an alias to `text()`. You can also access the rest of the translation API through this alias.
*
* @example
* var i18n = new I18n({
* 'pt_PT': {
* 'hi': 'olá',
* '{} day': '{} dia',
* '{} days': '{} dias',
* '_ordinals': {
* 'default': 'º'
* }
* }
* }, 'pt_PT');
* var _ = i18n.alias();
* _('hi'); // -> 'olá'
* _('{} days', 3); // -> '3 dias'
* _.ntext('{} day', '{} days', 2); // -> '2 dias'
* _.ntext('{} day', '{} days', 1); // -> '1 dia'
* _.ordinal(3); // -> 'º'
*/
alias: function( ) {
var ret = Ink.bind( I18n.prototype.text , this );
ret.ntext = Ink.bind( I18n.prototype.ntext , this );
ret.append = Ink.bind( I18n.prototype.append , this );
ret.ordinal = Ink.bind( I18n.prototype.ordinal , this );
ret.testMode = Ink.bind( I18n.prototype.testMode , this );
return ret;
}
};
/**
* @static
* @method I18n.reset
*
* Reset I18n global state (global dictionaries, and default language for instances)
**/
I18n.reset = function( ) {
I18n.prototype._gDicts = [ ];
I18n.prototype._gDict = { };
I18n.prototype._gLang = 'pt_PT';
};
I18n.reset( );
/**
* @static
* @method I18n.append
*
* @param dict {Object} Dictionary to be added
* @param lang {String} Language to be added to
*
* Add a dictionary to be used in all I18n instances for the corresponding language
*/
I18n.append = function( dict , lang ) {
if ( lang ) {
if ( !( lang in dict ) ) {
var obj = { };
obj[ lang ] = dict;
dict = obj;
}
if ( lang !== I18n.prototype._gLang ) { I18n.lang( lang ); }
}
I18n.prototype._gDicts.push( dict );
Ink.extendObj( I18n.prototype._gDict , dict[ I18n.prototype._gLang ] );
};
/**
* @static
* @method I18n.lang
*
* @param lang {String} String in the format `"pt_PT"`, `"fr"`, etc.
*
* Set global default language of I18n instances to `lang`
*/
/**
* @static
* @method I18n.lang
*
* Get the current default language of I18n instances.
*
* @return {String} language code
*/
I18n.lang = function( lang ) {
if ( !arguments.length ) { return I18n.prototype._gLang; }
if ( lang && I18n.prototype._gLang !== lang ) {
I18n.prototype._gLang = lang;
I18n.prototype._gDict = { };
for ( var i = 0, l = I18n.prototype._gDicts.length; i < l; i++ ) {
Ink.extendObj( I18n.prototype._gDict , I18n.prototype._gDicts[ i ][ lang ] || { } );
}
}
};
return I18n;
});
/**
* @module Ink.Util.Dumper_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Util.Dumper', '1', [], function() {
'use strict';
/**
* Dump/Profiling Utilities
*
* @class Ink.Util.Dumper
* @version 1
* @static
*/
var Dumper = {
/**
* Hex code for the 'tab'
*
* @property _tab
* @type {String}
* @private
* @readOnly
* @static
*
*/
_tab: '\xA0\xA0\xA0\xA0',
/**
* Function that returns the argument passed formatted
*
* @method _formatParam
* @param {Mixed} param
* @return {String} The argument passed formatted
* @private
* @static
*/
_formatParam: function(param)
{
var formated = '';
switch(typeof(param)) {
case 'string':
formated = '(string) '+param;
break;
case 'number':
formated = '(number) '+param;
break;
case 'boolean':
formated = '(boolean) '+param;
break;
case 'object':
if(param !== null) {
if(param.constructor === Array) {
formated = 'Array \n{\n' + this._outputFormat(param, 0) + '\n}';
} else {
formated = 'Object \n{\n' + this._outputFormat(param, 0) + '\n}';
}
} else {
formated = 'null';
}
break;
default:
formated = false;
}
return formated;
},
/**
* Function that returns the tabs concatenated
*
* @method _getTabs
* @param {Number} numberOfTabs Number of Tabs
* @return {String} Tabs concatenated
* @private
* @static
*/
_getTabs: function(numberOfTabs)
{
var tabs = '';
for(var _i = 0; _i < numberOfTabs; _i++) {
tabs += this._tab;
}
return tabs;
},
/**
* Function that formats the parameter to display
*
* @method _outputFormat
* @param {Any} param
* @param {Number} dim
* @return {String} The parameter passed formatted to displat
* @private
* @static
*/
_outputFormat: function(param, dim)
{
var formated = '';
//var _strVal = false;
var _typeof = false;
for(var key in param) {
if(param[key] !== null) {
if(typeof(param[key]) === 'object' && (param[key].constructor === Array || param[key].constructor === Object)) {
if(param[key].constructor === Array) {
_typeof = 'Array';
} else if(param[key].constructor === Object) {
_typeof = 'Object';
}
formated += this._tab + this._getTabs(dim) + '[' + key + '] => <b>'+_typeof+'</b>\n';
formated += this._tab + this._getTabs(dim) + '{\n';
formated += this._outputFormat(param[key], dim + 1) + this._tab + this._getTabs(dim) + '}\n';
} else if(param[key].constructor === Function) {
continue;
} else {
formated = formated + this._tab + this._getTabs(dim) + '[' + key + '] => ' + param[key] + '\n';
}
} else {
formated = formated + this._tab + this._getTabs(dim) + '[' + key + '] => null \n';
}
}
return formated;
},
/**
* Print variable structure. Can be passed an output target
*
* @method printDump
* @param {Object|String|Boolean} param
* @param {optional String|Object} target (can be an element ID or an element)
* @public
* @static
*/
printDump: function(param, target)
{
if(!target || typeof(target) === 'undefined') {
document.write('<pre>'+this._formatParam(param)+'</pre>');
} else {
if(typeof(target) === 'string') {
document.getElementById(target).innerHTML = '<pre>' + this._formatParam(param) + '</pre>';
} else if(typeof(target) === 'object') {
target.innerHTML = '<pre>'+this._formatParam(param)+'</pre>';
} else {
throw "TARGET must be an element or an element ID";
}
}
},
/**
* Function that returns the variable's structure
*
* @method returnDump
* @param {Object|String|Boolean} param
* @return {String} The variable structure
* @public
* @static
*/
returnDump: function(param)
{
return this._formatParam(param);
},
/**
* Function that alerts the variable structure
*
* @method alertDump
* @param {Object|String|Boolean} param
* @public
* @static
*/
alertDump: function(param)
{
window.alert(this._formatParam(param).replace(/(<b>)(Array|Object)(<\/b>)/g, "$2"));
},
/**
* Print to new window the variable structure
*
* @method windowDump
* @param {Object|String|Boolean} param
* @public
* @static
*/
windowDump: function(param)
{
var dumperwindow = 'dumperwindow_'+(Math.random() * 10000);
var win = window.open('',
dumperwindow,
'width=400,height=300,left=50,top=50,status,menubar,scrollbars,resizable'
);
win.document.open();
win.document.write('<pre>'+this._formatParam(param)+'</pre>');
win.document.close();
win.focus();
}
};
return Dumper;
});
/**
* @module Ink.Util.Date_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Util.Date', '1', [], function() {
'use strict';
/**
* Class to provide the same features that php date does
*
* @class Ink.Util.Date
* @version 1
* @static
*/
var InkDate = {
/**
* Function that returns the string representation of the month [PT only]
*
* @method _months
* @param {Number} index Month javascript (0 to 11)
* @return {String} The month's name
* @private
* @static
* @example
* console.log( InkDate._months(0) ); // Result: Janeiro
*/
_months: function(index){
var _m = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
return _m[index];
},
/**
* Function that returns the month [PT only] ( 0 to 11 )
*
* @method _iMonth
* @param {String} month Month javascript (0 to 11)
* @return {Number} The month's number
* @private
* @static
* @example
* console.log( InkDate._iMonth('maio') ); // Result: 4
*/
_iMonth : function( month )
{
if ( Number( month ) ) { return +month - 1; }
return {
'janeiro' : 0 ,
'jan' : 0 ,
'fevereiro' : 1 ,
'fev' : 1 ,
'março' : 2 ,
'mar' : 2 ,
'abril' : 3 ,
'abr' : 3 ,
'maio' : 4 ,
'mai' : 4 ,
'junho' : 5 ,
'jun' : 5 ,
'julho' : 6 ,
'jul' : 6 ,
'agosto' : 7 ,
'ago' : 7 ,
'setembro' : 8 ,
'set' : 8 ,
'outubro' : 9 ,
'out' : 9 ,
'novembro' : 10 ,
'nov' : 10 ,
'dezembro' : 11 ,
'dez' : 11
}[ month.toLowerCase( ) ];
} ,
/**
* Function that returns the representation the day of the week [PT Only]
*
* @method _wDays
* @param {Number} index Week's day index
* @return {String} The week's day name
* @private
* @static
* @example
* console.log( InkDate._wDays(0) ); // Result: Domingo
*/
_wDays: function(index){
var _d = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];
return _d[index];
},
/**
* Function that returns day of the week in javascript 1 to 7
*
* @method _iWeek
* @param {String} week Week's day name
* @return {Number} The week's day index
* @private
* @static
* @example
* console.log( InkDate._iWeek('quarta') ); // Result: 3
*/
_iWeek: function( week )
{
if ( Number( week ) ) { return +week || 7; }
return {
'segunda' : 1 ,
'seg' : 1 ,
'terça' : 2 ,
'ter' : 2 ,
'quarta' : 3 ,
'qua' : 3 ,
'quinta' : 4 ,
'qui' : 4 ,
'sexta' : 5 ,
'sex' : 5 ,
'sábado' : 6 ,
'sáb' : 6 ,
'domingo' : 7 ,
'dom' : 7
}[ week.toLowerCase( ) ];
},
/**
* Function that returns the number of days of a given month (m) on a given year (y)
*
* @method _daysInMonth
* @param {Number} _m Month
* @param {Number} _y Year
* @return {Number} Number of days of a give month on a given year
* @private
* @static
* @example
* console.log( InkDate._daysInMonth(2,2013) ); // Result: 28
*/
_daysInMonth: function(_m,_y){
var nDays;
if(_m===1 || _m===3 || _m===5 || _m===7 || _m===8 || _m===10 || _m===12)
{
nDays= 31;
}
else if ( _m===4 || _m===6 || _m===9 || _m===11)
{
nDays = 30;
}
else
{
if((_y%400===0) || (_y%4===0 && _y%100!==0))
{
nDays = 29;
}
else
{
nDays = 28;
}
}
return nDays;
},
/**
* Function that works exactly as php date() function
* Works like PHP 5.2.2 <a href="http://php.net/manual/en/function.date.php" target="_blank">PHP Date function</a>
*
* @method get
* @param {String} format - as the string in which the date it will be formatted - mandatory
* @param {Date} [_date] - the date to format. If undefined it will do it on now() date. Can receive unix timestamp or a date object
* @return {String} Formatted date
* @public
* @static
* @example
* <script>
* Ink.requireModules( ['Ink.Util.Date_1'], function( InkDate ){
* console.log( InkDate.get('Y-m-d') ); // Result (at the time of writing): 2013-05-07
* });
* </script>
*/
get: function(format, _date){
/*jshint maxcomplexity:50 */
if(typeof(format) === 'undefined' || format === ''){
format = "Y-m-d";
}
var iFormat = format.split("");
var result = new Array(iFormat.length);
var escapeChar = "\\";
var jsDate;
if (typeof(_date) === 'undefined'){
jsDate = new Date();
} else if (typeof(_date)==='number'){
jsDate = new Date(_date*1000);
} else {
jsDate = new Date(_date);
}
var jsFirstDay, jsThisDay, jsHour;
/* This switch is presented in the same order as in php date function (PHP 5.2.2) */
for (var i = 0; i < iFormat.length; i++) {
switch(iFormat[i]) {
case escapeChar:
result[i] = iFormat[i+1];
i++;
break;
/* DAY */
case "d": /* Day of the month, 2 digits with leading zeros; ex: 01 to 31 */
var jsDay = jsDate.getDate();
result[i] = (String(jsDay).length > 1) ? jsDay : "0" + jsDay;
break;
case "D": /* A textual representation of a day, three letters; Seg to Dom */
result[i] = this._wDays(jsDate.getDay()).substring(0, 3);
break;
case "j": /* Day of the month without leading zeros; ex: 1 to 31 */
result[i] = jsDate.getDate();
break;
case "l": /* A full textual representation of the day of the week; Domingo to Sabado */
result[i] = this._wDays(jsDate.getDay());
break;
case "N": /* ISO-8601 numeric representation of the day of the week; 1 (Segunda) to 7 (Domingo) */
result[i] = jsDate.getDay() || 7;
break;
case "S": /* English ordinal suffix for the day of the month, 2 characters; st, nd, rd or th. Works well with j */
var temp = jsDate.getDate();
var suffixes = ["st", "nd", "rd"];
var suffix = "";
if (temp >= 11 && temp <= 13) {
result[i] = "th";
} else {
result[i] = (suffix = suffixes[String(temp).substr(-1) - 1]) ? (suffix) : ("th");
}
break;
case "w": /* Numeric representation of the day of the week; 0 (for Sunday) through 6 (for Saturday) */
result[i] = jsDate.getDay();
break;
case "z": /* The day of the year (starting from 0); 0 to 365 */
jsFirstDay = Date.UTC(jsDate.getFullYear(), 0, 0);
jsThisDay = Date.UTC(jsDate.getFullYear(), jsDate.getMonth(), jsDate.getDate());
result[i] = Math.floor((jsThisDay - jsFirstDay) / (1000 * 60 * 60 * 24));
break;
/* WEEK */
case "W": /* ISO-8601 week number of year, weeks starting on Monday; ex: 42 (the 42nd week in the year) */
var jsYearStart = new Date( jsDate.getFullYear( ) , 0 , 1 );
jsFirstDay = jsYearStart.getDay() || 7;
var days = Math.floor( ( jsDate - jsYearStart ) / ( 24 * 60 * 60 * 1000 ) + 1 );
result[ i ] = Math.ceil( ( days - ( 8 - jsFirstDay ) ) / 7 ) + 1;
break;
/* MONTH */
case "F": /* A full textual representation of a month, such as Janeiro or Marco; Janeiro a Dezembro */
result[i] = this._months(jsDate.getMonth());
break;
case "m": /* Numeric representation of a month, with leading zeros; 01 to 12 */
var jsMonth = String(jsDate.getMonth() + 1);
result[i] = (jsMonth.length > 1) ? jsMonth : "0" + jsMonth;
break;
case "M": /* A short textual representation of a month, three letters; Jan a Dez */
result[i] = this._months(jsDate.getMonth()).substring(0,3);
break;
case "n": /* Numeric representation of a month, without leading zeros; 1 a 12 */
result[i] = jsDate.getMonth() + 1;
break;
case "t": /* Number of days in the given month; ex: 28 */
result[i] = this._daysInMonth(jsDate.getMonth()+1,jsDate.getYear());
break;
/* YEAR */
case "L": /* Whether it's a leap year; 1 if it is a leap year, 0 otherwise. */
var jsYear = jsDate.getFullYear();
result[i] = (jsYear % 4) ? false : ( (jsYear % 100) ? true : ( (jsYear % 400) ? false : true ) );
break;
case "o": /* ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. */
throw '"o" not implemented!';
case "Y": /* A full numeric representation of a year, 4 digits; 1999 */
result[i] = jsDate.getFullYear();
break;
case "y": /* A two digit representation of a year; 99 */
result[i] = String(jsDate.getFullYear()).substring(2);
break;
/* TIME */
case "a": /* Lowercase Ante meridiem and Post meridiem; am or pm */
result[i] = (jsDate.getHours() < 12) ? "am" : "pm";
break;
case "A": /* Uppercase Ante meridiem and Post meridiem; AM or PM */
result[i] = (jsDate.getHours < 12) ? "AM" : "PM";
break;
case "B": /* Swatch Internet time; 000 through 999 */
throw '"B" not implemented!';
case "g": /* 12-hour format of an hour without leading zeros; 1 to 12 */
jsHour = jsDate.getHours();
result[i] = (jsHour <= 12) ? jsHour : (jsHour - 12);
break;
case "G": /* 24-hour format of an hour without leading zeros; 1 to 23 */
result[i] = String(jsDate.getHours());
break;
case "h": /* 12-hour format of an hour with leading zeros; 01 to 12 */
jsHour = String(jsDate.getHours());
jsHour = (jsHour <= 12) ? jsHour : (jsHour - 12);
result[i] = (jsHour.length > 1) ? jsHour : "0" + jsHour;
break;
case "H": /* 24-hour format of an hour with leading zeros; 01 to 24 */
jsHour = String(jsDate.getHours());
result[i] = (jsHour.length > 1) ? jsHour : "0" + jsHour;
break;
case "i": /* Minutes with leading zeros; 00 to 59 */
var jsMinute = String(jsDate.getMinutes());
result[i] = (jsMinute.length > 1) ? jsMinute : "0" + jsMinute;
break;
case "s": /* Seconds with leading zeros; 00 to 59; */
var jsSecond = String(jsDate.getSeconds());
result[i] = (jsSecond.length > 1) ? jsSecond : "0" + jsSecond;
break;
case "u": /* Microseconds */
throw '"u" not implemented!';
/* TIMEZONE */
case "e": /* Timezone identifier */
throw '"e" not implemented!';
case "I": /* "1" if Daylight Savings Time, "0" otherwise. Works only on the northern hemisphere */
jsFirstDay = new Date(jsDate.getFullYear(), 0, 1);
result[i] = (jsDate.getTimezoneOffset() !== jsFirstDay.getTimezoneOffset()) ? (1) : (0);
break;
case "O": /* Difference to Greenwich time (GMT) in hours */
var jsMinZone = jsDate.getTimezoneOffset();
var jsMinutes = jsMinZone % 60;
jsHour = String(((jsMinZone - jsMinutes) / 60) * -1);
if (jsHour.charAt(0) !== "-") {
jsHour = "+" + jsHour;
}
jsHour = (jsHour.length === 3) ? (jsHour) : (jsHour.replace(/([+\-])(\d)/, "$1" + 0 + "$2"));
result[i] = jsHour + jsMinutes + "0";
break;
case "P": /* Difference to Greenwich time (GMT) with colon between hours and minutes */
throw '"P" not implemented!';
case "T": /* Timezone abbreviation */
throw '"T" not implemented!';
case "Z": /* Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. */
result[i] = jsDate.getTimezoneOffset() * 60;
break;
/* FULL DATE/TIME */
case "c": /* ISO 8601 date */
throw '"c" not implemented!';
case "r": /* RFC 2822 formatted date */
var jsDayName = this._wDays(jsDate.getDay()).substr(0, 3);
var jsMonthName = this._months(jsDate.getMonth()).substr(0, 3);
result[i] = jsDayName + ", " + jsDate.getDate() + " " + jsMonthName + this.get(" Y H:i:s O",jsDate);
break;
case "U": /* Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) */
result[i] = Math.floor(jsDate.getTime() / 1000);
break;
default:
result[i] = iFormat[i];
}
}
return result.join('');
},
/**
* Functions that works like php date() function but return a date based on the formatted string
* Works like PHP 5.2.2 <a href="http://php.net/manual/en/function.date.php" target="_blank">PHP Date function</a>
*
* @method set
* @param {String} [format] As the string in which the date it will be formatted. By default is 'Y-m-d'
* @param {String} str_date The date formatted - Mandatory.
* @return {Date} Date object based on the formatted date
* @public
* @static
*/
set : function( format , str_date ) {
if ( typeof str_date === 'undefined' ) { return ; }
if ( typeof format === 'undefined' || format === '' ) { format = "Y-m-d"; }
var iFormat = format.split("");
var result = new Array( iFormat.length );
var escapeChar = "\\";
var mList;
var objIndex = {
year : undefined ,
month : undefined ,
day : undefined ,
dayY : undefined ,
dayW : undefined ,
week : undefined ,
hour : undefined ,
hourD : undefined ,
min : undefined ,
sec : undefined ,
msec : undefined ,
ampm : undefined ,
diffM : undefined ,
diffH : undefined ,
date : undefined
};
var matches = 0;
/* This switch is presented in the same order as in php date function (PHP 5.2.2) */
for ( var i = 0; i < iFormat.length; i++) {
switch( iFormat[ i ] ) {
case escapeChar:
result[i] = iFormat[ i + 1 ];
i++;
break;
/* DAY */
case "d": /* Day of the month, 2 digits with leading zeros; ex: 01 to 31 */
result[ i ] = '(\\d{2})';
objIndex.day = { original : i , match : matches++ };
break;
case "j": /* Day of the month without leading zeros; ex: 1 to 31 */
result[ i ] = '(\\d{1,2})';
objIndex.day = { original : i , match : matches++ };
break;
case "D": /* A textual representation of a day, three letters; Seg to Dom */
result[ i ] = '([\\wá]{3})';
objIndex.dayW = { original : i , match : matches++ };
break;
case "l": /* A full textual representation of the day of the week; Domingo to Sabado */
result[i] = '([\\wá]{5,7})';
objIndex.dayW = { original : i , match : matches++ };
break;
case "N": /* ISO-8601 numeric representation of the day of the week; 1 (Segunda) to 7 (Domingo) */
result[ i ] = '(\\d)';
objIndex.dayW = { original : i , match : matches++ };
break;
case "w": /* Numeric representation of the day of the week; 0 (for Sunday) through 6 (for Saturday) */
result[ i ] = '(\\d)';
objIndex.dayW = { original : i , match : matches++ };
break;
case "S": /* English ordinal suffix for the day of the month, 2 characters; st, nd, rd or th. Works well with j */
result[ i ] = '\\w{2}';
break;
case "z": /* The day of the year (starting from 0); 0 to 365 */
result[ i ] = '(\\d{1,3})';
objIndex.dayY = { original : i , match : matches++ };
break;
/* WEEK */
case "W": /* ISO-8601 week number of year, weeks starting on Monday; ex: 42 (the 42nd week in the year) */
result[ i ] = '(\\d{1,2})';
objIndex.week = { original : i , match : matches++ };
break;
/* MONTH */
case "F": /* A full textual representation of a month, such as Janeiro or Marco; Janeiro a Dezembro */
result[ i ] = '([\\wç]{4,9})';
objIndex.month = { original : i , match : matches++ };
break;
case "M": /* A short textual representation of a month, three letters; Jan a Dez */
result[ i ] = '(\\w{3})';
objIndex.month = { original : i , match : matches++ };
break;
case "m": /* Numeric representation of a month, with leading zeros; 01 to 12 */
result[ i ] = '(\\d{2})';
objIndex.month = { original : i , match : matches++ };
break;
case "n": /* Numeric representation of a month, without leading zeros; 1 a 12 */
result[ i ] = '(\\d{1,2})';
objIndex.month = { original : i , match : matches++ };
break;
case "t": /* Number of days in the given month; ex: 28 */
result[ i ] = '\\d{2}';
break;
/* YEAR */
case "L": /* Whether it's a leap year; 1 if it is a leap year, 0 otherwise. */
result[ i ] = '\\w{4,5}';
break;
case "o": /* ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. */
throw '"o" not implemented!';
case "Y": /* A full numeric representation of a year, 4 digits; 1999 */
result[ i ] = '(\\d{4})';
objIndex.year = { original : i , match : matches++ };
break;
case "y": /* A two digit representation of a year; 99 */
result[ i ] = '(\\d{2})';
if ( typeof objIndex.year === 'undefined' || iFormat[ objIndex.year.original ] !== 'Y' ) {
objIndex.year = { original : i , match : matches++ };
}
break;
/* TIME */
case "a": /* Lowercase Ante meridiem and Post meridiem; am or pm */
result[ i ] = '(am|pm)';
objIndex.ampm = { original : i , match : matches++ };
break;
case "A": /* Uppercase Ante meridiem and Post meridiem; AM or PM */
result[ i ] = '(AM|PM)';
objIndex.ampm = { original : i , match : matches++ };
break;
case "B": /* Swatch Internet time; 000 through 999 */
throw '"B" not implemented!';
case "g": /* 12-hour format of an hour without leading zeros; 1 to 12 */
result[ i ] = '(\\d{1,2})';
objIndex.hourD = { original : i , match : matches++ };
break;
case "G": /* 24-hour format of an hour without leading zeros; 1 to 23 */
result[ i ] = '(\\d{1,2})';
objIndex.hour = { original : i , match : matches++ };
break;
case "h": /* 12-hour format of an hour with leading zeros; 01 to 12 */
result[ i ] = '(\\d{2})';
objIndex.hourD = { original : i , match : matches++ };
break;
case "H": /* 24-hour format of an hour with leading zeros; 01 to 24 */
result[ i ] = '(\\d{2})';
objIndex.hour = { original : i , match : matches++ };
break;
case "i": /* Minutes with leading zeros; 00 to 59 */
result[ i ] = '(\\d{2})';
objIndex.min = { original : i , match : matches++ };
break;
case "s": /* Seconds with leading zeros; 00 to 59; */
result[ i ] = '(\\d{2})';
objIndex.sec = { original : i , match : matches++ };
break;
case "u": /* Microseconds */
throw '"u" not implemented!';
/* TIMEZONE */
case "e": /* Timezone identifier */
throw '"e" not implemented!';
case "I": /* "1" if Daylight Savings Time, "0" otherwise. Works only on the northern hemisphere */
result[i] = '\\d';
break;
case "O": /* Difference to Greenwich time (GMT) in hours */
result[ i ] = '([-+]\\d{4})';
objIndex.diffH = { original : i , match : matches++ };
break;
case "P": /* Difference to Greenwich time (GMT) with colon between hours and minutes */
throw '"P" not implemented!';
case "T": /* Timezone abbreviation */
throw '"T" not implemented!';
case "Z": /* Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. */
result[ i ] = '(\\-?\\d{1,5})';
objIndex.diffM = { original : i , match : matches++ };
break;
/* FULL DATE/TIME */
case "c": /* ISO 8601 date */
throw '"c" not implemented!';
case "r": /* RFC 2822 formatted date */
result[ i ] = '([\\wá]{3}, \\d{1,2} \\w{3} \\d{4} \\d{2}:\\d{2}:\\d{2} [+\\-]\\d{4})';
objIndex.date = { original : i , match : matches++ };
break;
case "U": /* Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) */
result[ i ] = '(\\d{1,13})';
objIndex.date = { original : i , match : matches++ };
break;
default:
result[ i ] = iFormat[ i ];
}
}
var pattr = new RegExp( result.join('') );
try {
mList = str_date.match( pattr );
if ( !mList ) { return; }
}
catch ( e ) { return ; }
var _haveDatetime = typeof objIndex.date !== 'undefined';
var _haveYear = typeof objIndex.year !== 'undefined';
var _haveYDay = typeof objIndex.dayY !== 'undefined';
var _haveDay = typeof objIndex.day !== 'undefined';
var _haveMonth = typeof objIndex.month !== 'undefined';
var _haveMonthDay = _haveMonth && _haveDay;
var _haveOnlyDay = !_haveMonth && _haveDay;
var _haveWDay = typeof objIndex.dayW !== 'undefined';
var _haveWeek = typeof objIndex.week !== 'undefined';
var _haveWeekWDay = _haveWeek && _haveWDay;
var _haveOnlyWDay = !_haveWeek && _haveWDay;
var _validDate = _haveYDay || _haveMonthDay || !_haveYear && _haveOnlyDay || _haveWeekWDay || !_haveYear && _haveOnlyWDay;
var _noDate = !_haveYear && !_haveYDay && !_haveDay && !_haveMonth && !_haveWDay && !_haveWeek;
var _haveHour12 = typeof objIndex.hourD !== 'undefined' && typeof objIndex.ampm !== 'undefined';
var _haveHour24 = typeof objIndex.hour !== 'undefined';
var _haveHour = _haveHour12 || _haveHour24;
var _haveMin = typeof objIndex.min !== 'undefined';
var _haveSec = typeof objIndex.sec !== 'undefined';
var _haveMSec = typeof objIndex.msec !== 'undefined';
var _haveMoreM = !_noDate || _haveHour;
var _haveMoreS = _haveMoreM || _haveMin;
var _haveDiffM = typeof objIndex.diffM !== 'undefined';
var _haveDiffH = typeof objIndex.diffH !== 'undefined';
//var _haveGMT = _haveDiffM || _haveDiffH;
var hour;
var min;
if ( _haveDatetime ) {
if ( iFormat[ objIndex.date.original ] === 'U' ) {
return new Date( +mList[ objIndex.date.match + 1 ] * 1000 );
}
var dList = mList[ objIndex.date.match + 1 ].match( /\w{3}, (\d{1,2}) (\w{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+\-]\d{4})/ );
hour = +dList[ 4 ] + ( +dList[ 7 ].slice( 0 , 3 ) );
min = +dList[ 5 ] + ( dList[ 7 ].slice( 0 , 1 ) + dList[ 7 ].slice( 3 ) ) / 100 * 60;
return new Date( dList[ 3 ] , this._iMonth( dList[ 2 ] ) , dList[ 1 ] , hour , min , dList[ 6 ] );
}
var _d = new Date( );
var year;
var month;
var day;
var date;
var sec;
var msec;
var gmt;
if ( !_validDate && !_noDate ) { return ; }
if ( _validDate ) {
if ( _haveYear ) {
var _y = _d.getFullYear( ) - 50 + '';
year = mList[ objIndex.year.match + 1 ];
if ( iFormat[ objIndex.year.original ] === 'y' ) {
year = +_y.slice( 0 , 2 ) + ( year >= ( _y ).slice( 2 ) ? 0 : 1 ) + year;
}
} else {
year = _d.getFullYear();
}
if ( _haveYDay ) {
month = 0;
day = mList[ objIndex.dayY.match + 1 ];
} else if ( _haveDay ) {
if ( _haveMonth ) {
month = this._iMonth( mList[ objIndex.month.match + 1 ] );
} else {
month = _d.getMonth( );
}
day = mList[ objIndex.day.match + 1 ];
} else {
month = 0;
var week;
if ( _haveWeek ) {
week = mList[ objIndex.week.match + 1 ];
} else {
week = this.get( 'W' , _d );
}
day = ( week - 2 ) * 7 + ( 8 - ( ( new Date( year , 0 , 1 ) ).getDay( ) || 7 ) ) + this._iWeek( mList[ objIndex.week.match + 1 ] );
}
if ( month === 0 && day > 31 ) {
var aux = new Date( year , month , day );
month = aux.getMonth( );
day = aux.getDate( );
}
}
else {
year = _d.getFullYear( );
month = _d.getMonth( );
day = _d.getDate( );
}
date = year + '-' + ( month + 1 ) + '-' + day + ' ';
if ( _haveHour12 ) { hour = +mList[ objIndex.hourD.match + 1 ] + ( mList[ objIndex.ampm.match + 1 ] === 'pm' ? 12 : 0 ); }
else if ( _haveHour24 ) { hour = mList[ objIndex.hour.match + 1 ]; }
else if ( _noDate ) { hour = _d.getHours( ); }
else { hour = '00'; }
if ( _haveMin ) { min = mList[ objIndex.min.match + 1 ]; }
else if ( !_haveMoreM ) { min = _d.getMinutes( ); }
else { min = '00'; }
if ( _haveSec ) { sec = mList[ objIndex.sec.match + 1 ]; }
else if ( !_haveMoreS ) { sec = _d.getSeconds( ); }
else { sec = '00'; }
if ( _haveMSec ) { msec = mList[ objIndex.msec.match + 1 ]; }
else { msec = '000'; }
if ( _haveDiffH ) { gmt = mList[ objIndex.diffH.match + 1 ]; }
else if ( _haveDiffM ) { gmt = String( -1 * mList[ objIndex.diffM.match + 1 ] / 60 * 100 ).replace( /^(\d)/ , '+$1' ).replace( /(^[\-+])(\d{3}$)/ , '$10$2' ); }
else { gmt = '+0000'; }
return new Date( date + hour + ':' + min + ':' + sec + '.' + msec + gmt );
}
};
return InkDate;
});
/**
* @module Ink.Util.Cookie_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Util.Cookie', '1', [], function() {
'use strict';
/**
* Utilities for Cookie handling
*
* @class Ink.Util.Cookie
* @version 1
* @static
*/
var Cookie = {
/**
* Gets an object with current page cookies
*
* @method get
* @param {String} name
* @return {String|Object} If the name is specified, it returns the value related to that property. Otherwise it returns the full cookie object
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Cookie_1'], function( InkCookie ){
* var myCookieValue = InkCookie.get('someVarThere');
* console.log( myCookieValue ); // This will output the value of the cookie 'someVarThere', from the cookie object.
* });
*/
get: function(name)
{
var cookie = document.cookie || false;
var _Cookie = {};
if(cookie) {
cookie = cookie.replace(new RegExp("; ", "g"), ';');
var aCookie = cookie.split(';');
var aItem = [];
if(aCookie.length > 0) {
for(var i=0; i < aCookie.length; i++) {
aItem = aCookie[i].split('=');
if(aItem.length === 2) {
_Cookie[aItem[0]] = decodeURIComponent(aItem[1]);
}
aItem = [];
}
}
}
if(name) {
if(typeof(_Cookie[name]) !== 'undefined') {
return _Cookie[name];
} else {
return null;
}
}
return _Cookie;
},
/**
* Sets a cookie
*
* @method set
* @param {String} name Cookie name
* @param {String} value Cookie value
* @param {Number} [expires] Number to add to current Date in seconds
* @param {String} [path] Path to sets cookie (default '/')
* @param {String} [domain] Domain to sets cookie (default current hostname)
* @param {Boolean} [secure] True if wants secure, default 'false'
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Cookie_1'], function( InkCookie ){
* var expireDate = new Date( 2014,00,01, 0,0,0);
* InkCookie.set( 'someVarThere', 'anyValueHere', expireDate.getTime() );
* });
*/
set: function(name, value, expires, path, domain, secure)
{
var sName;
if(!name || value===false || typeof(name) === 'undefined' || typeof(value) === 'undefined') {
return false;
} else {
sName = name+'='+encodeURIComponent(value);
}
var sExpires = false;
var sPath = false;
var sDomain = false;
var sSecure = false;
if(expires && typeof(expires) !== 'undefined' && !isNaN(expires)) {
var oDate = new Date();
var sDate = (parseInt(Number(oDate.valueOf()), 10) + (Number(parseInt(expires, 10)) * 1000));
var nDate = new Date(sDate);
var expiresString = nDate.toGMTString();
var re = new RegExp("([^\\s]+)(\\s\\d\\d)\\s(\\w\\w\\w)\\s(.*)");
expiresString = expiresString.replace(re, "$1$2-$3-$4");
sExpires = 'expires='+expiresString;
} else {
if(typeof(expires) !== 'undefined' && !isNaN(expires) && Number(parseInt(expires, 10))===0) {
sExpires = '';
} else {
sExpires = 'expires=Thu, 01-Jan-2037 00:00:01 GMT';
}
}
if(path && typeof(path) !== 'undefined') {
sPath = 'path='+path;
} else {
sPath = 'path=/';
}
if(domain && typeof(domain) !== 'undefined') {
sDomain = 'domain='+domain;
} else {
var portClean = new RegExp(":(.*)");
sDomain = 'domain='+window.location.host;
sDomain = sDomain.replace(portClean,"");
}
if(secure && typeof(secure) !== 'undefined') {
sSecure = secure;
} else {
sSecure = false;
}
document.cookie = sName+'; '+sExpires+'; '+sPath+'; '+sDomain+'; '+sSecure;
},
/**
* Delete a cookie
*
* @method remove
* @param {String} cookieName Cookie name
* @param {String} [path] Path of the cookie (default '/')
* @param {String} [domain] Domain of the cookie (default current hostname)
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Cookie_1'], function( InkCookie ){
* InkCookie.remove( 'someVarThere' );
* });
*/
remove: function(cookieName, path, domain)
{
//var expiresDate = 'Thu, 01-Jan-1970 00:00:01 GMT';
var sPath = false;
var sDomain = false;
var expiresDate = -999999999;
if(path && typeof(path) !== 'undefined') {
sPath = path;
} else {
sPath = '/';
}
if(domain && typeof(domain) !== 'undefined') {
sDomain = domain;
} else {
sDomain = window.location.host;
}
this.set(cookieName, 'deleted', expiresDate, sPath, sDomain);
}
};
return Cookie;
});
/**
* @module Ink.Util.BinPack_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Util.BinPack', '1', [], function() {
'use strict';
/*jshint boss:true */
// https://github.com/jakesgordon/bin-packing/
/*
Copyright (c) 2011, 2012, 2013 Jake Gordon and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var Packer = function(w, h) {
this.init(w, h);
};
Packer.prototype = {
init: function(w, h) {
this.root = { x: 0, y: 0, w: w, h: h };
},
fit: function(blocks) {
var n, node, block;
for (n = 0; n < blocks.length; ++n) {
block = blocks[n];
if (node = this.findNode(this.root, block.w, block.h)) {
block.fit = this.splitNode(node, block.w, block.h);
}
}
},
findNode: function(root, w, h) {
if (root.used) {
return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);
}
else if ((w <= root.w) && (h <= root.h)) {
return root;
}
else {
return null;
}
},
splitNode: function(node, w, h) {
node.used = true;
node.down = { x: node.x, y: node.y + h, w: node.w, h: node.h - h };
node.right = { x: node.x + w, y: node.y, w: node.w - w, h: h };
return node;
}
};
var GrowingPacker = function() {};
GrowingPacker.prototype = {
fit: function(blocks) {
var n, node, block, len = blocks.length;
var w = len > 0 ? blocks[0].w : 0;
var h = len > 0 ? blocks[0].h : 0;
this.root = { x: 0, y: 0, w: w, h: h };
for (n = 0; n < len ; n++) {
block = blocks[n];
if (node = this.findNode(this.root, block.w, block.h)) {
block.fit = this.splitNode(node, block.w, block.h);
}
else {
block.fit = this.growNode(block.w, block.h);
}
}
},
findNode: function(root, w, h) {
if (root.used) {
return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);
}
else if ((w <= root.w) && (h <= root.h)) {
return root;
}
else {
return null;
}
},
splitNode: function(node, w, h) {
node.used = true;
node.down = { x: node.x, y: node.y + h, w: node.w, h: node.h - h };
node.right = { x: node.x + w, y: node.y, w: node.w - w, h: h };
return node;
},
growNode: function(w, h) {
var canGrowDown = (w <= this.root.w);
var canGrowRight = (h <= this.root.h);
var shouldGrowRight = canGrowRight && (this.root.h >= (this.root.w + w)); // attempt to keep square-ish by growing right when height is much greater than width
var shouldGrowDown = canGrowDown && (this.root.w >= (this.root.h + h)); // attempt to keep square-ish by growing down when width is much greater than height
if (shouldGrowRight) {
return this.growRight(w, h);
}
else if (shouldGrowDown) {
return this.growDown(w, h);
}
else if (canGrowRight) {
return this.growRight(w, h);
}
else if (canGrowDown) {
return this.growDown(w, h);
}
else {
return null; // need to ensure sensible root starting size to avoid this happening
}
},
growRight: function(w, h) {
this.root = {
used: true,
x: 0,
y: 0,
w: this.root.w + w,
h: this.root.h,
down: this.root,
right: { x: this.root.w, y: 0, w: w, h: this.root.h }
};
var node;
if (node = this.findNode(this.root, w, h)) {
return this.splitNode(node, w, h);
}
else {
return null;
}
},
growDown: function(w, h) {
this.root = {
used: true,
x: 0,
y: 0,
w: this.root.w,
h: this.root.h + h,
down: { x: 0, y: this.root.h, w: this.root.w, h: h },
right: this.root
};
var node;
if (node = this.findNode(this.root, w, h)) {
return this.splitNode(node, w, h);
}
else {
return null;
}
}
};
var sorts = {
random: function() { return Math.random() - 0.5; },
w: function(a, b) { return b.w - a.w; },
h: function(a, b) { return b.h - a.h; },
a: function(a, b) { return b.area - a.area; },
max: function(a, b) { return Math.max(b.w, b.h) - Math.max(a.w, a.h); },
min: function(a, b) { return Math.min(b.w, b.h) - Math.min(a.w, a.h); },
height: function(a, b) { return sorts.msort(a, b, ['h', 'w']); },
width: function(a, b) { return sorts.msort(a, b, ['w', 'h']); },
area: function(a, b) { return sorts.msort(a, b, ['a', 'h', 'w']); },
maxside: function(a, b) { return sorts.msort(a, b, ['max', 'min', 'h', 'w']); },
msort: function(a, b, criteria) { /* sort by multiple criteria */
var diff, n;
for (n = 0; n < criteria.length; ++n) {
diff = sorts[ criteria[n] ](a, b);
if (diff !== 0) {
return diff;
}
}
return 0;
}
};
// end of Jake's code
// aux, used to display blocks in unfitted property
var toString = function() {
return [this.w, ' x ', this.h].join('');
};
/**
* Binary Packing algorithm implementation
*
* Based on the work of Jake Gordon
*
* see https://github.com/jakesgordon/bin-packing/
*
* @class Ink.Util.BinPack
* @version 1
* @static
*/
var BinPack = {
/**
* @method binPack
* @param {Object} o options
* @param {Object[]} o.blocks array of items with w and h integer attributes.
* @param {Number[2]} [o.dimensions] if passed, container has fixed dimensions
* @param {String} [o.sorter] sorter function. one of: random, height, width, area, maxside
* @return {Object}
* * {Number[2]} dimensions - resulted container size,
* * {Number} filled - filled ratio,
* * {Object[]} fitted,
* * {Object[]} unfitted,
* * {Object[]} blocks
* @static
*/
binPack: function(o) {
var i, f, bl;
// calculate area if not there already
for (i = 0, f = o.blocks.length; i < f; ++i) {
bl = o.blocks[i];
if (! ('area' in bl) ) {
bl.area = bl.w * bl.h;
}
}
// apply algorithm
var packer = o.dimensions ? new Packer(o.dimensions[0], o.dimensions[1]) : new GrowingPacker();
if (!o.sorter) { o.sorter = 'maxside'; }
o.blocks.sort( sorts[ o.sorter ] );
packer.fit(o.blocks);
var dims2 = [packer.root.w, packer.root.h];
// layout is done here, generating report data...
var fitted = [];
var unfitted = [];
for (i = 0, f = o.blocks.length; i < f; ++i) {
bl = o.blocks[i];
if (bl.fit) {
fitted.push(bl);
}
else {
bl.toString = toString; // TO AID SERIALIZATION
unfitted.push(bl);
}
}
var area = dims2[0] * dims2[1];
var fit = 0;
for (i = 0, f = fitted.length; i < f; ++i) {
bl = fitted[i];
fit += bl.area;
}
return {
dimensions: dims2,
filled: fit / area,
blocks: o.blocks,
fitted: fitted,
unfitted: unfitted
};
}
};
return BinPack;
});
/**
* @module Ink.Util.Array_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Util.Array', '1', [], function() {
'use strict';
var arrayProto = Array.prototype;
/**
* Utility functions to use with Arrays
*
* @class Ink.Util.Array
* @version 1
* @static
*/
var InkArray = {
/**
* Checks if value exists in array
*
* @method inArray
* @param {Mixed} value
* @param {Array} arr
* @return {Boolean} True if value exists in the array
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray = [ 'value1', 'value2', 'value3' ];
* if( InkArray.inArray( 'value2', testArray ) === true ){
* console.log( "Yep it's in the array." );
* } else {
* console.log( "No it's NOT in the array." );
* }
* });
*/
inArray: function(value, arr) {
if (typeof arr === 'object') {
for (var i = 0, f = arr.length; i < f; ++i) {
if (arr[i] === value) {
return true;
}
}
}
return false;
},
/**
* Sorts an array of object by an object property
*
* @method sortMulti
* @param {Array} arr array of objects to sort
* @param {String} key property to sort by
* @return {Array|Boolean} False if it's not an array, returns a sorted array if it's an array.
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray = [
* { 'myKey': 'value1' },
* { 'myKey': 'value2' },
* { 'myKey': 'value3' }
* ];
*
* InkArray.sortMulti( testArray, 'myKey' );
* });
*/
sortMulti: function(arr, key) {
if (typeof arr === 'undefined' || arr.constructor !== Array) { return false; }
if (typeof key !== 'string') { return arr.sort(); }
if (arr.length > 0) {
if (typeof(arr[0][key]) === 'undefined') { return false; }
arr.sort(function(a, b){
var x = a[key];
var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
return arr;
},
/**
* Returns the associated key of an array value
*
* @method keyValue
* @param {String} value Value to search for
* @param {Array} arr Array where the search will run
* @param {Boolean} [first] Flag that determines if the search stops at first occurrence. It also returns an index number instead of an array of indexes.
* @return {Boolean|Number|Array} False if not exists | number if exists and 3rd input param is true | array if exists and 3rd input param is not set or it is !== true
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray = [ 'value1', 'value2', 'value3', 'value2' ];
* console.log( InkArray.keyValue( 'value2', testArray, true ) ); // Result: 1
* console.log( InkArray.keyValue( 'value2', testArray ) ); // Result: [1, 3]
* });
*/
keyValue: function(value, arr, first) {
if (typeof value !== 'undefined' && typeof arr === 'object' && this.inArray(value, arr)) {
var aKeys = [];
for (var i = 0, f = arr.length; i < f; ++i) {
if (arr[i] === value) {
if (typeof first !== 'undefined' && first === true) {
return i;
} else {
aKeys.push(i);
}
}
}
return aKeys;
}
return false;
},
/**
* Returns the array shuffled, false if the param is not an array
*
* @method shuffle
* @param {Array} arr Array to shuffle
* @return {Boolean|Number|Array} False if not an array | Array shuffled
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray = [ 'value1', 'value2', 'value3', 'value2' ];
* console.log( InkArray.shuffle( testArray ) ); // Result example: [ 'value3', 'value2', 'value2', 'value1' ]
* });
*/
shuffle: function(arr) {
if (typeof(arr) !== 'undefined' && arr.constructor !== Array) { return false; }
var total = arr.length,
tmp1 = false,
rnd = false;
while (total--) {
rnd = Math.floor(Math.random() * (total + 1));
tmp1 = arr[total];
arr[total] = arr[rnd];
arr[rnd] = tmp1;
}
return arr;
},
/**
* Runs a function through each of the elements of an array
*
* @method forEach
* @param {Array} arr Array to be cycled/iterated
* @param {Function} cb The function receives as arguments the value, index and array.
* @return {Array} Array iterated.
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray = [ 'value1', 'value2', 'value3', 'value2' ];
* InkArray.forEach( testArray, function( value, index, arr ){
* console.log( 'The value is: ' + value + ' | The index is: ' + index );
* });
* });
*/
forEach: function(array, callback, context) {
if (arrayProto.forEach) {
return arrayProto.forEach.call(array, callback, context);
}
for (var i = 0, len = array.length >>> 0; i < len; i++) {
callback.call(context, array[i], i, array);
}
},
/**
* Alias for backwards compatibility. See forEach
*
* @method forEach
*/
each: function () {
InkArray.forEach.apply(InkArray, [].slice.call(arguments));
},
/**
* Run a `map` function for each item in the array. The function will receive each item as argument and its return value will change the corresponding array item.
* @method map
* @param {Array} array The array to map over
* @param {Function} map The map function. Will take `(item, index, array)` and `this` will be the `context` argument.
* @param {Object} [context] Object to be `this` in the map function.
*
* @example
* InkArray.map([1, 2, 3, 4], function (item) {
* return item + 1;
* }); // -> [2, 3, 4, 5]
*/
map: function (array, callback, context) {
if (arrayProto.map) {
return arrayProto.map.call(array, callback, context);
}
var mapped = new Array(len);
for (var i = 0, len = array.length >>> 0; i < len; i++) {
mapped[i] = callback.call(context, array[i], i, array);
}
return mapped;
},
/**
* Run a test function through all the input array. Items which pass the test function (for which the test function returned `true`) are kept in the array. Other items are removed.
* @param {Array} array
* @param {Function} test A test function taking `(item, index, array)`
* @param {Object} [context] Object to be `this` in the test function.
* @return filtered array
*
* @example
* InkArray.filter([1, 2, 3, 4, 5], function (val) {
* return val > 2;
* }) // -> [3, 4, 5]
*/
filter: function (array, test, context) {
if (arrayProto.filter) {
return arrayProto.filter.call(array, test, context);
}
var filtered = [],
val = null;
for (var i = 0, len = array.length; i < len; i++) {
val = array[i]; // it might be mutated
if (test.call(context, val, i, array)) {
filtered.push(val);
}
}
return filtered;
},
/**
* Runs a callback function, which should return true or false.
* If one of the 'runs' returns true, it will return. Otherwise if none returns true, it will return false.
* See more at: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some (MDN)
*
* @method some
* @param {Array} arr The array you walk to iterate through
* @param {Function} cb The callback that will be called on the array's elements. It receives the value, the index and the array as arguments.
* @param {Object} Context object of the callback function
* @return {Boolean} True if the callback returns true at any point, false otherwise
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray1 = [ 10, 20, 50, 100, 30 ];
* var testArray2 = [ 1, 2, 3, 4, 5 ];
*
* function myTestFunction( value, index, arr ){
* if( value > 90 ){
* return true;
* }
* return false;
* }
* console.log( InkArray.some( testArray1, myTestFunction, null ) ); // Result: true
* console.log( InkArray.some( testArray2, myTestFunction, null ) ); // Result: false
* });
*/
some: function(arr, cb, context){
if (arr === null){
throw new TypeError('First argument is invalid.');
}
var t = Object(arr);
var len = t.length >>> 0;
if (typeof cb !== "function"){ throw new TypeError('Second argument must be a function.'); }
for (var i = 0; i < len; i++) {
if (i in t && cb.call(context, t[i], i, t)){ return true; }
}
return false;
},
/**
* Returns an array containing every item that is shared between the two given arrays
*
* @method intersect
* @param {Array} arr Array1 to be intersected with Array2
* @param {Array} arr Array2 to be intersected with Array1
* @return {Array} Empty array if one of the arrays is false (or do not intersect) | Array with the intersected values
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray1 = [ 'value1', 'value2', 'value3' ];
* var testArray2 = [ 'value2', 'value3', 'value4', 'value5', 'value6' ];
* console.log( InkArray.intersect( testArray1,testArray2 ) ); // Result: [ 'value2', 'value3' ]
* });
*/
intersect: function(arr1, arr2) {
if (!arr1 || !arr2 || arr1 instanceof Array === false || arr2 instanceof Array === false) {
return [];
}
var shared = [];
for (var i = 0, I = arr1.length; i<I; ++i) {
for (var j = 0, J = arr2.length; j < J; ++j) {
if (arr1[i] === arr2[j]) {
shared.push(arr1[i]);
}
}
}
return shared;
},
/**
* Convert lists type to type array
*
* @method convert
* @param {Array} arr Array to be converted
* @return {Array} Array resulting of the conversion
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray = [ 'value1', 'value2' ];
* testArray.myMethod = function(){
* console.log('stuff');
* }
*
* console.log( InkArray.convert( testArray ) ); // Result: [ 'value1', 'value2' ]
* });
*/
convert: function(arr) {
return arrayProto.slice.call(arr || [], 0);
},
/**
* Insert value into the array on specified idx
*
* @method insert
* @param {Array} arr Array where the value will be inserted
* @param {Number} idx Index of the array where the value should be inserted
* @param {Mixed} value Value to be inserted
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray = [ 'value1', 'value2' ];
* console.log( InkArray.insert( testArray, 1, 'value3' ) ); // Result: [ 'value1', 'value3', 'value2' ]
* });
*/
insert: function(arr, idx, value) {
arr.splice(idx, 0, value);
},
/**
* Remove a range of values from the array
*
* @method remove
* @param {Array} arr Array where the value will be inserted
* @param {Number} from Index of the array where the removal will start removing.
* @param {Number} rLen Number of items to be removed from the index onwards.
* @return {Array} An array with the remaining values
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){
* var testArray = [ 'value1', 'value2', 'value3', 'value4', 'value5' ];
* console.log( InkArray.remove( testArray, 1, 3 ) ); // Result: [ 'value1', 'value4', 'value5' ]
* });
*/
remove: function(arr, from, rLen){
var output = [];
for(var i = 0, iLen = arr.length; i < iLen; i++){
if(i >= from && i < from + rLen){
continue;
}
output.push(arr[i]);
}
return output;
}
};
return InkArray;
});
/**
* @module Ink.Util.Validator_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.Util.Validator', '1', [], function() {
'use strict';
/**
* Set of functions to provide validation
*
* @class Ink.Util.Validator
* @version 1
* @static
*/
var Validator = {
/**
* List of country codes avaible for isPhone function
*
* @property _countryCodes
* @type {Array}
* @private
* @static
* @readOnly
*/
_countryCodes : [
'AO',
'CV',
'MZ',
'PT'
],
/**
* International number for portugal
*
* @property _internacionalPT
* @type {Number}
* @private
* @static
* @readOnly
*
*/
_internacionalPT: 351,
/**
* List of all portuguese number prefixes
*
* @property _indicativosPT
* @type {Object}
* @private
* @static
* @readOnly
*
*/
_indicativosPT: {
21: 'lisboa',
22: 'porto',
231: 'mealhada',
232: 'viseu',
233: 'figueira da foz',
234: 'aveiro',
235: 'arganil',
236: 'pombal',
238: 'seia',
239: 'coimbra',
241: 'abrantes',
242: 'ponte de sôr',
243: 'santarém',
244: 'leiria',
245: 'portalegre',
249: 'torres novas',
251: 'valença',
252: 'vila nova de famalicão',
253: 'braga',
254: 'peso da régua',
255: 'penafiel',
256: 'são joão da madeira',
258: 'viana do castelo',
259: 'vila real',
261: 'torres vedras',
262: 'caldas da raínha',
263: 'vila franca de xira',
265: 'setúbal',
266: 'évora',
268: 'estremoz',
269: 'santiago do cacém',
271: 'guarda',
272: 'castelo branco',
273: 'bragança',
274: 'proença-a-nova',
275: 'covilhã',
276: 'chaves',
277: 'idanha-a-nova',
278: 'mirandela',
279: 'moncorvo',
281: 'tavira',
282: 'portimão',
283: 'odemira',
284: 'beja',
285: 'moura',
286: 'castro verde',
289: 'faro',
291: 'funchal, porto santo',
292: 'corvo, faial, flores, horta, pico',
295: 'angra do heroísmo, graciosa, são jorge, terceira',
296: 'ponta delgada, são miguel, santa maria',
91 : 'rede móvel 91 (Vodafone / Yorn)',
93 : 'rede móvel 93 (Optimus)',
96 : 'rede móvel 96 (TMN)',
92 : 'rede móvel 92 (TODOS)',
//925 : 'rede móvel 925 (TMN 925)',
//926 : 'rede móvel 926 (TMN 926)',
//927 : 'rede móvel 927 (TMN 927)',
//922 : 'rede móvel 922 (Phone-ix)',
707: 'número único',
760: 'número único',
800: 'número grátis',
808: 'chamada local',
30: 'voip'
},
/**
* International number for Cabo Verde
*
* @property _internacionalCV
* @type {Number}
* @private
* @static
* @readOnly
*/
_internacionalCV: 238,
/**
* List of all Cabo Verde number prefixes
*
* @property _indicativosCV
* @type {Object}
* @private
* @static
* @readOnly
*/
_indicativosCV: {
2: 'fixo',
91: 'móvel 91',
95: 'móvel 95',
97: 'móvel 97',
98: 'móvel 98',
99: 'móvel 99'
},
/**
* International number for angola
*
* @property _internacionalAO
* @type {Number}
* @private
* @static
* @readOnly
*/
_internacionalAO: 244,
/**
* List of all Angola number prefixes
*
* @property _indicativosAO
* @type {Object}
* @private
* @static
* @readOnly
*/
_indicativosAO: {
2: 'fixo',
91: 'móvel 91',
92: 'móvel 92'
},
/**
* International number for mozambique
*
* @property _internacionalMZ
* @type {Number}
* @private
* @static
* @readOnly
*/
_internacionalMZ: 258,
/**
* List of all Mozambique number prefixes
*
* @property _indicativosMZ
* @type {Object}
* @private
* @static
* @readOnly
*/
_indicativosMZ: {
2: 'fixo',
82: 'móvel 82',
84: 'móvel 84'
},
/**
* International number for Timor
*
* @property _internacionalTL
* @type {Number}
* @private
* @static
* @readOnly
*/
_internacionalTL: 670,
/**
* List of all Timor number prefixes
*
* @property _indicativosTL
* @type {Object}
* @private
* @static
* @readOnly
*/
_indicativosTL: {
3: 'fixo',
7: 'móvel 7'
},
/**
* Regular expression groups for several groups of characters
*
* http://en.wikipedia.org/wiki/C0_Controls_and_Basic_Latin
* http://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane
* http://en.wikipedia.org/wiki/ISO_8859-1
*
* @property _characterGroups
* @type {Object}
* @private
* @static
* @readOnly
*/
_characterGroups: {
numbers: ['0-9'],
asciiAlpha: ['a-zA-Z'],
latin1Alpha: ['a-zA-Z', '\u00C0-\u00FF'],
unicodeAlpha: ['a-zA-Z', '\u00C0-\u00FF', '\u0100-\u1FFF', '\u2C00-\uD7FF'],
/* whitespace characters */
space: [' '],
dash: ['-'],
underscore: ['_'],
nicknamePunctuation: ['_.-'],
singleLineWhitespace: ['\t '],
newline: ['\n'],
whitespace: ['\t\n\u000B\f\r\u00A0 '],
asciiPunctuation: ['\u0021-\u002F', '\u003A-\u0040', '\u005B-\u0060', '\u007B-\u007E'],
latin1Punctuation: ['\u0021-\u002F', '\u003A-\u0040', '\u005B-\u0060', '\u007B-\u007E', '\u00A1-\u00BF', '\u00D7', '\u00F7'],
unicodePunctuation: ['\u0021-\u002F', '\u003A-\u0040', '\u005B-\u0060', '\u007B-\u007E', '\u00A1-\u00BF', '\u00D7', '\u00F7', '\u2000-\u206F', '\u2E00-\u2E7F', '\u3000-\u303F'],
},
/**
* Create a regular expression for several character groups.
*
* @method createRegExp
*
* @param Groups... {Object}
* Groups to build regular expressions for. Possible keys are:
*
* - **numbers**: 0-9
* - **asciiAlpha**: a-z, A-Z
* - **latin1Alpha**: asciiAlpha, plus printable characters in latin-1
* - **unicodeAlpha**: unicode alphanumeric characters.
* - **space**: ' ', the space character.
* - **dash**: dash character.
* - **underscore**: underscore character.
* - **nicknamePunctuation**: dash, dot, underscore
* - **singleLineWhitespace**: space and tab (whitespace which only spans one line).
* - **newline**: newline character ('\n')
* - **whitespace**: whitespace characters in the ASCII character set.
* - **asciiPunctuation**: punctuation characters in the ASCII character set.
* - **latin1Punctuation**: punctuation characters in latin-1.
* - **unicodePunctuation**: punctuation characters in unicode.
*
*/
createRegExp: function (groups) {
var re = '^[';
for (var key in groups) if (groups.hasOwnProperty(key)) {
if (!(key in Validator._characterGroups)) {
throw new Error('group ' + key + ' is not a valid character group');
} else if (groups[key]) {
re += Validator._characterGroups[key].join('');
}
}
return new RegExp(re + ']*?$');
},
/**
* Checks if a field has the required groups. Takes an options object for further configuration.
*
* @method checkCharacterGroups
* @param {String} s The validation string
* @param {Object} [groups={}] What groups are included.
* @param [options.*] See createRegexp
*/
checkCharacterGroups: function (s, groups) {
return Validator.createRegExp(groups).test(s);
},
/**
* Checks whether a field contains unicode printable characters. Takes an
* options object for further configuration
*
* @method unicode
* @param {String} s The validation string
* @param {Object} [options={}] Optional configuration object
* @param [options.*] See createRegexp
*/
unicode: function (s, options) {
return Validator.checkCharacterGroups(s, Ink.extendObj({
unicodeAlpha: true}, options));
},
/**
* Checks that a field only contains only latin-1 alphanumeric
* characters. Takes options for allowing singleline whitespace,
* cross-line whitespace and punctuation.
*
* @method latin1
*
* @param {String} s The validation string
* @param {Object} [options={}] Optional configuration object
* @param [options.*] See createRegexp
*/
latin1: function (s, options) {
return Validator.checkCharacterGroups(s, Ink.extendObj({
latin1Alpha: true}, options));
},
/**
* Checks that a field only contains only ASCII alphanumeric
* characters. Takes options for allowing singleline whitespace,
* cross-line whitespace and punctuation.
*
* @method ascii
*
* @param {String} s The validation string
* @param {Object} [options={}] Optional configuration object
* @param [options.*] See createRegexp
*/
ascii: function (s, options) {
return Validator.checkCharacterGroups(s, Ink.extendObj({
asciiAlpha: true}, options));
},
/**
* Checks that the number is a valid number
*
* @method number
* @param {String} numb The number
* @param {Object} [options] Further options
* @param [options.decimalSep='.'] Allow decimal separator.
* @param [options.thousandSep=","] Strip this character from the number.
* @param [options.negative=false] Allow negative numbers.
* @param [options.decimalPlaces=0] Maximum number of decimal places. `0` means integer number.
* @param [options.max=null] Maximum number
* @param [options.min=null] Minimum number
* @param [options.returnNumber=false] When this option is true, return the number itself when the value is valid.
*/
number: function (numb, inOptions) {
numb = numb + '';
var options = Ink.extendObj({
decimalSep: '.',
thousandSep: '',
negative: true,
decimalPlaces: null,
maxDigits: null,
max: null,
min: null,
returnNumber: false
}, inOptions || {});
// smart recursion thing sets up aliases for options.
if (options.thousandSep) {
numb = numb.replace(new RegExp('\\' + options.thousandSep, 'g'), '');
options.thousandSep = '';
return Validator.number(numb, options);
}
if (options.negative === false) {
options.min = 0;
options.negative = true;
return Validator.number(numb, options);
}
if (options.decimalSep !== '.') {
numb = numb.replace(new RegExp('\\' + options.decimalSep, 'g'), '.');
}
if (!/^(-)?(\d+)?(\.\d+)?$/.test(numb) || numb === '') {
return false; // forbidden character found
}
var split;
if (options.decimalSep && numb.indexOf(options.decimalSep) !== -1) {
split = numb.split(options.decimalSep);
if (options.decimalPlaces !== null &&
split[1].length > options.decimalPlaces) {
return false;
}
} else {
split = ['' + numb, ''];
}
if (options.maxDigits!== null) {
if (split[0].replace(/-/g, '').length > options.maxDigits) {
return split
}
}
// Now look at the actual float
var ret = parseFloat(numb);
if (options.maxExcl !== null && ret >= options.maxExcl ||
options.minExcl !== null && ret <= options.minExcl) {
return false;
}
if (options.max !== null && ret > options.max ||
options.min !== null && ret < options.min) {
return false;
}
if (options.returnNumber) {
return ret;
} else {
return true;
}
},
/**
* Checks if a year is Leap "Bissexto"
*
* @method _isLeapYear
* @param {Number} year Year to be checked
* @return {Boolean} True if it is a leap year.
* @private
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator._isLeapYear( 2004 ) ); // Result: true
* console.log( InkValidator._isLeapYear( 2006 ) ); // Result: false
* });
*/
_isLeapYear: function(year){
var yearRegExp = /^\d{4}$/;
if(yearRegExp.test(year)){
return ((year%4) ? false: ((year%100) ? true : ((year%400)? false : true)) );
}
return false;
},
/**
* Object with the date formats available for validation
*
* @property _dateParsers
* @type {Object}
* @private
* @static
* @readOnly
*/
_dateParsers: {
'yyyy-mm-dd': {day:5, month:3, year:1, sep: '-', parser: /^(\d{4})(\-)(\d{1,2})(\-)(\d{1,2})$/},
'yyyy/mm/dd': {day:5, month:3, year:1, sep: '/', parser: /^(\d{4})(\/)(\d{1,2})(\/)(\d{1,2})$/},
'yy-mm-dd': {day:5, month:3, year:1, sep: '-', parser: /^(\d{2})(\-)(\d{1,2})(\-)(\d{1,2})$/},
'yy/mm/dd': {day:5, month:3, year:1, sep: '/', parser: /^(\d{2})(\/)(\d{1,2})(\/)(\d{1,2})$/},
'dd-mm-yyyy': {day:1, month:3, year:5, sep: '-', parser: /^(\d{1,2})(\-)(\d{1,2})(\-)(\d{4})$/},
'dd/mm/yyyy': {day:1, month:3, year:5, sep: '/', parser: /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/},
'dd-mm-yy': {day:1, month:3, year:5, sep: '-', parser: /^(\d{1,2})(\-)(\d{1,2})(\-)(\d{2})$/},
'dd/mm/yy': {day:1, month:3, year:5, sep: '/', parser: /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{2})$/}
},
/**
* Calculates the number of days in a given month of a given year
*
* @method _daysInMonth
* @param {Number} _m - month (1 to 12)
* @param {Number} _y - year
* @return {Number} Returns the number of days in a given month of a given year
* @private
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator._daysInMonth( 2, 2004 ) ); // Result: 29
* console.log( InkValidator._daysInMonth( 2, 2006 ) ); // Result: 28
* });
*/
_daysInMonth: function(_m,_y){
var nDays=0;
if(_m===1 || _m===3 || _m===5 || _m===7 || _m===8 || _m===10 || _m===12)
{
nDays= 31;
}
else if ( _m===4 || _m===6 || _m===9 || _m===11)
{
nDays = 30;
}
else
{
if((_y%400===0) || (_y%4===0 && _y%100!==0))
{
nDays = 29;
}
else
{
nDays = 28;
}
}
return nDays;
},
/**
* Checks if a date is valid
*
* @method _isValidDate
* @param {Number} year
* @param {Number} month
* @param {Number} day
* @return {Boolean} True if it's a valid date
* @private
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator._isValidDate( 2004, 2, 29 ) ); // Result: true
* console.log( InkValidator._isValidDate( 2006, 2, 29 ) ); // Result: false
* });
*/
_isValidDate: function(year, month, day){
var yearRegExp = /^\d{4}$/;
var validOneOrTwo = /^\d{1,2}$/;
if(yearRegExp.test(year) && validOneOrTwo.test(month) && validOneOrTwo.test(day)){
if(month>=1 && month<=12 && day>=1 && this._daysInMonth(month,year)>=day){
return true;
}
}
return false;
},
/**
* Checks if a email is valid
*
* @method mail
* @param {String} email
* @return {Boolean} True if it's a valid e-mail
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.email( 'agfsdfgfdsgdsf' ) ); // Result: false
* console.log( InkValidator.email( 'inkdev\u0040sapo.pt' ) ); // Result: true (where \u0040 is at sign)
* });
*/
email: function(email)
{
var emailValido = new RegExp("^[_a-z0-9-]+((\\.|\\+)[_a-z0-9-]+)*@([\\w]*-?[\\w]*\\.)+[a-z]{2,4}$", "i");
if(!emailValido.test(email)) {
return false;
} else {
return true;
}
},
/**
* Deprecated. Alias for email(). Use it instead.
*
* @method mail
* @public
* @static
*/
mail: function (mail) { return Validator.email(mail); },
/**
* Checks if a url is valid
*
* @method url
* @param {String} url URL to be checked
* @param {Boolean} [full] If true, validates a full URL (one that should start with 'http')
* @return {Boolean} True if the given URL is valid
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.url( 'www.sapo.pt' ) ); // Result: true
* console.log( InkValidator.url( 'http://www.sapo.pt', true ) ); // Result: true
* console.log( InkValidator.url( 'meh' ) ); // Result: false
* });
*/
url: function(url, full)
{
if(typeof full === "undefined" || full === false) {
var reHTTP = new RegExp("(^(http\\:\\/\\/|https\\:\\/\\/)(.+))", "i");
if(reHTTP.test(url) === false) {
url = 'http://'+url;
}
}
var reUrl = new RegExp("^(http:\\/\\/|https:\\/\\/)([\\w]*(-?[\\w]*)*\\.)+[a-z]{2,4}", "i");
if(reUrl.test(url) === false) {
return false;
} else {
return true;
}
},
/**
* Checks if a phone is valid in Portugal
*
* @method isPTPhone
* @param {Number} phone Phone number to be checked
* @return {Boolean} True if it's a valid Portuguese Phone
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.isPTPhone( '213919264' ) ); // Result: true
* console.log( InkValidator.isPTPhone( '00351213919264' ) ); // Result: true
* console.log( InkValidator.isPTPhone( '+351213919264' ) ); // Result: true
* console.log( InkValidator.isPTPhone( '1' ) ); // Result: false
* });
*/
isPTPhone: function(phone)
{
phone = phone.toString();
var aInd = [];
for(var i in this._indicativosPT) {
if(typeof(this._indicativosPT[i]) === 'string') {
aInd.push(i);
}
}
var strInd = aInd.join('|');
var re351 = /^(00351|\+351)/;
if(re351.test(phone)) {
phone = phone.replace(re351, "");
}
var reSpecialChars = /(\s|\-|\.)+/g;
phone = phone.replace(reSpecialChars, '');
//var reInt = new RegExp("\\d", "i");
var reInt = /[\d]{9}/i;
if(phone.length === 9 && reInt.test(phone)) {
var reValid = new RegExp("^("+strInd+")");
if(reValid.test(phone)) {
return true;
}
}
return false;
},
/**
* Alias function for isPTPhone
*
* @method isPortuguesePhone
* @param {Number} phone Phone number to be checked
* @return {Boolean} True if it's a valid Portuguese Phone
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.isPortuguesePhone( '213919264' ) ); // Result: true
* console.log( InkValidator.isPortuguesePhone( '00351213919264' ) ); // Result: true
* console.log( InkValidator.isPortuguesePhone( '+351213919264' ) ); // Result: true
* console.log( InkValidator.isPortuguesePhone( '1' ) ); // Result: false
* });
*/
isPortuguesePhone: function(phone)
{
return this.isPTPhone(phone);
},
/**
* Checks if a phone is valid in Cabo Verde
*
* @method isCVPhone
* @param {Number} phone Phone number to be checked
* @return {Boolean} True if it's a valid Cape Verdean Phone
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.isCVPhone( '2610303' ) ); // Result: true
* console.log( InkValidator.isCVPhone( '002382610303' ) ); // Result: true
* console.log( InkValidator.isCVPhone( '+2382610303' ) ); // Result: true
* console.log( InkValidator.isCVPhone( '1' ) ); // Result: false
* });
*/
isCVPhone: function(phone)
{
phone = phone.toString();
var aInd = [];
for(var i in this._indicativosCV) {
if(typeof(this._indicativosCV[i]) === 'string') {
aInd.push(i);
}
}
var strInd = aInd.join('|');
var re238 = /^(00238|\+238)/;
if(re238.test(phone)) {
phone = phone.replace(re238, "");
}
var reSpecialChars = /(\s|\-|\.)+/g;
phone = phone.replace(reSpecialChars, '');
//var reInt = new RegExp("\\d", "i");
var reInt = /[\d]{7}/i;
if(phone.length === 7 && reInt.test(phone)) {
var reValid = new RegExp("^("+strInd+")");
if(reValid.test(phone)) {
return true;
}
}
return false;
},
/**
* Checks if a phone is valid in Angola
*
* @method isAOPhone
* @param {Number} phone Phone number to be checked
* @return {Boolean} True if it's a valid Angolan Phone
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.isAOPhone( '244222396385' ) ); // Result: true
* console.log( InkValidator.isAOPhone( '00244222396385' ) ); // Result: true
* console.log( InkValidator.isAOPhone( '+244222396385' ) ); // Result: true
* console.log( InkValidator.isAOPhone( '1' ) ); // Result: false
* });
*/
isAOPhone: function(phone)
{
phone = phone.toString();
var aInd = [];
for(var i in this._indicativosAO) {
if(typeof(this._indicativosAO[i]) === 'string') {
aInd.push(i);
}
}
var strInd = aInd.join('|');
var re244 = /^(00244|\+244)/;
if(re244.test(phone)) {
phone = phone.replace(re244, "");
}
var reSpecialChars = /(\s|\-|\.)+/g;
phone = phone.replace(reSpecialChars, '');
//var reInt = new RegExp("\\d", "i");
var reInt = /[\d]{9}/i;
if(phone.length === 9 && reInt.test(phone)) {
var reValid = new RegExp("^("+strInd+")");
if(reValid.test(phone)) {
return true;
}
}
return false;
},
/**
* Checks if a phone is valid in Mozambique
*
* @method isMZPhone
* @param {Number} phone Phone number to be checked
* @return {Boolean} True if it's a valid Mozambican Phone
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.isMZPhone( '21426861' ) ); // Result: true
* console.log( InkValidator.isMZPhone( '0025821426861' ) ); // Result: true
* console.log( InkValidator.isMZPhone( '+25821426861' ) ); // Result: true
* console.log( InkValidator.isMZPhone( '1' ) ); // Result: false
* });
*/
isMZPhone: function(phone)
{
phone = phone.toString();
var aInd = [];
for(var i in this._indicativosMZ) {
if(typeof(this._indicativosMZ[i]) === 'string') {
aInd.push(i);
}
}
var strInd = aInd.join('|');
var re258 = /^(00258|\+258)/;
if(re258.test(phone)) {
phone = phone.replace(re258, "");
}
var reSpecialChars = /(\s|\-|\.)+/g;
phone = phone.replace(reSpecialChars, '');
//var reInt = new RegExp("\\d", "i");
var reInt = /[\d]{8,9}/i;
if((phone.length === 9 || phone.length === 8) && reInt.test(phone)) {
var reValid = new RegExp("^("+strInd+")");
if(reValid.test(phone)) {
if(phone.indexOf('2') === 0 && phone.length === 8) {
return true;
} else if(phone.indexOf('8') === 0 && phone.length === 9) {
return true;
}
}
}
return false;
},
/**
* Checks if a phone is valid in Timor
*
* @method isTLPhone
* @param {Number} phone Phone number to be checked
* @return {Boolean} True if it's a valid phone from Timor-Leste
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.isTLPhone( '6703331234' ) ); // Result: true
* console.log( InkValidator.isTLPhone( '006703331234' ) ); // Result: true
* console.log( InkValidator.isTLPhone( '+6703331234' ) ); // Result: true
* console.log( InkValidator.isTLPhone( '1' ) ); // Result: false
* });
*/
isTLPhone: function(phone)
{
phone = phone.toString();
var aInd = [];
for(var i in this._indicativosTL) {
if(typeof(this._indicativosTL[i]) === 'string') {
aInd.push(i);
}
}
var strInd = aInd.join('|');
var re670 = /^(00670|\+670)/;
if(re670.test(phone)) {
phone = phone.replace(re670, "");
}
var reSpecialChars = /(\s|\-|\.)+/g;
phone = phone.replace(reSpecialChars, '');
//var reInt = new RegExp("\\d", "i");
var reInt = /[\d]{7}/i;
if(phone.length === 7 && reInt.test(phone)) {
var reValid = new RegExp("^("+strInd+")");
if(reValid.test(phone)) {
return true;
}
}
return false;
},
/**
* Validates the function in all country codes available or in the ones set in the second param
*
* @method isPhone
* @param {String} phone number
* @param {optional String|Array} country or array of countries to validate
* @return {Boolean} True if it's a valid phone in any country available
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.isPhone( '6703331234' ) ); // Result: true
* });
*/
isPhone: function(){
var index;
if(arguments.length===0){
return false;
}
var phone = arguments[0];
if(arguments.length>1){
if(arguments[1].constructor === Array){
var func;
for(index=0; index<arguments[1].length; index++ ){
if(typeof(func=this['is' + arguments[1][index].toUpperCase() + 'Phone'])==='function'){
if(func(phone)){
return true;
}
} else {
throw "Invalid Country Code!";
}
}
} else if(typeof(this['is' + arguments[1].toUpperCase() + 'Phone'])==='function'){
return this['is' + arguments[1].toUpperCase() + 'Phone'](phone);
} else {
throw "Invalid Country Code!";
}
} else {
for(index=0; index<this._countryCodes.length; index++){
if(this['is' + this._countryCodes[index] + 'Phone'](phone)){
return true;
}
}
}
return false;
},
/**
* Validates if a zip code is valid in Portugal
*
* @method codPostal
* @param {Number|String} cp1
* @param {optional Number|String} cp2
* @param {optional Boolean} returnBothResults
* @return {Boolean} True if it's a valid zip code
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.codPostal( '1069', '300' ) ); // Result: true
* console.log( InkValidator.codPostal( '1069', '300', true ) ); // Result: [true, true]
* });
*
*/
codPostal: function(cp1,cp2,returnBothResults){
var cPostalSep = /^(\s*\-\s*|\s+)$/;
var trim = /^\s+|\s+$/g;
var cPostal4 = /^[1-9]\d{3}$/;
var cPostal3 = /^\d{3}$/;
var parserCPostal = /^(.{4})(.*)(.{3})$/;
returnBothResults = !!returnBothResults;
cp1 = cp1.replace(trim,'');
if(typeof(cp2)!=='undefined'){
cp2 = cp2.replace(trim,'');
if(cPostal4.test(cp1) && cPostal3.test(cp2)){
if( returnBothResults === true ){
return [true, true];
} else {
return true;
}
}
} else {
if(cPostal4.test(cp1) ){
if( returnBothResults === true ){
return [true,false];
} else {
return true;
}
}
var cPostal = cp1.match(parserCPostal);
if(cPostal!==null && cPostal4.test(cPostal[1]) && cPostalSep.test(cPostal[2]) && cPostal3.test(cPostal[3])){
if( returnBothResults === true ){
return [true,false];
} else {
return true;
}
}
}
if( returnBothResults === true ){
return [false,false];
} else {
return false;
}
},
/**
* Checks is a date is valid in a given format
*
* @method isDate
* @param {String} format - defined in _dateParsers
* @param {String} dateStr - date string
* @return {Boolean} True if it's a valid date and in the specified format
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.isDate( 'yyyy-mm-dd', '2012-05-21' ) ); // Result: true
* });
*/
isDate: function(format, dateStr){
if(typeof(this._dateParsers[format])==='undefined'){
return false;
}
var yearIndex = this._dateParsers[format].year;
var monthIndex = this._dateParsers[format].month;
var dayIndex = this._dateParsers[format].day;
var dateParser = this._dateParsers[format].parser;
var separator = this._dateParsers[format].sep;
/* Trim Deactivated
* var trim = /^\w+|\w+$/g;
* dateStr = dateStr.replace(trim,"");
*/
var data = dateStr.match(dateParser);
if(data!==null){
/* Trim Deactivated
* for(i=1;i<=data.length;i++){
* data[i] = data[i].replace(trim,"");
*}
*/
if(data[2]===data[4] && data[2]===separator){
var _y = ((data[yearIndex].length===2) ? "20" + data[yearIndex].toString() : data[yearIndex] );
if(this._isValidDate(_y,data[monthIndex].toString(),data[dayIndex].toString())){
return true;
}
}
}
return false;
},
/**
* Checks if a string is a valid color
*
* @method isColor
* @param {String} str Color string to be checked
* @return {Boolean} True if it's a valid color string
* @public
* @static
* @example
* Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){
* console.log( InkValidator.isColor( '#FF00FF' ) ); // Result: true
* console.log( InkValidator.isColor( 'amdafasfs' ) ); // Result: false
* });
*/
isColor: function(str){
var match, valid = false,
keyword = /^[a-zA-Z]+$/,
hexa = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,
rgb = /^rgb\(\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*\)$/,
rgba = /^rgba\(\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*(1(\.0)?|0(\.[0-9])?)\s*\)$/,
hsl = /^hsl\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*\)$/,
hsla = /^hsla\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*(1(\.0)?|0(\.[0-9])?)\s*\)$/;
// rgb(123, 123, 132) 0 to 255
// rgb(123%, 123%, 123%) 0 to 100
// rgba( 4 vals) last val: 0 to 1.0
// hsl(0 to 360, %, %)
// hsla( ..., 0 to 1.0)
if(
keyword.test(str) ||
hexa.test(str)
){
return true;
}
var i;
// rgb range check
if((match = rgb.exec(str)) !== null || (match = rgba.exec(str)) !== null){
i = match.length;
while(i--){
// check percentage values
if((i===2 || i===4 || i===6) && typeof match[i] !== "undefined" && match[i] !== ""){
if(typeof match[i-1] !== "undefined" && match[i-1] >= 0 && match[i-1] <= 100){
valid = true;
} else {
return false;
}
}
// check 0 to 255 values
if(i===1 || i===3 || i===5 && (typeof match[i+1] === "undefined" || match[i+1] === "")){
if(typeof match[i] !== "undefined" && match[i] >= 0 && match[i] <= 255){
valid = true;
} else {
return false;
}
}
}
}
// hsl range check
if((match = hsl.exec(str)) !== null || (match = hsla.exec(str)) !== null){
i = match.length;
while(i--){
// check percentage values
if(i===3 || i===5){
if(typeof match[i-1] !== "undefined" && typeof match[i] !== "undefined" && match[i] !== "" &&
match[i-1] >= 0 && match[i-1] <= 100){
valid = true;
} else {
return false;
}
}
// check 0 to 360 value
if(i===1){
if(typeof match[i] !== "undefined" && match[i] >= 0 && match[i] <= 360){
valid = true;
} else {
return false;
}
}
}
}
return valid;
},
/**
* Checks if the value is a valid IP. Supports ipv4 and ipv6
*
* @method validationFunctions.ip
* @param {String} value Value to be checked
* @param {String} ipType Type of IP to be validated. The values are: ipv4, ipv6. By default is ipv4.
* @return {Boolean} True if the value is a valid IP address. False if not.
*/
isIP: function( value, ipType ){
if( typeof value !== 'string' ){
return false;
}
ipType = (ipType || 'ipv4').toLowerCase();
switch( ipType ){
case 'ipv4':
return (/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/).test(value);
case 'ipv6':
return (/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/).test(value);
default:
return false;
}
},
/**
* Credit Card specifications, to be used in the credit card verification.
*
* @property _creditCardSpecs
* @type {Object}
* @private
*/
_creditCardSpecs: {
'default': {
'length': '13,14,15,16,17,18,19',
'prefix': /^.+/,
'luhn': true
},
'american express': {
'length': '15',
'prefix': /^3[47]/,
'luhn' : true
},
'diners club': {
'length': '14,16',
'prefix': /^36|55|30[0-5]/,
'luhn' : true
},
'discover': {
'length': '16',
'prefix': /^6(?:5|011)/,
'luhn' : true
},
'jcb': {
'length': '15,16',
'prefix': /^3|1800|2131/,
'luhn' : true
},
'maestro': {
'length': '16,18',
'prefix': /^50(?:20|38)|6(?:304|759)/,
'luhn' : true
},
'mastercard': {
'length': '16',
'prefix': /^5[1-5]/,
'luhn' : true
},
'visa': {
'length': '13,16',
'prefix': /^4/,
'luhn' : true
}
},
/**
* Luhn function, to be used when validating credit cards
*
*/
_luhn: function (num){
num = parseInt(num,10);
if ( (typeof num !== 'number') && (num % 1 !== 0) ){
// Luhn can only be used on nums!
return false;
}
num = num+'';
// Check num length
var length = num.length;
// Checksum of the card num
var
i, checksum = 0
;
for (i = length - 1; i >= 0; i -= 2)
{
// Add up every 2nd digit, starting from the right
checksum += parseInt(num.substr(i, 1),10);
}
for (i = length - 2; i >= 0; i -= 2)
{
// Add up every 2nd digit doubled, starting from the right
var dbl = parseInt(num.substr(i, 1) * 2,10);
// Subtract 9 from the dbl where value is greater than 10
checksum += (dbl >= 10) ? (dbl - 9) : dbl;
}
// If the checksum is a multiple of 10, the number is valid
return (checksum % 10 === 0);
},
/**
* Validates if a number is of a specific credit card
*
* @param {String} num Number to be validates
* @param {String|Array} creditCardType Credit card type. See _creditCardSpecs for the list of supported values.
* @return {Boolean}
*/
isCreditCard: function(num, creditCardType){
if ( /\d+/.test(num) === false ){
return false;
}
if ( typeof creditCardType === 'undefined' ){
creditCardType = 'default';
}
else if ( typeof creditCardType === 'array' ){
var i, ccLength = creditCardType.length;
for ( i=0; i < ccLength; i++ ){
// Test each type for validity
if (this.isCreditCard(num, creditCardType[i]) ){
return true;
}
}
return false;
}
// Check card type
creditCardType = creditCardType.toLowerCase();
if ( typeof this._creditCardSpecs[creditCardType] === 'undefined' ){
return false;
}
// Check card number length
var length = num.length+'';
// Validate the card length by the card type
if ( this._creditCardSpecs[creditCardType]['length'].split(",").indexOf(length) === -1 ){
return false;
}
// Check card number prefix
if ( !this._creditCardSpecs[creditCardType]['prefix'].test(num) ){
return false;
}
// No Luhn check required
if (this._creditCardSpecs[creditCardType]['luhn'] === false){
return true;
}
return this._luhn(num);
}
};
return Validator;
});
/**
* @module Ink.UI.Aux_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.Aux', '1', ['Ink.Net.Ajax_1','Ink.Dom.Css_1','Ink.Dom.Selector_1','Ink.Util.Url_1'], function(Ajax,Css,Selector,Url) {
'use strict';
var instances = {};
var lastIdNum = 0;
/**
* The Aux class provides auxiliar methods to ease some of the most common/repetitive UI tasks.
*
* @class Ink.UI.Aux
* @version 1
* @static
*/
var Aux = {
/**
* Supported Ink Layouts
*
* @property Layouts
* @type Object
* @readOnly
*/
Layouts: {
SMALL: 'small',
MEDIUM: 'medium',
LARGE: 'large'
},
/**
* Method to check if an item is a valid DOM Element.
*
* @method isDOMElement
* @static
* @param {Mixed} o The object to be checked.
* @return {Boolean} True if it's a valid DOM Element.
* @example
* var el = Ink.s('#element');
* if( Ink.UI.Aux.isDOMElement( el ) === true ){
* // It is a DOM Element.
* } else {
* // It is NOT a DOM Element.
* }
*/
isDOMElement: function(o) {
return (typeof o === 'object' && 'nodeType' in o && o.nodeType === 1);
},
/**
* Method to check if an item is a valid integer.
*
* @method isInteger
* @static
* @param {Mixed} n The value to be checked.
* @return {Boolean} True if 'n' is a valid integer.
* @example
* var value = 1;
* if( Ink.UI.Aux.isInteger( value ) === true ){
* // It is an integer.
* } else {
* // It is NOT an integer.
* }
*/
isInteger: function(n) {
return (typeof n === 'number' && n % 1 === 0);
},
/**
* Method to get a DOM Element. The first parameter should be either a DOM Element or a valid CSS Selector.
* If not, then it will throw an exception. Otherwise, it returns a DOM Element.
*
* @method elOrSelector
* @static
* @param {DOMElement|String} elOrSelector Valid DOM Element or CSS Selector
* @param {String} fieldName This field is used in the thrown Exception to identify the parameter.
* @return {DOMElement} Returns the DOMElement passed or the first result of the CSS Selector. Otherwise it throws an exception.
* @example
* // In case there are several .myInput, it will retrieve the first found
* var el = Ink.UI.Aux.elOrSelector('.myInput','My Input');
*/
elOrSelector: function(elOrSelector, fieldName) {
if (!this.isDOMElement(elOrSelector)) {
var t = Selector.select(elOrSelector);
if (t.length === 0) { throw new TypeError(fieldName + ' must either be a DOM Element or a selector expression!\nThe script element must also be after the DOM Element itself.'); }
return t[0];
}
return elOrSelector;
},
/**
* Method to make a deep copy (clone) of an object.
* Note: The object cannot have loops.
*
* @method clone
* @static
* @param {Object} o The object to be cloned/copied.
* @return {Object} Returns the result of the clone/copy.
* @example
* var originalObj = {
* key1: 'value1',
* key2: 'value2',
* key3: 'value3'
* };
* var cloneObj = Ink.UI.Aux.clone( originalObj );
*/
clone: function(o) {
try {
if (typeof o !== 'object') { throw new Error('Given argument is not an object!'); }
return JSON.parse( JSON.stringify(o) );
} catch (ex) {
throw new Error('Given object cannot have loops!');
}
},
/**
* Method to return the 'nth' position that an element occupies relatively to its parent.
*
* @method childIndex
* @static
* @param {DOMElement} childEl Valid DOM Element.
* @return {Number} Numerical position of an element relatively to its parent.
* @example
* <!-- Imagine the following HTML: -->
* <ul>
* <li>One</li>
* <li>Two</li>
* <li id="test">Three</li>
* <li>Four</li>
* </ul>
*
* <script>
* var testLi = Ink.s('#test');
* Ink.UI.Aux.childIndex( testLi ); // Returned value: 3
* </script>
*/
childIndex: function(childEl) {
if( Aux.isDOMElement(childEl) ){
var els = Selector.select('> *', childEl.parentNode);
for (var i = 0, f = els.length; i < f; ++i) {
if (els[i] === childEl) {
return i;
}
}
}
throw 'not found!';
},
/**
* This method provides a more convenient way to do an async AJAX request and expect a JSON response.
* It offers a callback option, as third paramenter, for a better async handling.
*
* @method ajaxJSON
* @static
* @async
* @param {String} endpoint Valid URL to be used as target by the request.
* @param {Object} params This field is used in the thrown Exception to identify the parameter.
* @example
* // In case there are several .myInput, it will retrieve the first found
* var el = Ink.UI.Aux.elOrSelector('.myInput','My Input');
*/
ajaxJSON: function(endpoint, params, cb) {
new Ajax(
endpoint,
{
evalJS: 'force',
method: 'POST',
parameters: params,
onSuccess: function( r) {
try {
r = r.responseJSON;
if (r.status !== 'ok') {
throw 'server error: ' + r.message;
}
cb(null, r);
} catch (ex) {
cb(ex);
}
},
onFailure: function() {
cb('communication failure');
}
}
);
},
/**
* Method to get the current Ink layout applied.
*
* @method currentLayout
* @static
* @return {String} Returns the value of one of the options of the property Layouts above defined.
* @example
* var inkLayout = Ink.UI.Aux.currentLayout();
*/
currentLayout: function() {
var i, f, k, v, el, detectorEl = Selector.select('#ink-layout-detector')[0];
if (!detectorEl) {
detectorEl = document.createElement('div');
detectorEl.id = 'ink-layout-detector';
for (k in this.Layouts) {
if (this.Layouts.hasOwnProperty(k)) {
v = this.Layouts[k];
el = document.createElement('div');
el.className = 'show-' + v + ' hide-all';
el.setAttribute('data-ink-layout', v);
detectorEl.appendChild(el);
}
}
document.body.appendChild(detectorEl);
}
for (i = 0, f = detectorEl.childNodes.length; i < f; ++i) {
el = detectorEl.childNodes[i];
if (Css.getStyle(el, 'visibility') !== 'hidden') {
return el.getAttribute('data-ink-layout');
}
}
},
/**
* Method to set the location's hash (window.location.hash).
*
* @method hashSet
* @static
* @param {Object} o Object with the info to be placed in the location's hash.
* @example
* // It will set the location's hash like: <url>#key1=value1&key2=value2&key3=value3
* Ink.UI.Aux.hashSet({
* key1: 'value1',
* key2: 'value2',
* key3: 'value3'
* });
*/
hashSet: function(o) {
if (typeof o !== 'object') { throw new TypeError('o should be an object!'); }
var hashParams = Url.getAnchorString();
hashParams = Ink.extendObj(hashParams, o);
window.location.hash = Url.genQueryString('', hashParams).substring(1);
},
/**
* Method to remove children nodes from a given object.
* This method was initially created to help solve a problem in Internet Explorer(s) that occurred when trying
* to set the innerHTML of some specific elements like 'table'.
*
* @method cleanChildren
* @static
* @param {DOMElement} parentEl Valid DOM Element
* @example
* <!-- Imagine the following HTML: -->
* <ul id="myUl">
* <li>One</li>
* <li>Two</li>
* <li>Three</li>
* <li>Four</li>
* </ul>
*
* <script>
* Ink.UI.Aux.cleanChildren( Ink.s( '#myUl' ) );
* </script>
*
* <!-- After running it, the HTML changes to: -->
* <ul id="myUl"></ul>
*/
cleanChildren: function(parentEl) {
if( !Aux.isDOMElement(parentEl) ){
throw 'Please provide a valid DOMElement';
}
var prevEl, el = parentEl.lastChild;
while (el) {
prevEl = el.previousSibling;
parentEl.removeChild(el);
el = prevEl;
}
},
/**
* This method stores the id and/or the classes of a given element in a given object.
*
* @method storeIdAndClasses
* @static
* @param {DOMElement} fromEl Valid DOM Element to get the id and classes from.
* @param {Object} inObj Object where the id and classes will be saved.
* @example
* <div id="myDiv" class="aClass"></div>
*
* <script>
* var storageObj = {};
* Ink.UI.Aux.storeIdAndClasses( Ink.s('#myDiv'), storageObj );
* // storageObj changes to:
* {
* _id: 'myDiv',
* _classes: 'aClass'
* }
* </script>
*/
storeIdAndClasses: function(fromEl, inObj) {
if( !Aux.isDOMElement(fromEl) ){
throw 'Please provide a valid DOMElement as first parameter';
}
var id = fromEl.id;
if (id) {
inObj._id = id;
}
var classes = fromEl.className;
if (classes) {
inObj._classes = classes;
}
},
/**
* This method sets the id and className properties of a given DOM Element based on a given similar object
* resultant of the previous function 'storeIdAndClasses'.
*
* @method restoreIdAndClasses
* @static
* @param {DOMElement} toEl Valid DOM Element to set the id and classes on.
* @param {Object} inObj Object where the id and classes to be set are.
* @example
* <div></div>
*
* <script>
* var storageObj = {
* _id: 'myDiv',
* _classes: 'aClass'
* };
*
* Ink.UI.Aux.storeIdAndClasses( Ink.s('div'), storageObj );
* </script>
*
* <!-- After the code runs the div element changes to: -->
* <div id="myDiv" class="aClass"></div>
*/
restoreIdAndClasses: function(toEl, inObj) {
if( !Aux.isDOMElement(toEl) ){
throw 'Please provide a valid DOMElement as first parameter';
}
if (inObj._id && toEl.id !== inObj._id) {
toEl.id = inObj._id;
}
if (inObj._classes && toEl.className.indexOf(inObj._classes) === -1) {
if (toEl.className) { toEl.className += ' ' + inObj._classes; }
else { toEl.className = inObj._classes; }
}
if (inObj._instanceId && !toEl.getAttribute('data-instance')) {
toEl.setAttribute('data-instance', inObj._instanceId);
}
},
/**
* This method saves a component's instance reference for later retrieval.
*
* @method registerInstance
* @static
* @param {Object} inst Object that holds the instance.
* @param {DOMElement} el DOM Element to associate with the object.
* @param {Object} [optionalPrefix] Defaults to 'instance'
*/
registerInstance: function(inst, el, optionalPrefix) {
if (inst._instanceId) { return; }
if (typeof inst !== 'object') { throw new TypeError('1st argument must be a JavaScript object!'); }
if (inst._options && inst._options.skipRegister) { return; }
if (!this.isDOMElement(el)) { throw new TypeError('2nd argument must be a DOM element!'); }
if (optionalPrefix !== undefined && typeof optionalPrefix !== 'string') { throw new TypeError('3rd argument must be a string!'); }
var id = (optionalPrefix || 'instance') + (++lastIdNum);
instances[id] = inst;
inst._instanceId = id;
var dataInst = el.getAttribute('data-instance');
dataInst = (dataInst !== null) ? [dataInst, id].join(' ') : id;
el.setAttribute('data-instance', dataInst);
},
/**
* This method deletes/destroy an instance with a given id.
*
* @method unregisterInstance
* @static
* @param {String} id Id of the instance to be destroyed.
*/
unregisterInstance: function(id) {
delete instances[id];
},
/**
* This method retrieves the registered instance(s) of a given element or instance id.
*
* @method getInstance
* @static
* @param {String|DOMElement} instanceIdOrElement Instance's id or DOM Element from which we want the instances.
* @return {Object|Object[]} Returns an instance or a collection of instances.
*/
getInstance: function(instanceIdOrElement) {
var ids;
if (this.isDOMElement(instanceIdOrElement)) {
ids = instanceIdOrElement.getAttribute('data-instance');
if (ids === null) { throw new Error('argument is not a DOM instance element!'); }
}
else {
ids = instanceIdOrElement;
}
ids = ids.split(' ');
var inst, id, i, l = ids.length;
var res = [];
for (i = 0; i < l; ++i) {
id = ids[i];
if (!id) { throw new Error('Element is not a JS instance!'); }
inst = instances[id];
if (!inst) { throw new Error('Instance "' + id + '" not found!'); }
res.push(inst);
}
return (l === 1) ? res[0] : res;
},
/**
* This method retrieves the registered instance(s) of an element based on the given selector.
*
* @method getInstanceFromSelector
* @static
* @param {String} selector CSS selector to define the element from which it'll get the instance(s).
* @return {Object|Object[]} Returns an instance or a collection of instances.
*/
getInstanceFromSelector: function(selector) {
var el = Selector.select(selector)[0];
if (!el) { throw new Error('Element not found!'); }
return this.getInstance(el);
},
/**
* This method retrieves the registered instances' ids of all instances.
*
* @method getInstanceIds
* @static
* @return {String[]} Id or collection of ids of all existing instances.
*/
getInstanceIds: function() {
var res = [];
for (var id in instances) {
if (instances.hasOwnProperty(id)) {
res.push( id );
}
}
return res;
},
/**
* This method retrieves all existing instances.
*
* @method getInstances
* @static
* @return {Object[]} Collection of existing instances.
*/
getInstances: function() {
var res = [];
for (var id in instances) {
if (instances.hasOwnProperty(id)) {
res.push( instances[id] );
}
}
return res;
},
/**
* This method is not to supposed to be invoked by the Aux component.
* Components should copy this method as its destroy method.
*
* @method destroyComponent
* @static
*/
destroyComponent: function() {
Ink.Util.Aux.unregisterInstance(this._instanceId);
this._element.parentNode.removeChild(this._element);
}
};
return Aux;
});
/**
* @module Ink.UI.Pagination_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.Pagination', '1',
['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1'],
function(Aux, Event, Css, Element, Selector ) {
'use strict';
/**
* Function to create the pagination anchors
*
* @method genAel
* @param {String} inner HTML to be placed inside the anchor.
* @return {DOMElement} Anchor created
*/
var genAEl = function(inner, index) {
var aEl = document.createElement('a');
aEl.setAttribute('href', '#');
if (index !== undefined) {
aEl.setAttribute('data-index', index);
}
aEl.innerHTML = inner;
return aEl;
};
/**
* @class Ink.UI.Pagination
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} options Options
* @param {Number} options.size number of pages
* @param {Number} [options.maxSize] if passed, only shows at most maxSize items. displays also first|prev page and next page|last buttons
* @param {Number} [options.start] start page. defaults to 1
* @param {String} [options.previousLabel] label to display on previous page button
* @param {String} [options.nextLabel] label to display on next page button
* @param {String} [options.previousPageLabel] label to display on previous page button
* @param {String} [options.nextPageLabel] label to display on next page button
* @param {String} [options.firstLabel] label to display on previous page button
* @param {String} [options.lastLabel] label to display on next page button
* @param {Function} [options.onChange] optional callback
* @param {Function} [options.numberFormatter] optional function which takes and 0-indexed number and returns the string which appears on a numbered button
* @param {Boolean} [options.setHash] if true, sets hashParameter on the location.hash. default is disabled
* @param {String} [options.hashParameter] parameter to use on setHash. by default uses 'page'
*/
var Pagination = function(selector, options) {
this._element = Aux.elOrSelector(selector, '1st argument');
this._options = Ink.extendObj(
{
size: undefined,
start: 1,
firstLabel: 'First',
lastLabel: 'Last',
previousLabel: 'Previous',
nextLabel: 'Next',
onChange: undefined,
setHash: false,
hashParameter: 'page',
numberFormatter: function(i) { return i + 1; }
},
options || {},
Element.data(this._element)
);
if (!this._options.previousPageLabel) {
this._options.previousPageLabel = 'Previous ' + this._options.maxSize;
}
if (!this._options.nextPageLabel) {
this._options.nextPageLabel = 'Next ' + this._options.maxSize;
}
this._handlers = {
click: Ink.bindEvent(this._onClick,this)
};
if (!Aux.isInteger(this._options.size)) {
throw new TypeError('size option is a required integer!');
}
if (!Aux.isInteger(this._options.start) && this._options.start > 0 && this._options.start <= this._options.size) {
throw new TypeError('start option is a required integer between 1 and size!');
}
if (this._options.maxSize && !Aux.isInteger(this._options.maxSize) && this._options.maxSize > 0) {
throw new TypeError('maxSize option is a positive integer!');
}
else if (this._options.size < 0) {
throw new RangeError('size option must be equal or more than 0!');
}
if (this._options.onChange !== undefined && typeof this._options.onChange !== 'function') {
throw new TypeError('onChange option must be a function!');
}
if (Css.hasClassName( Ink.s('ul', this._element), 'dotted')) {
this._options.numberFormatter = function() { return '<i class="icon-circle"></i>'; };
}
this._current = this._options.start - 1;
this._itemLiEls = [];
this._init();
};
Pagination.prototype = {
/**
* Init function called by the constructor
*
* @method _init
* @private
*/
_init: function() {
// generate and apply DOM
this._generateMarkup(this._element);
this._updateItems();
// subscribe events
this._observe();
Aux.registerInstance(this, this._element, 'pagination');
},
/**
* Responsible for setting listener in the 'click' event of the Pagination element.
*
* @method _observe
* @private
*/
_observe: function() {
Event.observe(this._element, 'click', this._handlers.click);
},
/**
* Updates the markup everytime there's a change in the Pagination object.
*
* @method _updateItems
* @private
*/
_updateItems: function() {
var liEls = this._itemLiEls;
var isSimpleToggle = this._options.size === liEls.length;
var i, f, liEl;
if (isSimpleToggle) {
// just toggle active class
for (i = 0, f = this._options.size; i < f; ++i) {
Css.setClassName(liEls[i], 'active', i === this._current);
}
}
else {
// remove old items
for (i = liEls.length - 1; i >= 0; --i) {
this._ulEl.removeChild(liEls[i]);
}
// add new items
liEls = [];
for (i = 0, f = this._options.size; i < f; ++i) {
liEl = document.createElement('li');
liEl.appendChild( genAEl( this._options.numberFormatter(i), i) );
Css.setClassName(liEl, 'active', i === this._current);
this._ulEl.insertBefore(liEl, this._nextEl);
liEls.push(liEl);
}
this._itemLiEls = liEls;
}
if (this._options.maxSize) {
// toggle visible items
var page = Math.floor( this._current / this._options.maxSize );
var pi = this._options.maxSize * page;
var pf = pi + this._options.maxSize - 1;
for (i = 0, f = this._options.size; i < f; ++i) {
liEl = liEls[i];
Css.setClassName(liEl, 'hide-all', i < pi || i > pf);
}
this._pageStart = pi;
this._pageEnd = pf;
this._page = page;
Css.setClassName(this._prevPageEl, 'disabled', !this.hasPreviousPage());
Css.setClassName(this._nextPageEl, 'disabled', !this.hasNextPage());
Css.setClassName(this._firstEl, 'disabled', this.isFirst());
Css.setClassName(this._lastEl, 'disabled', this.isLast());
}
// update prev and next
Css.setClassName(this._prevEl, 'disabled', !this.hasPrevious());
Css.setClassName(this._nextEl, 'disabled', !this.hasNext());
},
/**
* Returns the top element for the gallery DOM representation
*
* @method _generateMarkup
* @param {DOMElement} el
* @private
*/
_generateMarkup: function(el) {
Css.addClassName(el, 'ink-navigation');
var
ulEl,liEl,
hasUlAlready = false
;
if( ( ulEl = Selector.select('ul.pagination',el)).length < 1 ){
ulEl = document.createElement('ul');
Css.addClassName(ulEl, 'pagination');
} else {
hasUlAlready = true;
ulEl = ulEl[0];
}
if (this._options.maxSize) {
liEl = document.createElement('li');
liEl.appendChild( genAEl(this._options.firstLabel) );
this._firstEl = liEl;
Css.addClassName(liEl, 'first');
ulEl.appendChild(liEl);
liEl = document.createElement('li');
liEl.appendChild( genAEl(this._options.previousPageLabel) );
this._prevPageEl = liEl;
Css.addClassName(liEl, 'previousPage');
ulEl.appendChild(liEl);
}
liEl = document.createElement('li');
liEl.appendChild( genAEl(this._options.previousLabel) );
this._prevEl = liEl;
Css.addClassName(liEl, 'previous');
ulEl.appendChild(liEl);
liEl = document.createElement('li');
liEl.appendChild( genAEl(this._options.nextLabel) );
this._nextEl = liEl;
Css.addClassName(liEl, 'next');
ulEl.appendChild(liEl);
if (this._options.maxSize) {
liEl = document.createElement('li');
liEl.appendChild( genAEl(this._options.nextPageLabel) );
this._nextPageEl = liEl;
Css.addClassName(liEl, 'nextPage');
ulEl.appendChild(liEl);
liEl = document.createElement('li');
liEl.appendChild( genAEl(this._options.lastLabel) );
this._lastEl = liEl;
Css.addClassName(liEl, 'last');
ulEl.appendChild(liEl);
}
if( !hasUlAlready ){
el.appendChild(ulEl);
}
this._ulEl = ulEl;
},
/**
* Click handler
*
* @method _onClick
* @param {Event} ev
* @private
*/
_onClick: function(ev) {
Event.stop(ev);
var tgtEl = Event.element(ev);
if (tgtEl.nodeName.toLowerCase() !== 'a') {
do{
tgtEl = tgtEl.parentNode;
}while( (tgtEl.nodeName.toLowerCase() !== 'a') && (tgtEl !== this._element) );
if( tgtEl === this._element){
return;
}
}
var liEl = tgtEl.parentNode;
if (liEl.nodeName.toLowerCase() !== 'li') { return; }
if ( Css.hasClassName(liEl, 'active') ||
Css.hasClassName(liEl, 'disabled') ) { return; }
var isPrev = Css.hasClassName(liEl, 'previous');
var isNext = Css.hasClassName(liEl, 'next');
var isPrevPage = Css.hasClassName(liEl, 'previousPage');
var isNextPage = Css.hasClassName(liEl, 'nextPage');
var isFirst = Css.hasClassName(liEl, 'first');
var isLast = Css.hasClassName(liEl, 'last');
if (isFirst) {
this.setCurrent(0);
}
else if (isLast) {
this.setCurrent(this._options.size - 1);
}
else if (isPrevPage || isNextPage) {
this.setCurrent( (isPrevPage ? -1 : 1) * this._options.maxSize, true);
}
else if (isPrev || isNext) {
this.setCurrent(isPrev ? -1 : 1, true);
}
else {
var nr = parseInt( tgtEl.getAttribute('data-index'), 10);
this.setCurrent(nr);
}
},
/**************
* PUBLIC API *
**************/
/**
* Sets the number of pages
*
* @method setSize
* @param {Number} sz number of pages
* @public
*/
setSize: function(sz) {
if (!Aux.isInteger(sz)) {
throw new TypeError('1st argument must be an integer number!');
}
this._options.size = sz;
this._updateItems();
this._current = 0;
},
/**
* Sets the current page
*
* @method setCurrent
* @param {Number} nr sets the current page to given number
* @param {Boolean} isRelative trueish to set relative change instead of absolute (default)
* @public
*/
setCurrent: function(nr, isRelative) {
if (!Aux.isInteger(nr)) {
throw new TypeError('1st argument must be an integer number!');
}
if (isRelative) {
nr += this._current;
}
if (nr < 0) {
nr = 0;
}
else if (nr > this._options.size - 1) {
nr = this._options.size - 1;
}
this._current = nr;
this._updateItems();
/*if (this._options.setHash) {
var o = {};
o[this._options.hashParameter] = nr;
Aux.setHash(o);
}*/
if (this._options.onChange) { this._options.onChange(this); }
},
/**
* Returns the number of pages
*
* @method getSize
* @return {Number} Number of pages
* @public
*/
getSize: function() {
return this._options.size;
},
/**
* Returns current page
*
* @method getCurrent
* @return {Number} Current page
* @public
*/
getCurrent: function() {
return this._current;
},
/**
* Returns true iif at first page
*
* @method isFirst
* @return {Boolean} True if at first page
* @public
*/
isFirst: function() {
return this._current === 0;
},
/**
* Returns true iif at last page
*
* @method isLast
* @return {Boolean} True if at last page
* @public
*/
isLast: function() {
return this._current === this._options.size - 1;
},
/**
* Returns true iif has prior pages
*
* @method hasPrevious
* @return {Boolean} True if has prior pages
* @public
*/
hasPrevious: function() {
return this._current > 0;
},
/**
* Returns true iif has pages ahead
*
* @method hasNext
* @return {Boolean} True if has pages ahead
* @public
*/
hasNext: function() {
return this._current < this._options.size - 1;
},
/**
* Returns true iif has prior set of page(s)
*
* @method hasPreviousPage
* @return {Boolean} Returns true iif has prior set of page(s)
* @public
*/
hasPreviousPage: function() {
return this._options.maxSize && this._current > this._options.maxSize - 1;
},
/**
* Returns true iif has set of page(s) ahead
*
* @method hasNextPage
* @return {Boolean} Returns true iif has set of page(s) ahead
* @public
*/
hasNextPage: function() {
return this._options.maxSize && this._options.size - this._current >= this._options.maxSize + 1;
},
/**
* Unregisters the component and removes its markup from the DOM
*
* @method destroy
* @public
*/
destroy: Aux.destroyComponent
};
return Pagination;
});
/**
* @module Ink.UI.SortableList_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.SortableList', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) {
'use strict';
/**
* Adds sortable behaviour to any list!
*
* @class Ink.UI.SortableList
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {String} [options.dragObject] CSS Selector. The element that will trigger the dragging in the list. Default is 'li'.
* @example
* <ul class="unstyled ink-sortable-list" id="slist" data-instance="sortableList9">
* <li><span class="ink-label info"><i class="icon-reorder"></i>drag here</span>primeiro</li>
* <li><span class="ink-label info"><i class="icon-reorder"></i>drag here</span>segundo</li>
* <li><span class="ink-label info"><i class="icon-reorder"></i>drag here</span>terceiro</li>
* </ul>
* <script>
* Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.SortableList_1'], function( Selector, SortableList ){
* var sortableListElement = Ink.s('.ink-sortable-list');
* var sortableListObj = new SortableList( sortableListElement );
* });
* </script>
*/
var SortableList = function(selector, options) {
this._element = Aux.elOrSelector(selector, '1st argument');
if( !Aux.isDOMElement(selector) && (typeof selector !== 'string') ){
throw '[Ink.UI.SortableList] :: Invalid selector';
} else if( typeof selector === 'string' ){
this._element = Ink.Dom.Selector.select( selector );
if( this._element.length < 1 ){
throw '[Ink.UI.SortableList] :: Selector has returned no elements';
}
this._element = this._element[0];
} else {
this._element = selector;
}
this._options = Ink.extendObj({
dragObject: 'li'
}, Ink.Dom.Element.data(this._element));
this._options = Ink.extendObj( this._options, options || {});
this._handlers = {
down: Ink.bindEvent(this._onDown,this),
move: Ink.bindEvent(this._onMove,this),
up: Ink.bindEvent(this._onUp,this)
};
this._model = [];
this._index = undefined;
this._isMoving = false;
if (this._options.model instanceof Array) {
this._model = this._options.model;
this._createdFrom = 'JSON';
}
else if (this._element.nodeName.toLowerCase() === 'ul') {
this._createdFrom = 'DOM';
}
else {
throw new TypeError('You must pass a selector expression/DOM element as 1st option or provide a model on 2nd argument!');
}
this._dragTriggers = Selector.select( this._options.dragObject, this._element );
if( !this._dragTriggers ){
throw "[Ink.UI.SortableList] :: Drag object not found";
}
this._init();
};
SortableList.prototype = {
/**
* Init function called by the constructor.
*
* @method _init
* @private
*/
_init: function() {
// extract model
if (this._createdFrom === 'DOM') {
this._extractModelFromDOM();
this._createdFrom = 'JSON';
}
var isTouch = 'ontouchstart' in document.documentElement;
this._down = isTouch ? 'touchstart': 'mousedown';
this._move = isTouch ? 'touchmove' : 'mousemove';
this._up = isTouch ? 'touchend' : 'mouseup';
// subscribe events
var db = document.body;
Event.observe(db, this._move, this._handlers.move);
Event.observe(db, this._up, this._handlers.up);
this._observe();
Aux.registerInstance(this, this._element, 'sortableList');
},
/**
* Sets the event handlers.
*
* @method _observe
* @private
*/
_observe: function() {
Event.observe(this._element, this._down, this._handlers.down);
},
/**
* Updates the model from the UL representation
*
* @method _extractModelFromDOM
* @private
*/
_extractModelFromDOM: function() {
this._model = [];
var that = this;
var liEls = Selector.select('> li', this._element);
InkArray.each(liEls,function(liEl) {
//var t = Element.getChildrenText(liEl);
var t = liEl.innerHTML;
that._model.push(t);
});
},
/**
* Returns the top element for the gallery DOM representation
*
* @method _generateMarkup
* @return {DOMElement}
* @private
*/
_generateMarkup: function() {
var el = document.createElement('ul');
el.className = 'unstyled ink-sortable-list';
var that = this;
InkArray.each(this._model,function(label, idx) {
var liEl = document.createElement('li');
if (idx === that._index) {
liEl.className = 'drag';
}
liEl.innerHTML = [
// '<span class="ink-label ink-info"><i class="icon-reorder"></i>', that._options.dragLabel, '</span>', label
label
].join('');
el.appendChild(liEl);
});
return el;
},
/**
* Extracts the Y coordinate of the mouse from the given MouseEvent
*
* @method _getY
* @param {Event} ev
* @return {Number}
* @private
*/
_getY: function(ev) {
if (ev.type.indexOf('touch') === 0) {
//console.log(ev.type, ev.changedTouches[0].pageY);
return ev.changedTouches[0].pageY;
}
if (typeof ev.pageY === 'number') {
return ev.pageY;
}
return ev.clientY;
},
/**
* Refreshes the markup.
*
* @method _refresh
* @param {Boolean} skipObs True if needs to set the event handlers, false if not.
* @private
*/
_refresh: function(skipObs) {
var el = this._generateMarkup();
this._element.parentNode.replaceChild(el, this._element);
this._element = el;
Aux.restoreIdAndClasses(this._element, this);
this._dragTriggers = Selector.select( this._options.dragObject, this._element );
// subscribe events
if (!skipObs) { this._observe(); }
},
/**
* Mouse down handler
*
* @method _onDown
* @param {Event} ev
* @return {Boolean|undefined} [description]
* @private
*/
_onDown: function(ev) {
if (this._isMoving) { return; }
var tgtEl = Event.element(ev);
if( !InkArray.inArray(tgtEl,this._dragTriggers) ){
while( !InkArray.inArray(tgtEl,this._dragTriggers) && (tgtEl.nodeName.toLowerCase() !== 'body') ){
tgtEl = tgtEl.parentNode;
}
if( tgtEl.nodeName.toLowerCase() === 'body' ){
return;
}
}
Event.stop(ev);
var liEl;
if( tgtEl.nodeName.toLowerCase() !== 'li' ){
while( (tgtEl.nodeName.toLowerCase() !== 'li') && (tgtEl.nodeName.toLowerCase() !== 'body') ){
tgtEl = tgtEl.parentNode;
}
}
liEl = tgtEl;
this._index = Aux.childIndex(liEl);
this._height = liEl.offsetHeight;
this._startY = this._getY(ev);
this._isMoving = true;
document.body.style.cursor = 'move';
this._refresh(false);
return false;
},
/**
* Mouse move handler
*
* @method _onMove
* @param {Event} ev
* @private
*/
_onMove: function(ev) {
if (!this._isMoving) { return; }
Event.stop(ev);
var y = this._getY(ev);
//console.log(y);
var dy = y - this._startY;
var sign = dy > 0 ? 1 : -1;
var di = sign * Math.floor( Math.abs(dy) / this._height );
if (di === 0) { return; }
di = di / Math.abs(di);
if ( (di === -1 && this._index === 0) ||
(di === 1 && this._index === this._model.length - 1) ) { return; }
var a = di > 0 ? this._index : this._index + di;
var b = di < 0 ? this._index : this._index + di;
//console.log(a, b);
this._model.splice(a, 2, this._model[b], this._model[a]);
this._index += di;
this._startY = y;
this._refresh(false);
},
/**
* Mouse up handler
*
* @method _onUp
* @param {Event} ev
* @private
*/
_onUp: function(ev) {
if (!this._isMoving) { return; }
Event.stop(ev);
this._index = undefined;
this._isMoving = false;
document.body.style.cursor = '';
this._refresh();
},
/**************
* PUBLIC API *
**************/
/**
* Returns a copy of the model
*
* @method getModel
* @return {Array} Copy of the model
* @public
*/
getModel: function() {
return this._model.slice();
},
/**
* Unregisters the component and removes its markup from the DOM
*
* @method destroy
* @public
*/
destroy: Aux.destroyComponent
};
return SortableList;
});
/**
* @module Ink.UI.Spy_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.Spy', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) {
'use strict';
/**
* Spy is a component that 'spies' an element (or a group of elements) and when they leave the viewport (through the top),
* highlight an option - related to that element being spied - that resides in a menu, initially identified as target.
*
* @class Ink.UI.Spy
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {DOMElement|String} options.target Target menu on where the spy will highlight the right option.
* @example
* <script>
* Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Spy_1'], function( Selector, Spy ){
* var menuElement = Ink.s('#menu');
* var specialAnchorToSpy = Ink.s('#specialAnchor');
* var spyObj = new Spy( specialAnchorToSpy, {
* target: menuElement
* });
* });
* </script>
*/
var Spy = function( selector, options ){
this._rootElement = Aux.elOrSelector(selector,'1st argument');
/**
* Setting default options and - if needed - overriding it with the data attributes
*/
this._options = Ink.extendObj({
target: undefined
}, Element.data( this._rootElement ) );
/**
* In case options have been defined when creating the instance, they've precedence
*/
this._options = Ink.extendObj(this._options,options || {});
this._options.target = Aux.elOrSelector( this._options.target, 'Target' );
this._scrollTimeout = null;
this._init();
};
Spy.prototype = {
/**
* Stores the spy elements
*
* @property _elements
* @type {Array}
* @readOnly
*
*/
_elements: [],
/**
* Init function called by the constructor
*
* @method _init
* @private
*/
_init: function(){
Event.observe( document, 'scroll', Ink.bindEvent(this._onScroll,this) );
this._elements.push(this._rootElement);
},
/**
* Scroll handler. Responsible for highlighting the right options of the target menu.
*
* @method _onScroll
* @private
*/
_onScroll: function(){
var scrollHeight = Element.scrollHeight();
if( (scrollHeight < this._rootElement.offsetTop) ){
return;
} else {
for( var i = 0, total = this._elements.length; i < total; i++ ){
if( (this._elements[i].offsetTop <= scrollHeight) && (this._elements[i] !== this._rootElement) && (this._elements[i].offsetTop > this._rootElement.offsetTop) ){
return;
}
}
}
InkArray.each(
Selector.select(
'a',
this._options.target
), Ink.bind(function(item){
var comparisonValue = ( ("name" in this._rootElement) && this._rootElement.name ?
'#' + this._rootElement.name : '#' + this._rootElement.id
);
if( item.href.substr(item.href.indexOf('#')) === comparisonValue ){
Css.addClassName(Element.findUpwardsByTag(item,'li'),'active');
} else {
Css.removeClassName(Element.findUpwardsByTag(item,'li'),'active');
}
},this)
);
}
};
return Spy;
});
/**
* @module Ink.UI.Sticky_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.Sticky', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1'], function(Aux, Event, Css, Element, Selector ) {
'use strict';
/**
* The Sticky component takes an element and transforms it's behavior in order to, when the user scrolls he sets its position
* to fixed and maintain it until the user scrolls back to the same place.
*
* @class Ink.UI.Sticky
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {Number} options.offsetBottom Number of pixels of distance from the bottomElement.
* @param {Number} options.offsetTop Number of pixels of distance from the topElement.
* @param {String} options.topElement CSS Selector that specifies a top element with which the component could collide.
* @param {String} options.bottomElement CSS Selector that specifies a bottom element with which the component could collide.
* @example
* <script>
* Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Sticky_1'], function( Selector, Sticky ){
* var menuElement = Ink.s('#menu');
* var stickyObj = new Sticky( menuElement );
* });
* </script>
*/
var Sticky = function( selector, options ){
if( typeof selector !== 'object' && typeof selector !== 'string'){
throw '[Sticky] :: Invalid selector defined';
}
if( typeof selector === 'object' ){
this._rootElement = selector;
} else {
this._rootElement = Selector.select( selector );
if( this._rootElement.length <= 0) {
throw "[Sticky] :: Can't find any element with the specified selector";
}
this._rootElement = this._rootElement[0];
}
/**
* Setting default options and - if needed - overriding it with the data attributes
*/
this._options = Ink.extendObj({
offsetBottom: 0,
offsetTop: 0,
topElement: undefined,
bottomElement: undefined
}, Element.data( this._rootElement ) );
/**
* In case options have been defined when creating the instance, they've precedence
*/
this._options = Ink.extendObj(this._options,options || {});
if( typeof( this._options.topElement ) !== 'undefined' ){
this._options.topElement = Aux.elOrSelector( this._options.topElement, 'Top Element');
} else {
this._options.topElement = Aux.elOrSelector( 'body', 'Top Element');
}
if( typeof( this._options.bottomElement ) !== 'undefined' ){
this._options.bottomElement = Aux.elOrSelector( this._options.bottomElement, 'Bottom Element');
} else {
this._options.bottomElement = Aux.elOrSelector( 'body', 'Top Element');
}
this._computedStyle = window.getComputedStyle ? window.getComputedStyle(this._rootElement, null) : this._rootElement.currentStyle;
this._dims = {
height: this._computedStyle.height,
width: this._computedStyle.width
};
this._init();
};
Sticky.prototype = {
/**
* Init function called by the constructor
*
* @method _init
* @private
*/
_init: function(){
Event.observe( document, 'scroll', Ink.bindEvent(this._onScroll,this) );
Event.observe( window, 'resize', Ink.bindEvent(this._onResize,this) );
this._calculateOriginalSizes();
this._calculateOffsets();
},
/**
* Scroll handler.
*
* @method _onScroll
* @private
*/
_onScroll: function(){
var viewport = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body;
if(
( ( (Element.elementWidth(this._rootElement)*100)/viewport.clientWidth ) > 90 ) ||
( viewport.clientWidth<=649 )
){
if( Element.hasAttribute(this._rootElement,'style') ){
this._rootElement.removeAttribute('style');
}
return;
}
if( this._scrollTimeout ){
clearTimeout(this._scrollTimeout);
}
this._scrollTimeout = setTimeout(Ink.bind(function(){
var scrollHeight = Element.scrollHeight();
if( Element.hasAttribute(this._rootElement,'style') ){
if( scrollHeight <= (this._options.originalTop-this._options.originalOffsetTop)){
this._rootElement.removeAttribute('style');
} else if( ((document.body.scrollHeight-(scrollHeight+parseInt(this._dims.height,10))) < this._options.offsetBottom) ){
this._rootElement.style.position = 'fixed';
this._rootElement.style.top = 'auto';
this._rootElement.style.left = this._options.originalLeft + 'px';
if( this._options.offsetBottom < parseInt(document.body.scrollHeight - (document.documentElement.clientHeight+scrollHeight),10) ){
this._rootElement.style.bottom = this._options.originalOffsetBottom + 'px';
} else {
this._rootElement.style.bottom = this._options.offsetBottom - parseInt(document.body.scrollHeight - (document.documentElement.clientHeight+scrollHeight),10) + 'px';
}
this._rootElement.style.width = this._options.originalWidth + 'px';
} else if( ((document.body.scrollHeight-(scrollHeight+parseInt(this._dims.height,10))) >= this._options.offsetBottom) ){
this._rootElement.style.left = this._options.originalLeft + 'px';
this._rootElement.style.position = 'fixed';
this._rootElement.style.bottom = 'auto';
this._rootElement.style.left = this._options.originalLeft + 'px';
this._rootElement.style.top = this._options.originalOffsetTop + 'px';
this._rootElement.style.width = this._options.originalWidth + 'px';
}
} else {
if( scrollHeight <= (this._options.originalTop-this._options.originalOffsetTop)){
return;
}
this._rootElement.style.left = this._options.originalLeft + 'px';
this._rootElement.style.position = 'fixed';
this._rootElement.style.bottom = 'auto';
this._rootElement.style.left = this._options.originalLeft + 'px';
this._rootElement.style.top = this._options.originalOffsetTop + 'px';
this._rootElement.style.width = this._options.originalWidth + 'px';
}
this._scrollTimeout = undefined;
},this), 0);
},
/**
* Resize handler
*
* @method _onResize
* @private
*/
_onResize: function(){
if( this._resizeTimeout ){
clearTimeout(this._resizeTimeout);
}
this._resizeTimeout = setTimeout(Ink.bind(function(){
this._rootElement.removeAttribute('style');
this._calculateOriginalSizes();
this._calculateOffsets();
}, this),0);
},
/**
* On each resizing (and in the beginning) the component recalculates the offsets, since
* the top and bottom element heights might have changed.
*
* @method _calculateOffsets
* @private
*/
_calculateOffsets: function(){
/**
* Calculating the offset top
*/
if( typeof this._options.topElement !== 'undefined' ){
if( this._options.topElement.nodeName.toLowerCase() !== 'body' ){
var
topElementHeight = Element.elementHeight( this._options.topElement ),
topElementTop = Element.elementTop( this._options.topElement )
;
this._options.offsetTop = ( parseInt(topElementHeight,10) + parseInt(topElementTop,10) ) + parseInt(this._options.originalOffsetTop,10);
} else {
this._options.offsetTop = parseInt(this._options.originalOffsetTop,10);
}
}
/**
* Calculating the offset bottom
*/
if( typeof this._options.bottomElement !== 'undefined' ){
if( this._options.bottomElement.nodeName.toLowerCase() !== 'body' ){
var
bottomElementHeight = Element.elementHeight(this._options.bottomElement)
;
this._options.offsetBottom = parseInt(bottomElementHeight,10) + parseInt(this._options.originalOffsetBottom,10);
} else {
this._options.offsetBottom = parseInt(this._options.originalOffsetBottom,10);
}
}
this._onScroll();
},
/**
* Function to calculate the 'original size' of the element.
* It's used in the begining (_init method) and when a scroll happens
*
* @method _calculateOriginalSizes
* @private
*/
_calculateOriginalSizes: function(){
if( typeof this._options.originalOffsetTop === 'undefined' ){
this._options.originalOffsetTop = parseInt(this._options.offsetTop,10);
this._options.originalOffsetBottom = parseInt(this._options.offsetBottom,10);
}
this._options.originalTop = parseInt(this._rootElement.offsetTop,10);
this._options.originalLeft = parseInt(this._rootElement.offsetLeft,10);
if(isNaN(this._options.originalWidth = parseInt(this._dims.width,10))) {
this._options.originalWidth = 0;
}
this._options.originalWidth = parseInt(this._computedStyle.width,10);
}
};
return Sticky;
});
/**
* @module Ink.UI.Table_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.Table', '1', ['Ink.Net.Ajax_1','Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1','Ink.Util.String_1'], function(Ajax, Aux, Event, Css, Element, Selector, InkArray, InkString ) {
'use strict';
/**
* The Table component transforms the native/DOM table element into a
* sortable, paginated component.
*
* @class Ink.UI.Table
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {Number} options.pageSize Number of rows per page.
* @param {String} options.endpoint Endpoint to get the records via AJAX
* @example
* <table class="ink-table alternating" data-page-size="6">
* <thead>
* <tr>
* <th data-sortable="true" width="75%">Pepper</th>
* <th data-sortable="true" width="25%">Scoville Rating</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>Trinidad Moruga Scorpion</td>
* <td>1500000</td>
* </tr>
* <tr>
* <td>Bhut Jolokia</td>
* <td>1000000</td>
* </tr>
* <tr>
* <td>Naga Viper</td>
* <td>1463700</td>
* </tr>
* <tr>
* <td>Red Savina Habanero</td>
* <td>580000</td>
* </tr>
* <tr>
* <td>Habanero</td>
* <td>350000</td>
* </tr>
* <tr>
* <td>Scotch Bonnet</td>
* <td>180000</td>
* </tr>
* <tr>
* <td>Malagueta</td>
* <td>50000</td>
* </tr>
* <tr>
* <td>Tabasco</td>
* <td>35000</td>
* </tr>
* <tr>
* <td>Serrano Chili</td>
* <td>27000</td>
* </tr>
* <tr>
* <td>Jalapeño</td>
* <td>8000</td>
* </tr>
* <tr>
* <td>Poblano</td>
* <td>1500</td>
* </tr>
* <tr>
* <td>Peperoncino</td>
* <td>500</td>
* </tr>
* </tbody>
* </table>
* <nav class="ink-navigation"><ul class="pagination"></ul></nav>
* <script>
* Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Table_1'], function( Selector, Table ){
* var tableElement = Ink.s('.ink-table');
* var tableObj = new Table( tableElement );
* });
* </script>
*/
var Table = function( selector, options ){
/**
* Get the root element
*/
this._rootElement = Aux.elOrSelector(selector, '1st argument');
if( this._rootElement.nodeName.toLowerCase() !== 'table' ){
throw '[Ink.UI.Table] :: The element is not a table';
}
this._options = Ink.extendObj({
pageSize: undefined,
endpoint: undefined,
loadMode: 'full',
allowResetSorting: false,
visibleFields: undefined
},Element.data(this._rootElement));
this._options = Ink.extendObj( this._options, options || {});
/**
* Checking if it's in markup mode or endpoint mode
*/
this._markupMode = ( typeof this._options.endpoint === 'undefined' );
if( !!this._options.visibleFields ){
this._options.visibleFields = this._options.visibleFields.split(',');
}
/**
* Initializing variables
*/
this._handlers = {
click: Ink.bindEvent(this._onClick,this)
};
this._originalFields = [];
this._sortableFields = {};
this._originalData = this._data = [];
this._headers = [];
this._pagination = null;
this._totalRows = 0;
this._init();
};
Table.prototype = {
/**
* Init function called by the constructor
*
* @method _init
* @private
*/
_init: function(){
/**
* If not is in markup mode, we have to do the initial request
* to get the first data and the headers
*/
if( !this._markupMode ){
this._getData( this._options.endpoint, true );
} else{
this._setHeadersHandlers();
/**
* Getting the table's data
*/
InkArray.each(Selector.select('tbody tr',this._rootElement),Ink.bind(function(tr){
this._data.push(tr);
},this));
this._originalData = this._data.slice(0);
this._totalRows = this._data.length;
/**
* Set pagination if defined
*
*/
if( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') ){
/**
* Applying the pagination
*/
this._pagination = this._rootElement.nextSibling;
while(this._pagination.nodeType !== 1){
this._pagination = this._pagination.nextSibling;
}
if( this._pagination.nodeName.toLowerCase() !== 'nav' ){
throw '[Ink.UI.Table] :: Missing the pagination markup or is mis-positioned';
}
var Pagination = Ink.getModule('Ink.UI.Pagination',1);
this._pagination = new Pagination( this._pagination, {
size: Math.ceil(this._totalRows/this._options.pageSize),
onChange: Ink.bind(function( pagingObj ){
this._paginate( (pagingObj._current+1) );
},this)
});
this._paginate(1);
}
}
},
/**
* Click handler. This will mainly handle the sorting (when you click in the headers)
*
* @method _onClick
* @param {Event} event Event obj
* @private
*/
_onClick: function( event ){
var
tgtEl = Event.element(event),
dataset = Element.data(tgtEl),
index,i,
paginated = ( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') )
;
if( (tgtEl.nodeName.toLowerCase() !== 'th') || ( !("sortable" in dataset) || (dataset.sortable.toString() !== 'true') ) ){
return;
}
Event.stop(event);
index = -1;
if( InkArray.inArray( tgtEl,this._headers ) ){
for( i=0; i<this._headers.length; i++ ){
if( this._headers[i] === tgtEl ){
index = i;
break;
}
}
}
if( !this._markupMode && paginated ){
for( var prop in this._sortableFields ){
if( prop !== ('col_' + index) ){
this._sortableFields[prop] = 'none';
this._headers[prop.replace('col_','')].innerHTML = InkString.stripTags(this._headers[prop.replace('col_','')].innerHTML);
}
}
if( this._sortableFields['col_'+index] === 'asc' )
{
this._sortableFields['col_'+index] = 'desc';
this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML) + '<i class="icon-caret-down"></i>';
} else {
this._sortableFields['col_'+index] = 'asc';
this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML) + '<i class="icon-caret-up"></i>';
}
this._pagination.setCurrent(this._pagination._current);
} else {
if( index === -1){
return;
}
if( (this._sortableFields['col_'+index] === 'desc') && (this._options.allowResetSorting && (this._options.allowResetSorting.toString() === 'true')) )
{
this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML);
this._sortableFields['col_'+index] = 'none';
// if( !found ){
this._data = this._originalData.slice(0);
// }
} else {
for( var prop in this._sortableFields ){
if( prop !== ('col_' + index) ){
this._sortableFields[prop] = 'none';
this._headers[prop.replace('col_','')].innerHTML = InkString.stripTags(this._headers[prop.replace('col_','')].innerHTML);
}
}
this._sort(index);
if( this._sortableFields['col_'+index] === 'asc' )
{
this._data.reverse();
this._sortableFields['col_'+index] = 'desc';
this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML) + '<i class="icon-caret-down"></i>';
} else {
this._sortableFields['col_'+index] = 'asc';
this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML) + '<i class="icon-caret-up"></i>';
}
}
var tbody = Selector.select('tbody',this._rootElement)[0];
Aux.cleanChildren(tbody);
InkArray.each(this._data,function(item){
tbody.appendChild(item);
});
this._pagination.setCurrent(0);
this._paginate(1);
}
},
/**
* Applies and/or changes the CSS classes in order to show the right columns
*
* @method _paginate
* @param {Number} page Current page
* @private
*/
_paginate: function( page ){
InkArray.each(this._data,Ink.bind(function(item, index){
if( (index >= ((page-1)*parseInt(this._options.pageSize,10))) && (index < (((page-1)*parseInt(this._options.pageSize,10))+parseInt(this._options.pageSize,10)) ) ){
Css.removeClassName(item,'hide-all');
} else {
Css.addClassName(item,'hide-all');
}
},this));
},
/**
* Sorts by a specific column.
*
* @method _sort
* @param {Number} index Column number (starting at 0)
* @private
*/
_sort: function( index ){
this._data.sort(Ink.bind(function(a,b){
var
aValue = Element.textContent(Selector.select('td',a)[index]),
bValue = Element.textContent(Selector.select('td',b)[index])
;
var regex = new RegExp(/\d/g);
if( !isNaN(aValue) && regex.test(aValue) ){
aValue = parseInt(aValue,10);
} else if( !isNaN(aValue) ){
aValue = parseFloat(aValue);
}
if( !isNaN(bValue) && regex.test(bValue) ){
bValue = parseInt(bValue,10);
} else if( !isNaN(bValue) ){
bValue = parseFloat(bValue);
}
if( aValue === bValue ){
return 0;
} else {
return ( ( aValue>bValue ) ? 1 : -1 );
}
},this));
},
/**
* Assembles the headers markup
*
* @method _setHeaders
* @param {Object} headers Key-value object that contains the fields as keys, their configuration (label and sorting ability) as value
* @private
*/
_setHeaders: function( headers, rows ){
var
field, header,
thead, tr, th,
index = 0
;
if( (thead = Selector.select('thead',this._rootElement)).length === 0 ){
thead = this._rootElement.createTHead();
tr = thead.insertRow(0);
for( field in headers ){
if (headers.hasOwnProperty(field)) {
if( !!this._options.visibleFields && (this._options.visibleFields.indexOf(field) === -1) ){
continue;
}
// th = tr.insertCell(index++);
th = document.createElement('th');
header = headers[field];
if( ("sortable" in header) && (header.sortable.toString() === 'true') ){
th.setAttribute('data-sortable','true');
}
if( ("label" in header) ){
Element.setTextContent(th, header.label);
}
this._originalFields.push(field);
tr.appendChild(th);
}
}
} else {
var firstLine = rows[0];
for( field in firstLine ){
if (firstLine.hasOwnProperty(field)) {
if( !!this._options.visibleFields && (this._options.visibleFields.indexOf(field) === -1) ){
continue;
}
this._originalFields.push(field);
}
}
}
},
/**
* Method that sets the handlers for the headers
*
* @method _setHeadersHandlers
* @private
*/
_setHeadersHandlers: function(){
/**
* Setting the sortable columns and its event listeners
*/
var theads = Selector.select('thead', this._rootElement);
if (!theads.length) {
return;
}
Event.observe(theads[0],'click',this._handlers.click);
this._headers = Selector.select('thead tr th',this._rootElement);
InkArray.each(this._headers,Ink.bind(function(item, index){
var dataset = Element.data( item );
if( ('sortable' in dataset) && (dataset.sortable.toString() === 'true') ){
this._sortableFields['col_' + index] = 'none';
}
}, this));
},
/**
* This method gets the rows from AJAX and places them as <tr> and <td>
*
* @method _setData
* @param {Object} rows Array of objects with the data to be showed
* @private
*/
_setData: function( rows ){
var
field,
tbody, tr, td,
trIndex,
tdIndex
;
tbody = Selector.select('tbody',this._rootElement);
if( tbody.length === 0){
tbody = document.createElement('tbody');
this._rootElement.appendChild( tbody );
} else {
tbody = tbody[0];
tbody.innerHTML = '';
}
this._data = [];
for( trIndex in rows ){
if (rows.hasOwnProperty(trIndex)) {
tr = document.createElement('tr');
tbody.appendChild( tr );
tdIndex = 0;
for( field in rows[trIndex] ){
if (rows[trIndex].hasOwnProperty(field)) {
if( !!this._options.visibleFields && (this._options.visibleFields.indexOf(field) === -1) ){
continue;
}
td = tr.insertCell(tdIndex++);
td.innerHTML = rows[trIndex][field];
}
}
this._data.push(tr);
}
}
this._originalData = this._data.slice(0);
},
/**
* Sets the endpoint. Useful for changing the endpoint in runtime.
*
* @method _setEndpoint
* @param {String} endpoint New endpoint
*/
setEndpoint: function( endpoint, currentPage ){
if( !this._markupMode ){
this._options.endpoint = endpoint;
this._pagination.setCurrent( (!!currentPage) ? parseInt(currentPage,10) : 0 );
}
},
/**
* Checks if it needs the pagination and creates the necessary markup to have pagination
*
* @method _setPagination
* @private
*/
_setPagination: function(){
var paginated = ( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') );
/**
* Set pagination if defined
*/
if( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') ){
/**
* Applying the pagination
*/
if( !this._pagination ){
this._pagination = document.createElement('nav');
this._pagination.className = 'ink-navigation';
this._rootElement.parentNode.insertBefore(this._pagination,this._rootElement.nextSibling);
this._pagination.appendChild( document.createElement('ul') ).className = 'pagination';
var Pagination = Ink.getModule('Ink.UI.Pagination',1);
this._pagination = new Pagination( this._pagination, {
size: Math.ceil(this._totalRows/this._options.pageSize),
onChange: Ink.bind(function( ){
this._getData( this._options.endpoint );
},this)
});
}
}
},
/**
* Method to choose which is the best way to get the data based on the endpoint:
* - AJAX
* - JSONP
*
* @method _getData
* @param {String} endpoint Valid endpoint
* @param {Boolean} [firstRequest] If true, will make the request set the headers onSuccess
* @private
*/
_getData: function( endpoint ){
Ink.requireModules(['Ink.Util.Url_1'],Ink.bind(function( InkURL ){
var
parsedURL = InkURL.parseUrl( endpoint ),
paginated = ( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') ),
pageNum = ((!!this._pagination) ? this._pagination._current+1 : 1)
;
if( parsedURL.query ){
parsedURL.query = parsedURL.query.split("&");
} else {
parsedURL.query = [];
}
if( !paginated ){
this._getDataViaAjax( endpoint );
} else {
parsedURL.query.push( 'rows_per_page=' + this._options.pageSize );
parsedURL.query.push( 'page=' + pageNum );
var sortStr = '';
for( var index in this._sortableFields ){
if( this._sortableFields[index] !== 'none' ){
parsedURL.query.push('sortField=' + this._originalFields[parseInt(index.replace('col_',''),10)]);
parsedURL.query.push('sortOrder=' + this._sortableFields[index]);
break;
}
}
this._getDataViaAjax( endpoint + '?' + parsedURL.query.join('&') );
}
},this));
},
/**
* Gets the data via AJAX and triggers the changes in the
*
* @param {[type]} endpoint [description]
* @param {[type]} firstRequest [description]
* @return {[type]} [description]
*/
_getDataViaAjax: function( endpoint ){
var paginated = ( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') );
new Ajax( endpoint, {
method: 'GET',
contentType: 'application/json',
sanitizeJSON: true,
onSuccess: Ink.bind(function( response ){
if( response.status === 200 ){
var jsonResponse = JSON.parse( response.responseText );
if( this._headers.length === 0 ){
this._setHeaders( jsonResponse.headers, jsonResponse.rows );
this._setHeadersHandlers();
}
this._setData( jsonResponse.rows );
if( paginated ){
if( !!this._totalRows && (parseInt(jsonResponse.totalRows,10) !== parseInt(this._totalRows,10)) ){
this._totalRows = jsonResponse.totalRows;
this._pagination.setSize( Math.ceil(this._totalRows/this._options.pageSize) );
} else {
this._totalRows = jsonResponse.totalRows;
}
} else {
if( !!this._totalRows && (jsonResponse.rows.length !== parseInt(this._totalRows,10)) ){
this._totalRows = jsonResponse.rows.length;
this._pagination.setSize( Math.ceil(this._totalRows/this._options.pageSize) );
} else {
this._totalRows = jsonResponse.rows.length;
}
}
this._setPagination( );
}
},this)
} );
}
};
return Table;
});
/**
* @module Ink.UI.Tabs_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.Tabs', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) {
'use strict';
/**
* Tabs component
*
* @class Ink.UI.Tabs
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {Boolean} [options.preventUrlChange] Flag that determines if follows the link on click or stops the event
* @param {String} [options.active] ID of the tab to activate on creation
* @param {Array} [options.disabled] IDs of the tabs that will be disabled on creation
* @param {Function} [options.onBeforeChange] callback to be executed before changing tabs
* @param {Function} [options.onChange] callback to be executed after changing tabs
* @example
* <div class="ink-tabs top"> <!-- replace 'top' with 'bottom', 'left' or 'right' to place navigation -->
*
* <!-- put navigation first if using top, left or right positioning -->
* <ul class="tabs-nav">
* <li><a href="#home">Home</a></li>
* <li><a href="#news">News</a></li>
* <li><a href="#description">Description</a></li>
* <li><a href="#stuff">Stuff</a></li>
* <li><a href="#more_stuff">More stuff</a></li>
* </ul>
*
* <!-- Put your content second if using top, left or right navigation -->
* <div id="home" class="tabs-content"><p>Content</p></div>
* <div id="news" class="tabs-content"><p>Content</p></div>
* <div id="description" class="tabs-content"><p>Content</p></div>
* <div id="stuff" class="tabs-content"><p>Content</p></div>
* <div id="more_stuff" class="tabs-content"><p>Content</p></div>
* <!-- If you're using bottom navigation, switch the nav block with the content blocks -->
*
* </div>
* <script>
* Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Tabs_1'], function( Selector, Tabs ){
* var tabsElement = Ink.s('.ink-tabs');
* var tabsObj = new Tabs( tabsElement );
* });
* </script>
*/
var Tabs = function(selector, options) {
if (!Aux.isDOMElement(selector)) {
selector = Selector.select(selector);
if (selector.length === 0) { throw new TypeError('1st argument must either be a DOM Element or a selector expression!'); }
this._element = selector[0];
} else {
this._element = selector;
}
this._options = Ink.extendObj({
preventUrlChange: false,
active: undefined,
disabled: [],
onBeforeChange: undefined,
onChange: undefined
}, Element.data(selector));
this._options = Ink.extendObj(this._options,options || {});
this._handlers = {
tabClicked: Ink.bindEvent(this._onTabClicked,this),
disabledTabClicked: Ink.bindEvent(this._onDisabledTabClicked,this),
resize: Ink.bindEvent(this._onResize,this)
};
this._init();
};
Tabs.prototype = {
/**
* Init function called by the constructor
*
* @method _init
* @private
*/
_init: function() {
this._menu = Selector.select('.tabs-nav', this._element)[0];
this._menuTabs = this._getChildElements(this._menu);
this._contentTabs = Selector.select('.tabs-content', this._element);
//initialization of the tabs, hides all content before setting the active tab
this._initializeDom();
// subscribe events
this._observe();
//sets the first active tab
this._setFirstActive();
//shows the active tab
this._changeTab(this._activeMenuLink);
this._handlers.resize();
Aux.registerInstance(this, this._element, 'tabs');
},
/**
* Initialization of the tabs, hides all content before setting the active tab
*
* @method _initializeDom
* @private
*/
_initializeDom: function(){
for(var i = 0; i < this._contentTabs.length; i++){
Css.hide(this._contentTabs[i]);
}
},
/**
* Subscribe events
*
* @method _observe
* @private
*/
_observe: function() {
InkArray.each(this._menuTabs,Ink.bind(function(elem){
var link = Selector.select('a', elem)[0];
if(InkArray.inArray(link.getAttribute('href'), this._options.disabled)){
this.disable(link);
} else {
this.enable(link);
}
},this));
Event.observe(window, 'resize', this._handlers.resize);
},
/**
* Run at instantiation, to determine which is the first active tab
* fallsback from window.location.href to options.active to the first not disabled tab
*
* @method _setFirstActive
* @private
*/
_setFirstActive: function() {
var hash = window.location.hash;
this._activeContentTab = Selector.select(hash, this._element)[0] ||
Selector.select(this._hashify(this._options.active), this._element)[0] ||
Selector.select('.tabs-content', this._element)[0];
this._activeMenuLink = this._findLinkByHref(this._activeContentTab.getAttribute('id'));
this._activeMenuTab = this._activeMenuLink.parentNode;
},
/**
* Changes to the desired tab
*
* @method _changeTab
* @param {DOMElement} link anchor linking to the content container
* @param {boolean} runCallbacks defines if the callbacks should be run or not
* @private
*/
_changeTab: function(link, runCallbacks){
if(runCallbacks && typeof this._options.onBeforeChange !== 'undefined'){
this._options.onBeforeChange(this);
}
var selector = link.getAttribute('href');
Css.removeClassName(this._activeMenuTab, 'active');
Css.removeClassName(this._activeContentTab, 'active');
Css.addClassName(this._activeContentTab, 'hide-all');
this._activeMenuLink = link;
this._activeMenuTab = this._activeMenuLink.parentNode;
this._activeContentTab = Selector.select(selector.substr(selector.indexOf('#')), this._element)[0];
Css.addClassName(this._activeMenuTab, 'active');
Css.addClassName(this._activeContentTab, 'active');
Css.removeClassName(this._activeContentTab, 'hide-all');
Css.show(this._activeContentTab);
if(runCallbacks && typeof(this._options.onChange) !== 'undefined'){
this._options.onChange(this);
}
},
/**
* Tab clicked handler
*
* @method _onTabClicked
* @param {Event} ev
* @private
*/
_onTabClicked: function(ev) {
Event.stop(ev);
var target = Event.findElement(ev, 'A');
if(target.nodeName.toLowerCase() !== 'a') {
return;
}
if( this._options.preventUrlChange.toString() !== 'true'){
window.location.hash = target.getAttribute('href').substr(target.getAttribute('href').indexOf('#'));
}
if(target === this._activeMenuLink){
return;
}
this.changeTab(target);
},
/**
* Disabled tab clicked handler
*
* @method _onDisabledTabClicked
* @param {Event} ev
* @private
*/
_onDisabledTabClicked: function(ev) {
Event.stop(ev);
},
/**
* Resize handler
*
* @method _onResize
* @private
*/
_onResize: function(){
var currentLayout = Aux.currentLayout();
if(currentLayout === this._lastLayout){
return;
}
if(currentLayout === Aux.Layouts.SMALL || currentLayout === Aux.Layouts.MEDIUM){
Css.removeClassName(this._menu, 'menu');
Css.removeClassName(this._menu, 'horizontal');
// Css.addClassName(this._menu, 'pills');
} else {
Css.addClassName(this._menu, 'menu');
Css.addClassName(this._menu, 'horizontal');
// Css.removeClassName(this._menu, 'pills');
}
this._lastLayout = currentLayout;
},
/*****************
* Aux Functions *
*****************/
/**
* Allows the hash to be passed with or without the cardinal sign
*
* @method _hashify
* @param {String} hash the string to be hashified
* @return {String} Resulting hash
* @private
*/
_hashify: function(hash){
if(!hash){
return "";
}
return hash.indexOf('#') === 0? hash : '#' + hash;
},
/**
* Returns the anchor with the desired href
*
* @method _findLinkBuHref
* @param {String} href the href to be found on the returned link
* @return {String|undefined} [description]
* @private
*/
_findLinkByHref: function(href){
href = this._hashify(href);
var ret;
InkArray.each(this._menuTabs,Ink.bind(function(elem){
var link = Selector.select('a', elem)[0];
if( (link.getAttribute('href').indexOf('#') !== -1) && ( link.getAttribute('href').substr(link.getAttribute('href').indexOf('#')) === href ) ){
ret = link;
}
},this));
return ret;
},
/**
* Returns the child elements of a given parent element
*
* @method _getChildElements
* @param {DOMElement} parent DOMElement to fetch the child elements from.
* @return {Array} Child elements of the given parent.
* @private
*/
_getChildElements: function(parent){
var childNodes = [];
var children = parent.children;
for(var i = 0; i < children.length; i++){
if(children[i].nodeType === 1){
childNodes.push(children[i]);
}
}
return childNodes;
},
/**************
* PUBLIC API *
**************/
/**
* Changes to the desired tag
*
* @method changeTab
* @param {String|DOMElement} selector the id of the desired tab or the link that links to it
* @public
*/
changeTab: function(selector) {
var element = (selector.nodeType === 1)? selector : this._findLinkByHref(this._hashify(selector));
if(!element || Css.hasClassName(element, 'ink-disabled')){
return;
}
this._changeTab(element, true);
},
/**
* Disables the desired tag
*
* @method disable
* @param {String|DOMElement} selector the id of the desired tab or the link that links to it
* @public
*/
disable: function(selector){
var element = (selector.nodeType === 1)? selector : this._findLinkByHref(this._hashify(selector));
if(!element){
return;
}
Event.stopObserving(element, 'click', this._handlers.tabClicked);
Event.observe(element, 'click', this._handlers.disabledTabClicked);
Css.addClassName(element, 'ink-disabled');
},
/**
* Enables the desired tag
*
* @method enable
* @param {String|DOMElement} selector the id of the desired tab or the link that links to it
* @public
*/
enable: function(selector){
var element = (selector.nodeType === 1)? selector : this._findLinkByHref(this._hashify(selector));
if(!element){
return;
}
Event.stopObserving(element, 'click', this._handlers.disabledTabClicked);
Event.observe(element, 'click', this._handlers.tabClicked);
Css.removeClassName(element, 'ink-disabled');
},
/***********
* Getters *
***********/
/**
* Returns the active tab id
*
* @method activeTab
* @return {String} ID of the active tab.
* @public
*/
activeTab: function(){
return this._activeContentTab.getAttribute('id');
},
/**
* Returns the current active Menu LI
*
* @method activeMenuTab
* @return {DOMElement} Active menu LI.
* @public
*/
activeMenuTab: function(){
return this._activeMenuTab;
},
/**
* Returns the current active Menu anchorChanges to the desired tag
*
* @method activeMenuLink
* @return {DOMElement} Active menu link
* @public
*/
activeMenuLink: function(){
return this._activeMenuLink;
},
/**
* Returns the current active Content Tab
*
* @method activeContentTab
* @return {DOMElement} Active Content Tab
* @public
*/
activeContentTab: function(){
return this._activeContentTab;
},
/**
* Unregisters the component and removes its markup from the DOM
*
* @method destroy
* @public
*/
destroy: Aux.destroyComponent
};
return Tabs;
});
/**
* @module Ink.UI.Toggle_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.Toggle', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) {
'use strict';
/**
* Toggle component
*
* @class Ink.UI.Toggle
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {String} options.target CSS Selector that specifies the elements that will toggle
* @param {String} [options.triggerEvent] Event that will trigger the toggling. Default is 'click'
* @param {Boolean} [options.closeOnClick] Flag that determines if, when clicking outside of the toggled content, it should hide it. Default: true.
* @example
* <div class="ink-dropdown">
* <button class="ink-button toggle" data-target="#dropdown">Dropdown <span class="icon-caret-down"></span></button>
* <ul id="dropdown" class="dropdown-menu">
* <li class="heading">Heading</li>
* <li class="separator-above"><a href="#">Option</a></li>
* <li><a href="#">Option</a></li>
* <li class="separator-above disabled"><a href="#">Disabled option</a></li>
* <li class="submenu">
* <a href="#" class="toggle" data-target="#submenu1">A longer option name</a>
* <ul id="submenu1" class="dropdown-menu">
* <li class="submenu">
* <a href="#" class="toggle" data-target="#ultrasubmenu">Sub option</a>
* <ul id="ultrasubmenu" class="dropdown-menu">
* <li><a href="#">Sub option</a></li>
* <li><a href="#" data-target="ultrasubmenu">Sub option</a></li>
* <li><a href="#">Sub option</a></li>
* </ul>
* </li>
* <li><a href="#">Sub option</a></li>
* <li><a href="#">Sub option</a></li>
* </ul>
* </li>
* <li><a href="#">Option</a></li>
* </ul>
* </div>
* <script>
* Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Toggle_1'], function( Selector, Toggle ){
* var toggleElement = Ink.s('.toggle');
* var toggleObj = new Toggle( toggleElement );
* });
* </script>
*/
var Toggle = function( selector, options ){
if( typeof selector !== 'string' && typeof selector !== 'object' ){
throw '[Ink.UI.Toggle] Invalid CSS selector to determine the root element';
}
if( typeof selector === 'string' ){
this._rootElement = Selector.select( selector );
if( this._rootElement.length <= 0 ){
throw '[Ink.UI.Toggle] Root element not found';
}
this._rootElement = this._rootElement[0];
} else {
this._rootElement = selector;
}
this._options = Ink.extendObj({
target : undefined,
triggerEvent: 'click',
closeOnClick: true
},Element.data(this._rootElement));
this._options = Ink.extendObj(this._options,options || {});
this._targets = (function (target) {
if (typeof target === 'string') {
return Selector.select(target);
} else if (typeof target === 'object') {
if (target.constructor === Array) {
return target;
} else {
return [target];
}
}
}(this._options.target));
if (!this._targets.length) {
throw '[Ink.UI.Toggle] Toggle target was not found! Supply a valid selector, array, or element through the `target` option.';
}
this._init();
};
Toggle.prototype = {
/**
* Init function called by the constructor
*
* @method _init
* @private
*/
_init: function(){
this._accordion = ( Css.hasClassName(this._rootElement.parentNode,'accordion') || Css.hasClassName(this._targets[0].parentNode,'accordion') );
Event.observe( this._rootElement, this._options.triggerEvent, Ink.bindEvent(this._onTriggerEvent,this) );
if( this._options.closeOnClick.toString() === 'true' ){
Event.observe( document, 'click', Ink.bindEvent(this._onClick,this));
}
},
/**
* Event handler. It's responsible for handling the <triggerEvent> defined in the options.
* This will trigger the toggle.
*
* @method _onTriggerEvent
* @param {Event} event
* @private
*/
_onTriggerEvent: function( event ){
if( this._accordion ){
var elms, i, accordionElement;
if( Css.hasClassName(this._targets[0].parentNode,'accordion') ){
accordionElement = this._targets[0].parentNode;
} else {
accordionElement = this._targets[0].parentNode.parentNode;
}
elms = Selector.select('.toggle',accordionElement);
for( i=0; i<elms.length; i+=1 ){
var
dataset = Element.data( elms[i] ),
targetElm = Selector.select( dataset.target,accordionElement )
;
if( (targetElm.length > 0) && (targetElm[0] !== this._targets[0]) ){
targetElm[0].style.display = 'none';
}
}
}
var finalClass,
finalDisplay;
for (var j = 0, len = this._targets.length; j < len; j++) {
finalClass = ( Css.getStyle(this._targets[j],'display') === 'none') ? 'show-all' : 'hide-all';
finalDisplay = ( Css.getStyle(this._targets[j],'display') === 'none') ? 'block' : 'none';
Css.removeClassName(this._targets[j],'show-all');
Css.removeClassName(this._targets[j], 'hide-all');
Css.addClassName(this._targets[j], finalClass);
this._targets[j].style.display = finalDisplay;
}
if( finalClass === 'show-all' ){
Css.addClassName(this._rootElement,'active');
} else {
Css.removeClassName(this._rootElement,'active');
}
},
/**
* Click handler. Will handle clicks outside the toggle component.
*
* @method _onClick
* @param {Event} event
* @private
*/
_onClick: function( event ){
var
tgtEl = Event.element(event),
shades
;
var ancestorOfTargets = InkArray.some(this._targets, function (target) {
return Element.isAncestorOf(target, tgtEl);
});
if( (this._rootElement === tgtEl) || Element.isAncestorOf(this._rootElement, tgtEl) || ancestorOfTargets ) {
return;
} else if( (shades = Ink.ss('.ink-shade')).length ) {
var
shadesLength = shades.length
;
for( var i = 0; i < shadesLength; i++ ){
if( Element.isAncestorOf(shades[i],tgtEl) && Element.isAncestorOf(shades[i],this._rootElement) ){
return;
}
}
}
if(!Element.findUpwardsByClass(tgtEl, 'toggle')) {
return;
}
this._dismiss( this._rootElement );
},
/**
* Dismisses the toggling.
*
* @method _dismiss
* @private
*/
_dismiss: function(){
if( ( Css.getStyle(this._targets[0],'display') === 'none') ){
return;
}
for (var i = 0, len = this._targets.length; i < len; i++) {
Css.removeClassName(this._targets[i], 'show-all');
Css.addClassName(this._targets[i], 'hide-all');
this._targets[i].style.display = 'none';
}
Css.removeClassName(this._rootElement,'active');
}
};
return Toggle;
});
/**
* @module Ink.UI.Tooltip_1
* @author inkdev AT sapo.pt
*/
Ink.createModule('Ink.UI.Tooltip', '1', ['Ink.UI.Aux_1', 'Ink.Dom.Event_1', 'Ink.Dom.Element_1', 'Ink.Dom.Selector_1', 'Ink.Util.Array_1', 'Ink.Dom.Css_1', 'Ink.Dom.Browser_1'], function (Aux, InkEvent, InkElement, Selector, InkArray, Css) {
'use strict';
/**
* @class Ink.UI.Tooltip
* @constructor
*
* @param {DOMElement|String} target Target element or selector of elements, to display the tooltips on.
* @param {Object} [options]
* @param [options.text=''] Text content for the tooltip.
* @param [options.where='up'] Positioning for the tooltip. Options:
* @param options.where.up/down/left/right Place above, below, to the left of, or to the right of, the target. Show an arrow.
* @param options.where.mousemove Place the tooltip to the bottom and to the right of the mouse when it hovers the element, and follow the mouse as it moves.
* @param options.where.mousefix Place the tooltip to the bottom and to the right of the mouse when it hovers the element, keep the tooltip there motionless.
*
* @param [options.color=''] Color of the tooltip. Options are red, orange, blue, green and black. Default is white.
* @param [options.fade=0.3] Fade time; Duration of the fade in/out effect.
* @param [options.forever=0] Set to 1/true to prevent the tooltip from being erased when the mouse hovers away from the target
* @param [options.timeout=0] Time for the tooltip to live. Useful together with [options.forever].
* @param [options.delay] Time the tooltip waits until it is displayed. Useful to avoid getting the attention of the user unnecessarily
* @param [options.template=null] Element or selector containing HTML to be cloned into the tooltips. Can be a hidden element, because CSS `display` is set to `block`.
* @param [options.templatefield=null] Selector within the template element to choose where the text is inserted into the tooltip. Useful when a wrapper DIV is required.
*
* @param [options.left,top=10] (Nitty-gritty) Spacing from the target to the tooltip, when `where` is `mousemove` or `mousefix`
* @param [options.spacing=8] (Nitty-gritty) Spacing between the tooltip and the target element, when `where` is `up`, `down`, `left`, or `right`
*
* @example
* <ul class="buttons">
* <li class="button" data-tip-text="Create a new document">New</li>
* <li class="button" data-tip-text="Exit the program">Quit</li>
* <li class="button" data-tip-text="Save the document you are working on">Save</li>
* </ul>
*
* [...]
*
* <script>
* Ink.requireModules(['Ink.UI.Tooltip_1'], function (Tooltip) {
* new Tooltip('.button', {where: 'mousefix'});
* });
* </script>
*/
function Tooltip(element, options) {
this._init(element, options || {});
}
function EachTooltip(root, elm) {
this._init(root, elm);
}
var transitionDurationName,
transitionPropertyName,
transitionTimingFunctionName;
(function () { // Feature detection
var test = document.createElement('DIV');
var names = ['transition', 'oTransition', 'msTransition', 'mozTransition',
'webkitTransition'];
for (var i = 0; i < names.length; i++) {
if (typeof test.style[names[i] + 'Duration'] !== 'undefined') {
transitionDurationName = names[i] + 'Duration';
transitionPropertyName = names[i] + 'Property';
transitionTimingFunctionName = names[i] + 'TimingFunction';
break;
}
}
}());
// Body or documentElement
var bodies = document.getElementsByTagName('body');
var body = bodies && bodies.length ? bodies[0] : document.documentElement;
Tooltip.prototype = {
_init: function(element, options) {
var elements;
this.options = Ink.extendObj({
where: 'up',
zIndex: 10000,
left: 10,
top: 10,
spacing: 8,
forever: 0,
color: '',
timeout: 0,
delay: 0,
template: null,
templatefield: null,
fade: 0.3,
text: ''
}, options || {});
if (typeof element === 'string') {
elements = Selector.select(element);
} else if (typeof element === 'object') {
elements = [element];
} else {
throw 'Element expected';
}
this.tooltips = [];
for (var i = 0, len = elements.length; i < len; i++) {
this.tooltips[i] = new EachTooltip(this, elements[i]);
}
},
/**
* Destroys the tooltips created by this instance
*
* @method destroy
*/
destroy: function () {
InkArray.each(this.tooltips, function (tooltip) {
tooltip._destroy();
});
this.tooltips = null;
this.options = null;
}
};
EachTooltip.prototype = {
_oppositeDirections: {
left: 'right',
right: 'left',
up: 'down',
down: 'up'
},
_init: function(root, elm) {
InkEvent.observe(elm, 'mouseover', Ink.bindEvent(this._onMouseOver, this));
InkEvent.observe(elm, 'mouseout', Ink.bindEvent(this._onMouseOut, this));
InkEvent.observe(elm, 'mousemove', Ink.bindEvent(this._onMouseMove, this));
this.root = root;
this.element = elm;
this._delayTimeout = null;
this.tooltip = null;
},
_makeTooltip: function (mousePosition) {
if (!this._getOpt('text')) {
return false;
}
var tooltip = this._createTooltipElement();
if (this.tooltip) {
this._removeTooltip();
}
this.tooltip = tooltip;
this._fadeInTooltipElement(tooltip);
this._placeTooltipElement(tooltip, mousePosition);
InkEvent.observe(tooltip, 'mouseover', Ink.bindEvent(this._onTooltipMouseOver, this));
var timeout = this._getFloatOpt('timeout');
if (timeout) {
setTimeout(Ink.bind(function () {
if (this.tooltip === tooltip) {
this._removeTooltip();
}
}, this), timeout * 1000);
}
},
_createTooltipElement: function () {
var template = this._getOpt('template'), // User template instead of our HTML
templatefield = this._getOpt('templatefield'),
tooltip, // The element we float
field; // Element where we write our message. Child or same as the above
if (template) { // The user told us of a template to use. We copy it.
var temp = document.createElement('DIV');
temp.innerHTML = Aux.elOrSelector(template, 'options.template').outerHTML;
tooltip = temp.firstChild;
if (templatefield) {
field = Selector.select(templatefield, tooltip);
if (field) {
field = field[0];
} else {
throw 'options.templatefield must be a valid selector within options.template';
}
} else {
field = tooltip; // Assume same element if user did not specify a field
}
} else { // We create the default structure
tooltip = document.createElement('DIV');
Css.addClassName(tooltip, 'ink-tooltip');
Css.addClassName(tooltip, this._getOpt('color'));
field = document.createElement('DIV');
Css.addClassName(field, 'content');
tooltip.appendChild(field);
}
InkElement.setTextContent(field, this._getOpt('text'));
tooltip.style.display = 'block';
tooltip.style.position = 'absolute';
tooltip.style.zIndex = this._getIntOpt('zIndex');
return tooltip;
},
_fadeInTooltipElement: function (tooltip) {
var fadeTime = this._getFloatOpt('fade');
if (transitionDurationName && fadeTime) {
tooltip.style.opacity = '0';
tooltip.style[transitionDurationName] = fadeTime + 's';
tooltip.style[transitionPropertyName] = 'opacity';
tooltip.style[transitionTimingFunctionName] = 'ease-in-out';
setTimeout(function () {
tooltip.style.opacity = '1';
}, 0);
}
},
_placeTooltipElement: function (tooltip, mousePosition) {
var where = this._getOpt('where');
if (where === 'mousemove' || where === 'mousefix') {
var mPos = mousePosition;
this._setPos(mPos[0], mPos[1]);
body.appendChild(tooltip);
} else if (where.match(/(up|down|left|right)/)) {
body.appendChild(tooltip);
var targetElementPos = InkElement.offset(this.element);
var tleft = targetElementPos[0],
ttop = targetElementPos[1];
if (tleft instanceof Array) { // Work around a bug in Ink.Dom.Element.offsetLeft which made it return the result of offset() instead. TODO remove this check when fix is merged
ttop = tleft[1];
tleft = tleft[0];
}
var centerh = (InkElement.elementWidth(this.element) / 2) - (InkElement.elementWidth(tooltip) / 2),
centerv = (InkElement.elementHeight(this.element) / 2) - (InkElement.elementHeight(tooltip) / 2);
var spacing = this._getIntOpt('spacing');
var tooltipDims = InkElement.elementDimensions(tooltip);
var elementDims = InkElement.elementDimensions(this.element);
var maxX = InkElement.scrollWidth() + InkElement.viewportWidth();
var maxY = InkElement.scrollHeight() + InkElement.viewportHeight();
if (where === 'left' && tleft - tooltipDims[0] < 0) {
where = 'right';
} else if (where === 'right' && tleft + tooltipDims[0] > maxX) {
where = 'left';
} else if (where === 'up' && ttop - tooltipDims[1] < 0) {
where = 'down';
} else if (where === 'down' && ttop + tooltipDims[1] > maxY) {
where = 'up';
}
if (where === 'up') {
ttop -= tooltipDims[1];
ttop -= spacing;
tleft += centerh;
} else if (where === 'down') {
ttop += elementDims[1];
ttop += spacing;
tleft += centerh;
} else if (where === 'left') {
tleft -= tooltipDims[0];
tleft -= spacing;
ttop += centerv;
} else if (where === 'right') {
tleft += elementDims[0];
tleft += spacing;
ttop += centerv;
}
var arrow = null;
if (where.match(/(up|down|left|right)/)) {
arrow = document.createElement('SPAN');
Css.addClassName(arrow, 'arrow');
Css.addClassName(arrow, this._oppositeDirections[where]);
tooltip.appendChild(arrow);
}
var scrl = this._getLocalScroll();
var tooltipLeft = tleft - scrl[0];
var tooltipTop = ttop - scrl[1];
var toBottom = (tooltipTop + tooltipDims[1]) - maxY;
var toRight = (tooltipLeft + tooltipDims[0]) - maxX;
var toLeft = 0 - tooltipLeft;
var toTop = 0 - tooltipTop;
if (toBottom > 0) {
if (arrow) { arrow.style.top = (tooltipDims[1] / 2) + toBottom + 'px'; }
tooltipTop -= toBottom;
} else if (toTop > 0) {
if (arrow) { arrow.style.top = (tooltipDims[1] / 2) - toTop + 'px'; }
tooltipTop += toTop;
} else if (toRight > 0) {
if (arrow) { arrow.style.left = (tooltipDims[0] / 2) + toRight + 'px'; }
tooltipLeft -= toRight;
} else if (toLeft > 0) {
if (arrow) { arrow.style.left = (tooltipDims[0] / 2) - toLeft + 'px'; }
tooltipLeft += toLeft;
}
tooltip.style.left = tooltipLeft + 'px';
tooltip.style.top = tooltipTop + 'px';
}
},
_removeTooltip: function() {
var tooltip = this.tooltip;
if (!tooltip) {return;}
var remove = Ink.bind(InkElement.remove, {}, tooltip);
if (this._getOpt('where') !== 'mousemove' && transitionDurationName) {
tooltip.style.opacity = 0;
// remove() will operate on correct tooltip, although this.tooltip === null then
setTimeout(remove, this._getFloatOpt('fade') * 1000);
} else {
remove();
}
this.tooltip = null;
},
_getOpt: function (option) {
var dataAttrVal = InkElement.data(this.element)[InkElement._camelCase('tip-' + option)];
if (dataAttrVal /* either null or "" may signify the absense of this attribute*/) {
return dataAttrVal;
}
var instanceOption = this.root.options[option];
if (typeof instanceOption !== 'undefined') {
return instanceOption;
}
},
_getIntOpt: function (option) {
return parseInt(this._getOpt(option), 10);
},
_getFloatOpt: function (option) {
return parseFloat(this._getOpt(option), 10);
},
_destroy: function () {
if (this.tooltip) {
InkElement.remove(this.tooltip);
}
this.root = null; // Cyclic reference = memory leaks
this.element = null;
this.tooltip = null;
},
_onMouseOver: function(e) {
// on IE < 10 you can't access the mouse event not even a tick after it fired
var mousePosition = this._getMousePosition(e);
var delay = this._getFloatOpt('delay');
if (delay) {
this._delayTimeout = setTimeout(Ink.bind(function () {
if (!this.tooltip) {
this._makeTooltip(mousePosition);
}
this._delayTimeout = null;
}, this), delay * 1000);
} else {
this._makeTooltip(mousePosition);
}
},
_onMouseMove: function(e) {
if (this._getOpt('where') === 'mousemove' && this.tooltip) {
var mPos = this._getMousePosition(e);
this._setPos(mPos[0], mPos[1]);
}
},
_onMouseOut: function () {
if (!this._getIntOpt('forever')) {
this._removeTooltip();
}
if (this._delayTimeout) {
clearTimeout(this._delayTimeout);
this._delayTimeout = null;
}
},
_onTooltipMouseOver: function () {
if (this.tooltip) { // If tooltip is already being removed, this has no effect
this._removeTooltip();
}
},
_setPos: function(left, top) {
left += this._getIntOpt('left');
top += this._getIntOpt('top');
var pageDims = this._getPageXY();
if (this.tooltip) {
var elmDims = [InkElement.elementWidth(this.tooltip), InkElement.elementHeight(this.tooltip)];
var scrollDim = this._getScroll();
if((elmDims[0] + left - scrollDim[0]) >= (pageDims[0] - 20)) {
left = (left - elmDims[0] - this._getIntOpt('left') - 10);
}
if((elmDims[1] + top - scrollDim[1]) >= (pageDims[1] - 20)) {
top = (top - elmDims[1] - this._getIntOpt('top') - 10);
}
this.tooltip.style.left = left + 'px';
this.tooltip.style.top = top + 'px';
}
},
_getPageXY: function() {
var cWidth = 0;
var cHeight = 0;
if( typeof( window.innerWidth ) === 'number' ) {
cWidth = window.innerWidth;
cHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
cWidth = document.documentElement.clientWidth;
cHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
cWidth = document.body.clientWidth;
cHeight = document.body.clientHeight;
}
return [parseInt(cWidth, 10), parseInt(cHeight, 10)];
},
_getScroll: function() {
var dd = document.documentElement, db = document.body;
if (dd && (dd.scrollLeft || dd.scrollTop)) {
return [dd.scrollLeft, dd.scrollTop];
} else if (db) {
return [db.scrollLeft, db.scrollTop];
} else {
return [0, 0];
}
},
_getLocalScroll: function () {
var cumScroll = [0, 0];
var cursor = this.element.parentNode;
var left, top;
while (cursor && cursor !== document.documentElement && cursor !== document.body) {
left = cursor.scrollLeft;
top = cursor.scrollTop;
if (left) {
cumScroll[0] += left;
}
if (top) {
cumScroll[1] += top;
}
cursor = cursor.parentNode;
}
return cumScroll;
},
_getMousePosition: function(e) {
return [parseInt(InkEvent.pointerX(e), 10), parseInt(InkEvent.pointerY(e), 10)];
}
};
return Tooltip;
});
/**
* @module Ink.UI.TreeView_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.TreeView', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) {
'use strict';
/**
* TreeView is an Ink's component responsible for presenting a defined set of elements in a tree-like hierarchical structure
*
* @class Ink.UI.TreeView
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {String} options.node CSS selector that identifies the elements that are considered nodes.
* @param {String} options.child CSS selector that identifies the elements that are children of those nodes.
* @example
* <ul class="ink-tree-view">
* <li class="open"><span></span><a href="#">root</a>
* <ul>
* <li><a href="">child 1</a></li>
* <li><span></span><a href="">child 2</a>
* <ul>
* <li><a href="">grandchild 2a</a></li>
* <li><span></span><a href="">grandchild 2b</a>
* <ul>
* <li><a href="">grandgrandchild 1bA</a></li>
* <li><a href="">grandgrandchild 1bB</a></li>
* </ul>
* </li>
* </ul>
* </li>
* <li><a href="">child 3</a></li>
* </ul>
* </li>
* </ul>
* <script>
* Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.TreeView_1'], function( Selector, TreeView ){
* var treeViewElement = Ink.s('.ink-tree-view');
* var treeViewObj = new TreeView( treeViewElement );
* });
* </script>
*/
var TreeView = function(selector, options){
/**
* Gets the element
*/
if( !Aux.isDOMElement(selector) && (typeof selector !== 'string') ){
throw '[Ink.UI.TreeView] :: Invalid selector';
} else if( typeof selector === 'string' ){
this._element = Selector.select( selector );
if( this._element.length < 1 ){
throw '[Ink.UI.TreeView] :: Selector has returned no elements';
}
this._element = this._element[0];
} else {
this._element = selector;
}
/**
* Default options and they're overrided by data-attributes if any.
* The parameters are:
* @param {string} node Selector to define which elements are seen as nodes. Default: li
* @param {string} child Selector to define which elements are represented as childs. Default: ul
*/
this._options = Ink.extendObj({
node: 'li',
child: 'ul'
},Element.data(this._element));
this._options = Ink.extendObj(this._options, options || {});
this._init();
};
TreeView.prototype = {
/**
* Init function called by the constructor. Sets the necessary event handlers.
*
* @method _init
* @private
*/
_init: function(){
this._handlers = {
click: Ink.bindEvent(this._onClick,this)
};
Event.observe(this._element, 'click', this._handlers.click);
var
nodes = Selector.select(this._options.node,this._element),
children
;
InkArray.each(nodes,Ink.bind(function(item){
if( Css.hasClassName(item,'open') )
{
return;
}
if( !Css.hasClassName(item, 'closed') ){
Css.addClassName(item,'closed');
}
children = Selector.select(this._options.child,item);
InkArray.each(children,Ink.bind(function( inner_item ){
if( !Css.hasClassName(inner_item, 'hide-all') ){
Css.addClassName(inner_item,'hide-all');
}
},this));
},this));
},
/**
* Handles the click event (as specified in the _init function).
*
* @method _onClick
* @param {Event} event
* @private
*/
_onClick: function(event){
/**
* Summary:
* If the clicked element is a "node" as defined in the options, will check if it has any "child".
* If so, will show it or hide it, depending on its current state. And will stop the event's default behavior.
* If not, will execute the event's default behavior.
*
*/
var tgtEl = Event.element(event);
if( this._options.node[0] === '.' ) {
if( !Css.hasClassName(tgtEl,this._options.node.substr(1)) ){
while( (!Css.hasClassName(tgtEl,this._options.node.substr(1))) && (tgtEl.nodeName.toLowerCase() !== 'body') ){
tgtEl = tgtEl.parentNode;
}
}
} else if( this._options.node[0] === '#' ){
if( tgtEl.id !== this._options.node.substr(1) ){
while( (tgtEl.id !== this._options.node.substr(1)) && (tgtEl.nodeName.toLowerCase() !== 'body') ){
tgtEl = tgtEl.parentNode;
}
}
} else {
if( tgtEl.nodeName.toLowerCase() !== this._options.node ){
while( (tgtEl.nodeName.toLowerCase() !== this._options.node) && (tgtEl.nodeName.toLowerCase() !== 'body') ){
tgtEl = tgtEl.parentNode;
}
}
}
if(tgtEl.nodeName.toLowerCase() === 'body'){ return; }
var child = Selector.select(this._options.child,tgtEl);
if( child.length > 0 ){
Event.stop(event);
child = child[0];
if( Css.hasClassName(child,'hide-all') ){ Css.removeClassName(child,'hide-all'); Css.addClassName(tgtEl,'open'); Css.removeClassName(tgtEl,'closed'); }
else { Css.addClassName(child,'hide-all'); Css.removeClassName(tgtEl,'open'); Css.addClassName(tgtEl,'closed'); }
}
}
};
return TreeView;
});
/**
* @module Ink.UI.SmoothScroller_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.SmoothScroller', '1', ['Ink.Dom.Event_1','Ink.Dom.Selector_1','Ink.Dom.Loaded_1'], function(Event, Selector, Loaded ) {
'use strict';
/**
* @class Ink.UI.SmoothScroller
* @version 1
* @static
*/
var SmoothScroller = {
/**
* Sets the speed of the scrolling
*
* @property speed
* @type {Number}
* @readOnly
* @static
*/
speed: 10,
/**
* Returns the Y position of the div
*
* @method gy
* @param {DOMElement} d DOMElement to get the Y position from
* @return {Number} Y position of div 'd'
* @public
* @static
*/
gy: function(d) {
var gy;
gy = d.offsetTop;
if (d.offsetParent){
while ( (d = d.offsetParent) ){
gy += d.offsetTop;
}
}
return gy;
},
/**
* Returns the current scroll position
*
* @method scrollTop
* @return {Number} Current scroll position
* @public
* @static
*/
scrollTop: function() {
var
body = document.body,
d = document.documentElement
;
if (body && body.scrollTop){
return body.scrollTop;
}
if (d && d.scrollTop){
return d.scrollTop;
}
if (window.pageYOffset)
{
return window.pageYOffset;
}
return 0;
},
/**
* Attaches an event for an element
*
* @method add
* @param {DOMElement} el DOMElement to make the listening of the event
* @param {String} event Event name to be listened
* @param {DOMElement} fn Callback function to run when the event is triggered.
* @public
* @static
*/
add: function(el, event, fn) {
Event.observe(el,event,fn);
return;
},
/**
* Kill an event of an element
*
* @method end
* @param {String} e Event to be killed/stopped
* @public
* @static
*/
// kill an event of an element
end: function(e) {
if (window.event) {
window.event.cancelBubble = true;
window.event.returnValue = false;
return;
}
Event.stop(e);
},
/**
* Moves the scrollbar to the target element
*
* @method scroll
* @param {Number} d Y coordinate value to stop
* @public
* @static
*/
scroll: function(d) {
var a = Ink.UI.SmoothScroller.scrollTop();
if (d > a) {
a += Math.ceil((d - a) / Ink.UI.SmoothScroller.speed);
} else {
a = a + (d - a) / Ink.UI.SmoothScroller.speed;
}
window.scrollTo(0, a);
if ((a) === d || Ink.UI.SmoothScroller.offsetTop === a)
{
clearInterval(Ink.UI.SmoothScroller.interval);
}
Ink.UI.SmoothScroller.offsetTop = a;
},
/**
* Initializer that adds the rendered to run when the page is ready
*
* @method init
* @public
* @static
*/
// initializer that adds the renderer to the onload function of the window
init: function() {
Loaded.run(Ink.UI.SmoothScroller.render);
},
/**
* This method extracts all the anchors and validates thenm as # and attaches the events
*
* @method render
* @public
* @static
*/
render: function() {
var a = Selector.select('a.scrollableLink');
Ink.UI.SmoothScroller.end(this);
for (var i = 0; i < a.length; i++) {
var _elm = a[i];
if (_elm.href && _elm.href.indexOf('#') !== -1 && ((_elm.pathname === location.pathname) || ('/' + _elm.pathname === location.pathname))) {
Ink.UI.SmoothScroller.add(_elm, 'click', Ink.UI.SmoothScroller.end);
Event.observe(_elm,'click', Ink.bindEvent(Ink.UI.SmoothScroller.clickScroll, this, _elm));
}
}
},
/**
* Click handler
*
* @method clickScroll
* @public
* @static
*/
clickScroll: function(event, _elm) {
/*
Ink.UI.SmoothScroller.end(this);
var hash = this.hash.substr(1);
var elm = Selector.select('a[name="' + hash + '"],#' + hash);
if (typeof(elm[0]) !== 'undefined') {
if (this.parentNode.className.indexOf('active') === -1) {
var ul = this.parentNode.parentNode,
li = ul.firstChild;
do {
if ((typeof(li.tagName) !== 'undefined') && (li.tagName.toUpperCase() === 'LI') && (li.className.indexOf('active') !== -1)) {
li.className = li.className.replace('active', '');
break;
}
} while ((li = li.nextSibling));
this.parentNode.className += " active";
}
clearInterval(Ink.UI.SmoothScroller.interval);
Ink.UI.SmoothScroller.interval = setInterval('Ink.UI.SmoothScroller.scroll(' + Ink.UI.SmoothScroller.gy(elm[0]) + ')', 10);
}
*/
Ink.UI.SmoothScroller.end(_elm);
if(_elm !== null && _elm.getAttribute('href') !== null) {
var hashIndex = _elm.href.indexOf('#');
if(hashIndex === -1) {
return;
}
var hash = _elm.href.substr((hashIndex + 1));
var elm = Selector.select('a[name="' + hash + '"],#' + hash);
if (typeof(elm[0]) !== 'undefined') {
if (_elm.parentNode.className.indexOf('active') === -1) {
var ul = _elm.parentNode.parentNode,
li = ul.firstChild;
do {
if ((typeof(li.tagName) !== 'undefined') && (li.tagName.toUpperCase() === 'LI') && (li.className.indexOf('active') !== -1)) {
li.className = li.className.replace('active', '');
break;
}
} while ((li = li.nextSibling));
_elm.parentNode.className += " active";
}
clearInterval(Ink.UI.SmoothScroller.interval);
Ink.UI.SmoothScroller.interval = setInterval('Ink.UI.SmoothScroller.scroll(' + Ink.UI.SmoothScroller.gy(elm[0]) + ')', 10);
}
}
}
};
return SmoothScroller;
});
/**
* @module Ink.UI.ImageQuery_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.ImageQuery', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) {
'use strict';
/**
* @class Ink.UI.ImageQuery
* @constructor
* @version 1
*
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {String|Function} [options.src] String or Callback function (that returns a string) with the path to be used to get the images.
* @param {String|Function} [options.retina] String or Callback function (that returns a string) with the path to be used to get RETINA specific images.
* @param {Array} [options.queries] Array of queries
* @param {String} [options.queries.label] Label of the query. Ex. 'small'
* @param {Number} [options.queries.width] Min-width to use this query
* @param {Function} [options.onLoad] Date format string
*
* @example
* <div class="imageQueryExample large-100 medium-100 small-100 content-center clearfix vspace">
* <img src="/assets/imgs/imagequery/small/image.jpg" />
* </div>
* <script type="text/javascript">
* Ink.requireModules( ['Ink.Dom.Selector_1', 'Ink.UI.ImageQuery_1'], function( Selector, ImageQuery ){
* var imageQueryElement = Ink.s('.imageQueryExample img');
* var imageQueryObj = new ImageQuery('.imageQueryExample img',{
* src: '/assets/imgs/imagequery/{:label}/{:file}',
* queries: [
* {
* label: 'small',
* width: 480
* },
* {
* label: 'medium',
* width: 640
* },
* {
* label: 'large',
* width: 1024
* }
* ]
* });
* } );
* </script>
*/
var ImageQuery = function(selector, options){
/**
* Selector's type checking
*/
if( !Aux.isDOMElement(selector) && (typeof selector !== 'string') ){
throw '[ImageQuery] :: Invalid selector';
} else if( typeof selector === 'string' ){
this._element = Selector.select( selector );
if( this._element.length < 1 ){
throw '[ImageQuery] :: Selector has returned no elements';
} else if( this._element.length > 1 ){
var i;
for( i=1;i<this._element.length;i+=1 ){
new Ink.UI.ImageQuery(this._element[i],options);
}
}
this._element = this._element[0];
} else {
this._element = selector;
}
/**
* Default options and they're overrided by data-attributes if any.
* The parameters are:
* @param {array} queries Array of objects that determine the label/name and its min-width to be applied.
* @param {boolean} allowFirstLoad Boolean flag to allow the loading of the first element.
*/
this._options = Ink.extendObj({
queries:[],
onLoad: null
},Element.data(this._element));
this._options = Ink.extendObj(this._options, options || {});
/**
* Determining the original basename (with the querystring) of the file.
*/
var pos;
if( (pos=this._element.src.lastIndexOf('?')) !== -1 ){
var search = this._element.src.substr(pos);
this._filename = this._element.src.replace(search,'').split('/').pop()+search;
} else {
this._filename = this._element.src.split('/').pop();
}
this._init();
};
ImageQuery.prototype = {
/**
* Init function called by the constructor
*
* @method _init
* @private
*/
_init: function(){
// Sort queries by width, in descendant order.
this._options.queries = InkArray.sortMulti(this._options.queries,'width').reverse();
// Declaring the event handlers, in this case, the window.resize and the (element) load.
this._handlers = {
resize: Ink.bindEvent(this._onResize,this),
load: Ink.bindEvent(this._onLoad,this)
};
if( typeof this._options.onLoad === 'function' ){
Event.observe(this._element, 'onload', this._handlers.load);
}
Event.observe(window, 'resize', this._handlers.resize);
// Imediate call to apply the right images based on the current viewport
this._handlers.resize.call(this);
},
/**
* Handles the resize event (as specified in the _init function)
*
* @method _onResize
* @private
*/
_onResize: function(){
clearTimeout(timeout);
var timeout = setTimeout(Ink.bind(function(){
if( !this._options.queries || (this._options.queries === {}) ){
clearTimeout(timeout);
return;
}
var
query, selected,
viewportWidth
;
/**
* Gets viewport width
*/
if( typeof( window.innerWidth ) === 'number' ) {
viewportWidth = window.innerWidth;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
viewportWidth = document.documentElement.clientWidth;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
viewportWidth = document.body.clientWidth;
}
/**
* Queries are in a descendant order. We want to find the query with the highest width that fits
* the viewport, therefore the first one.
*/
for( query=0; query < this._options.queries.length; query+=1 ){
if (this._options.queries[query].width <= viewportWidth){
selected = query;
break;
}
}
/**
* If it doesn't find any selectable query (because they don't meet the requirements)
* let's select the one with the smallest width
*/
if( typeof selected === 'undefined' ){ selected = this._options.queries.length-1; }
/**
* Choosing the right src. The rule is:
*
* "If there is specifically defined in the query object, use that. Otherwise uses the global src."
*
* The above rule applies to a retina src.
*/
var src = this._options.queries[selected].src || this._options.src;
if ( ("devicePixelRatio" in window && window.devicePixelRatio>1) && ('retina' in this._options ) ) {
src = this._options.queries[selected].retina || this._options.retina;
}
/**
* Injects the file variable for usage in the 'templating system' below
*/
this._options.queries[selected].file = this._filename;
/**
* Since we allow the src to be a callback, let's run it and get the results.
* For the inside, we're passing the element (img) being processed and the object of the selected
* query.
*/
if( typeof src === 'function' ){
src = src.apply(this,[this._element,this._options.queries[selected]]);
if( typeof src !== 'string' ){
throw '[ImageQuery] :: "src" callback does not return a string';
}
}
/**
* Replace the values of the existing properties on the query object (except src and retina) in the
* defined src and/or retina.
*/
var property;
for( property in this._options.queries[selected] ){
if (this._options.queries[selected].hasOwnProperty(property)) {
if( ( property === 'src' ) || ( property === 'retina' ) ){ continue; }
src = src.replace("{:" + property + "}",this._options.queries[selected][property]);
}
}
this._element.src = src;
// Removes the injected file property
delete this._options.queries[selected].file;
timeout = undefined;
},this),300);
},
/**
* Handles the element loading (img onload) event
*
* @method _onLoad
* @private
*/
_onLoad: function(){
/**
* Since we allow a callback for this let's run it.
*/
this._options.onLoad.call(this);
}
};
return ImageQuery;
});
/**
* @module Ink.UI.FormValidator_2
* @author inkdev AT sapo.pt
* @version 2
*/
Ink.createModule('Ink.UI.FormValidator', '2', [ 'Ink.UI.Aux_1','Ink.Dom.Element_1','Ink.Dom.Event_1','Ink.Dom.Selector_1','Ink.Dom.Css_1','Ink.Util.Array_1','Ink.Util.I18n_1','Ink.Util.Validator_1'], function( Aux, Element, Event, Selector, Css, InkArray, I18n, InkValidator ) {
'use strict';
/**
* Validation Functions to be used
* Some functions are a port from PHP, others are the 'best' solutions available
*
* @type {Object}
* @private
* @static
*/
var validationFunctions = {
/**
* Checks if the value is actually defined and is not empty
*
* @method validationFunctions.required
* @param {String} value Value to be checked
* @return {Boolean} True case is defined, false if it's empty or not defined.
*/
'required': function( value ){
return ( (typeof value !== 'undefined') && ( !(/^\s*$/).test(value) ) );
},
/**
* Checks if the value has a minimum length
*
* @method validationFunctions.min_length
* @param {String} value Value to be checked
* @param {String|Number} minSize Number of characters that the value at least must have.
* @return {Boolean} True if the length of value is equal or bigger than the minimum chars defined. False if not.
*/
'min_length': function( value, minSize ){
return ( (typeof value === 'string') && ( value.length >= parseInt(minSize,10) ) );
},
/**
* Checks if the value has a maximum length
*
* @method validationFunctions.max_length
* @param {String} value Value to be checked
* @param {String|Number} maxSize Number of characters that the value at maximum can have.
* @return {Boolean} True if the length of value is equal or smaller than the maximum chars defined. False if not.
*/
'max_length': function( value, maxSize ){
return ( (typeof value === 'string') && ( value.length <= parseInt(maxSize,10) ) );
},
/**
* Checks if the value has an exact length
*
* @method validationFunctions.exact_length
* @param {String} value Value to be checked
* @param {String|Number} exactSize Number of characters that the value must have.
* @return {Boolean} True if the length of value is equal to the size defined. False if not.
*/
'exact_length': function( value, exactSize ){
return ( (typeof value === 'string') && ( value.length === parseInt(exactSize,10) ) );
},
/**
* Checks if the value has a valid e-mail address
*
* @method validationFunctions.email
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid e-mail address. False if not.
*/
'email': function( value ){
return ( ( typeof value === 'string' ) && InkValidator.mail( value ) );
},
/**
* Checks if the value has a valid URL
*
* @method validationFunctions.url
* @param {String} value Value to be checked
* @param {Boolean} fullCheck Flag that specifies if the value must be validated as a full url (with the protocol) or not.
* @return {Boolean} True if the URL is considered valid. False if not.
*/
'url': function( value, fullCheck ){
fullCheck = fullCheck || false;
return ( (typeof value === 'string') && InkValidator.url( value, fullCheck ) );
},
/**
* Checks if the value is a valid IP. Supports ipv4 and ipv6
*
* @method validationFunctions.ip
* @param {String} value Value to be checked
* @param {String} ipType Type of IP to be validated. The values are: ipv4, ipv6. By default is ipv4.
* @return {Boolean} True if the value is a valid IP address. False if not.
*/
'ip': function( value, ipType ){
if( typeof value !== 'string' ){
return false;
}
return InkValidator.isIP(value, ipType);
},
/**
* Checks if the value is a valid phone number. Supports several countries, based in the Ink.Util.Validator class.
*
* @method validationFunctions.phone
* @param {String} value Value to be checked
* @param {String} phoneType Country's initials to specify the type of phone number to be validated. Ex: 'AO'.
* @return {Boolean} True if it's a valid phone number. False if not.
*/
'phone': function( value, phoneType ){
if( typeof value !== 'string' ){
return false;
}
var countryCode = phoneType ? phoneType.toUpperCase() : '';
return InkValidator['is' + countryCode + 'Phone'](value);
},
/**
* Checks if it's a valid credit card.
*
* @method validationFunctions.credit_card
* @param {String} value Value to be checked
* @param {String} cardType Type of credit card to be validated. The card types available are in the Ink.Util.Validator class.
* @return {Boolean} True if the value is a valid credit card number. False if not.
*/
'credit_card': function( value, cardType ){
if( typeof value !== 'string' ){
return false;
}
return InkValidator.isCreditCard( value, cardType || 'default' );
},
/**
* Checks if the value is a valid date.
*
* @method validationFunctions.date
* @param {String} value Value to be checked
* @param {String} format Specific format of the date.
* @return {Boolean} True if the value is a valid date. False if not.
*/
'date': function( value, format ){
return ( (typeof value === 'string' ) && InkValidator.isDate(format, value) );
},
/**
* Checks if the value only contains alphabetical values.
*
* @method validationFunctions.alpha
* @param {String} value Value to be checked
* @param {Boolean} supportSpaces Allow whitespace
* @return {Boolean} True if the value is alphabetical-only. False if not.
*/
'alpha': function( value, supportSpaces ){
return InkValidator.ascii(value, {singleLineWhitespace: supportSpaces});
},
/*
* Check that the value contains only printable unicode text characters
* from the Basic Multilingual plane (BMP)
* Optionally allow punctuation and whitespace
*
* @method validationFunctions.text
* @param {String} value Value to be checked
* @return {Boolean} Whether the value only contains printable text characters
**/
'text': function (value, whitespace, punctuation) {
return InkValidator.unicode(value, {
singleLineWhitespace: whitespace,
unicodePunctuation: punctuation});
},
/*
* Check that the value contains only printable text characters
* available in the latin-1 encoding.
*
* Optionally allow punctuation and whitespace
*
* @method validationFunctions.text
* @param {String} value Value to be checked
* @return {Boolean} Whether the value only contains printable text characters
**/
'latin': function (value, punctuation, whitespace) {
if ( typeof value !== 'string') { return false; }
return InkValidator.latin1(value, {latin1Punctuation: punctuation, singleLineWhitespace: whitespace});
},
/**
* Checks if the value only contains alphabetical and numerical characters.
*
* @method validationFunctions.alpha_numeric
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid alphanumerical. False if not.
*/
'alpha_numeric': function( value ){
return InkValidator.ascii(value, {numbers: true});
},
/**
* Checks if the value only contains alphabetical, dash or underscore characteres.
*
* @method validationFunctions.alpha_dashes
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid. False if not.
*/
'alpha_dash': function( value ){
return InkValidator.ascii(value, {dash: true, underscore: true});
},
/**
* Checks if the value is a digit (an integer of length = 1).
*
* @method validationFunctions.digit
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid digit. False if not.
*/
'digit': function( value ){
return ((typeof value === 'string') && /^[0-9]{1}$/.test(value));
},
/**
* Checks if the value is a valid integer.
*
* @method validationFunctions.integer
* @param {String} value Value to be checked
* @param {String} positive Flag that specifies if the integer is must be positive (unsigned).
* @return {Boolean} True if the value is a valid integer. False if not.
*/
'integer': function( value, positive ){
return InkValidator.number(value, {
negative: !positive,
decimalPlaces: 0
});
},
/**
* Checks if the value is a valid decimal number.
*
* @method validationFunctions.decimal
* @param {String} value Value to be checked
* @param {String} decimalSeparator Character that splits the integer part from the decimal one. By default is '.'.
* @param {String} [decimalPlaces] Maximum number of digits that the decimal part must have.
* @param {String} [leftDigits] Maximum number of digits that the integer part must have, when provided.
* @return {Boolean} True if the value is a valid decimal number. False if not.
*/
'decimal': function( value, decimalSeparator, decimalPlaces, leftDigits ){
return InkValidator.number(value, {
decimalSep: decimalSeparator || '.',
decimalPlaces: +decimalPlaces || null,
maxDigits: +leftDigits
});
},
/**
* Checks if it is a numeric value.
*
* @method validationFunctions.numeric
* @param {String} value Value to be checked
* @param {String} decimalSeparator Verifies if it's a valid decimal. Otherwise checks if it's a valid integer.
* @param {String} [decimalPlaces] (when the number is decimal) Maximum number of digits that the decimal part must have.
* @param {String} [leftDigits] (when the number is decimal) Maximum number of digits that the integer part must have, when provided.
* @return {Boolean} True if the value is numeric. False if not.
*/
'numeric': function( value, decimalSeparator, decimalPlaces, leftDigits ){
decimalSeparator = decimalSeparator || '.';
if( value.indexOf(decimalSeparator) !== -1 ){
return validationFunctions.decimal( value, decimalSeparator, decimalPlaces, leftDigits );
} else {
return validationFunctions.integer( value );
}
},
/**
* Checks if the value is in a specific range of values. The parameters after the first one are used for specifying the range, and are similar in function to python's range() function.
*
* @method validationFunctions.range
* @param {String} value Value to be checked
* @param {String} minValue Left limit of the range.
* @param {String} maxValue Right limit of the range.
* @param {String} [multipleOf] In case you want numbers that are only multiples of another number.
* @return {Boolean} True if the value is within the range. False if not.
*/
'range': function( value, minValue, maxValue, multipleOf ){
value = +value;
minValue = +minValue;
maxValue = +maxValue;
if (isNaN(value) || isNaN(minValue) || isNaN(maxValue)) {
return false;
}
if( value < minValue || value > maxValue ){
return false;
}
if (multipleOf) {
return (value - minValue) % multipleOf === 0;
} else {
return true;
}
},
/**
* Checks if the value is a valid color.
*
* @method validationFunctions.color
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid color. False if not.
*/
'color': function( value ){
return InkValidator.isColor(value);
},
/**
* Checks if the value matches the value of a different field.
*
* @method validationFunctions.matches
* @param {String} value Value to be checked
* @param {String} fieldToCompare Name or ID of the field to compare.
* @return {Boolean} True if the values match. False if not.
*/
'matches': function( value, fieldToCompare ){
return ( value === this.getFormElements()[fieldToCompare][0].getValue() );
}
};
/**
* Error messages for the validation functions above
* @type {Object}
* @private
* @static
*/
var validationMessages = new I18n({
en_US: {
'formvalidator.required' : 'The {field} filling is mandatory',
'formvalidator.min_length': 'The {field} must have a minimum size of {param1} characters',
'formvalidator.max_length': 'The {field} must have a maximum size of {param1} characters',
'formvalidator.exact_length': 'The {field} must have an exact size of {param1} characters',
'formvalidator.email': 'The {field} must have a valid e-mail address',
'formvalidator.url': 'The {field} must have a valid URL',
'formvalidator.ip': 'The {field} does not contain a valid {param1} IP address',
'formvalidator.phone': 'The {field} does not contain a valid {param1} phone number',
'formvalidator.credit_card': 'The {field} does not contain a valid {param1} credit card',
'formvalidator.date': 'The {field} should contain a date in the {param1} format',
'formvalidator.alpha': 'The {field} should only contain letters',
'formvalidator.text': 'The {field} should only contain alphabetic characters',
'formvalidator.latin': 'The {field} should only contain alphabetic characters',
'formvalidator.alpha_numeric': 'The {field} should only contain letters or numbers',
'formvalidator.alpha_dashes': 'The {field} should only contain letters or dashes',
'formvalidator.digit': 'The {field} should only contain a digit',
'formvalidator.integer': 'The {field} should only contain an integer',
'formvalidator.decimal': 'The {field} should contain a valid decimal number',
'formvalidator.numeric': 'The {field} should contain a number',
'formvalidator.range': 'The {field} should contain a number between {param1} and {param2}',
'formvalidator.color': 'The {field} should contain a valid color',
'formvalidator.matches': 'The {field} should match the field {param1}',
'formvalidator.validation_function_not_found': 'The rule {rule} has not been defined'
},
pt_PT: {
'formvalidator.required' : 'Preencher {field} é obrigatório',
'formvalidator.min_length': '{field} deve ter no mínimo {param1} caracteres',
'formvalidator.max_length': '{field} tem um tamanho máximo de {param1} caracteres',
'formvalidator.exact_length': '{field} devia ter exactamente {param1} caracteres',
'formvalidator.email': '{field} deve ser um e-mail válido',
'formvalidator.url': 'O {field} deve ser um URL válido',
'formvalidator.ip': '{field} não tem um endereço IP {param1} válido',
'formvalidator.phone': '{field} deve ser preenchido com um número de telefone {param1} válido.',
'formvalidator.credit_card': '{field} não tem um cartão de crédito {param1} válido',
'formvalidator.date': '{field} deve conter uma data no formato {param1}',
'formvalidator.alpha': 'O campo {field} deve conter apenas caracteres alfabéticos',
'formvalidator.text': 'O campo {field} deve conter apenas caracteres alfabéticos',
'formvalidator.latin': 'O campo {field} deve conter apenas caracteres alfabéticos',
'formvalidator.alpha_numeric': '{field} deve conter apenas letras e números',
'formvalidator.alpha_dashes': '{field} deve conter apenas letras e traços',
'formvalidator.digit': '{field} destina-se a ser preenchido com apenas um dígito',
'formvalidator.integer': '{field} deve conter um número inteiro',
'formvalidator.decimal': '{field} deve conter um número válido',
'formvalidator.numeric': '{field} deve conter um número válido',
'formvalidator.range': '{field} deve conter um número entre {param1} e {param2}',
'formvalidator.color': '{field} deve conter uma cor válida',
'formvalidator.matches': '{field} deve corresponder ao campo {param1}',
'formvalidator.validation_function_not_found': '[A regra {rule} não foi definida]'
},
}, 'en_US');
/**
* Constructor of a FormElement.
* This type of object has particular methods to parse rules and validate them in a specific DOM Element.
*
* @param {DOMElement} element DOM Element
* @param {Object} options Object with configuration options
* @return {FormElement} FormElement object
*/
var FormElement = function( element, options ){
this._element = Aux.elOrSelector( element, 'Invalid FormElement' );
this._errors = {};
this._rules = {};
this._value = null;
this._options = Ink.extendObj( {
label: this._getLabel()
}, Element.data(this._element) );
this._options = Ink.extendObj( this._options, options || {} );
};
/**
* FormElement's prototype
*/
FormElement.prototype = {
/**
* Function to get the label that identifies the field.
* If it can't find one, it will use the name or the id
* (depending on what is defined)
*
* @method _getLabel
* @return {String} Label to be used in the error messages
* @private
*/
_getLabel: function(){
var controlGroup = Element.findUpwardsByClass(this._element,'control-group');
var label = Ink.s('label',controlGroup);
if( label ){
label = Element.textContent(label);
} else {
label = this._element.name || this._element.id || '';
}
return label;
},
/**
* Function to parse a rules' string.
* Ex: required|number|max_length[30]
*
* @method _parseRules
* @param {String} rules String with the rules
* @private
*/
_parseRules: function( rules ){
this._rules = {};
rules = rules.split("|");
var i, rulesLength = rules.length, rule, params, paramStartPos ;
if( rulesLength > 0 ){
for( i = 0; i < rulesLength; i++ ){
rule = rules[i];
if( !rule ){
continue;
}
if( ( paramStartPos = rule.indexOf('[') ) !== -1 ){
params = rule.substr( paramStartPos+1 );
params = params.split(']');
params = params[0];
params = params.split(',');
for (var p = 0, len = params.length; p < len; p++) {
params[p] =
params[p] === 'true' ? true :
params[p] === 'false' ? false :
params[p];
}
params.splice(0,0,this.getValue());
rule = rule.substr(0,paramStartPos);
this._rules[rule] = params;
} else {
this._rules[rule] = [this.getValue()];
}
}
}
},
/**
* Function to add an error to the FormElement's 'errors' object.
* It basically receives the rule where the error occurred, the parameters passed to it (if any)
* and the error message.
* Then it replaces some tokens in the message for a more 'custom' reading
*
* @method _addError
* @param {String|null} rule Rule that failed, or null if no rule was found.
* @private
* @static
*/
_addError: function(rule){
var params = this._rules[rule] || [];
var paramObj = {
field: this._options.label,
value: this.getValue()
};
for( var i = 1; i < params.length; i++ ){
paramObj['param' + i] = params[i];
}
var i18nKey = 'formvalidator.' + rule;
this._errors[rule] = validationMessages.text(i18nKey, paramObj);
if (this._errors[rule] === i18nKey) {
this._errors[rule] = 'Validation message not found';
}
},
/**
* Function to retrieve the element's value
*
* @method getValue
* @return {mixed} The DOM Element's value
* @public
*/
getValue: function(){
switch(this._element.nodeName.toLowerCase()){
case 'select':
return Ink.s('option:selected',this._element).value;
case 'textarea':
return this._element.innerHTML;
case 'input':
if( "type" in this._element ){
if( (this._element.type === 'radio') && (this._element.type === 'checkbox') ){
if( this._element.checked ){
return this._element.value;
}
} else if( this._element.type !== 'file' ){
return this._element.value;
}
} else {
return this._element.value;
}
return;
default:
return this._element.innerHTML;
}
},
/**
* Function that returns the constructed errors object.
*
* @method getErrors
* @return {Object} Errors' object
* @public
*/
getErrors: function(){
return this._errors;
},
/**
* Function that returns the DOM element related to it.
*
* @method getElement
* @return {Object} DOM Element
* @public
*/
getElement: function(){
return this._element;
},
/**
* Get other elements in the same form.
*
* @method getFormElements
* @return {Object} A mapping of keys to other elements in this form.
* @public
*/
getFormElements: function () {
return this._options.form._formElements;
},
/**
* Function used to validate the element based on the rules defined.
* It parses the rules defined in the _options.rules property.
*
* @method validate
* @return {Boolean} True if every rule was valid. False if one fails.
* @public
*/
validate: function(){
this._errors = {};
if( "rules" in this._options || 1){
this._parseRules( this._options.rules );
}
if( ("required" in this._rules) || (this.getValue() !== '') ){
for(var rule in this._rules) {
if (this._rules.hasOwnProperty(rule)) {
if( (typeof validationFunctions[rule] === 'function') ){
if( validationFunctions[rule].apply(this, this._rules[rule] ) === false ){
this._addError( rule );
return false;
}
} else {
this._addError( null );
return false;
}
}
}
}
return true;
}
};
/**
* @class Ink.UI.FormValidator_2
* @version 2
* @constructor
* @param {String|DOMElement} selector Either a CSS Selector string, or the form's DOMElement
* @param {} [varname] [description]
* @example
* Ink.requireModules( ['Ink.UI.FormValidator_2'], function( FormValidator ){
* var myValidator = new FormValidator( 'form' );
* });
*/
var FormValidator = function( selector, options ){
/**
* DOMElement of the <form> being validated
*
* @property _rootElement
* @type {DOMElement}
*/
this._rootElement = Aux.elOrSelector( selector );
/**
* Object that will gather the form elements by name
*
* @property _formElements
* @type {Object}
*/
this._formElements = {};
/**
* Error message DOMElements
*
* @property _errorMessages
*/
this._errorMessages = [];
/**
* Array of elements marked with validation errors
*
* @property _markedErrorElements
*/
this._markedErrorElements = [];
/**
* Configuration options. Fetches the data attributes first, then the ones passed when executing the constructor.
* By doing that, the latter will be the one with highest priority.
*
* @property _options
* @type {Object}
*/
this._options = Ink.extendObj({
eventTrigger: 'submit',
searchFor: 'input, select, textarea, .control-group',
beforeValidation: undefined,
onError: undefined,
onSuccess: undefined
},Element.data(this._rootElement));
this._options = Ink.extendObj( this._options, options || {} );
// Sets an event listener for a specific event in the form, if defined.
// By default is the 'submit' event.
if( typeof this._options.eventTrigger === 'string' ){
Event.observe( this._rootElement,this._options.eventTrigger, Ink.bindEvent(this.validate,this) );
}
this._init();
};
/**
* Method used to set validation functions (either custom or ovewrite the existent ones)
*
* @method setRule
* @param {String} name Name of the function. E.g. 'required'
* @param {String} errorMessage Error message to be displayed in case of returning false. E.g. 'Oops, you passed {param1} as parameter1, lorem ipsum dolor...'
* @param {Function} cb Function to be executed when calling this rule
* @public
* @static
*/
FormValidator.setRule = function( name, errorMessage, cb ){
validationFunctions[ name ] = cb;
if (validationMessages.getKey('formvalidator.' + name) !== errorMessage) {
var langObj = {}; langObj['formvalidator.' + name] = errorMessage;
var dictObj = {}; dictObj[validationMessages.lang()] = langObj;
validationMessages.append(dictObj);
}
};
/**
* Get the i18n object in charge of the error messages
*
* @method getI18n
* @return {Ink.Util.I18n} The i18n object the FormValidator is using.
*/
FormValidator.getI18n = function () {
return validationMessages;
};
/**
* Sets the I18n object for validation error messages
*
* @method setI18n
* @param {Ink.Util.I18n} i18n The I18n object.
*/
FormValidator.setI18n = function (i18n) {
validationMessages = i18n;
};
/**
* Add to the I18n dictionary. See `Ink.Util.I18n.append()` documentation.
*
* @method AppendI18n
*/
FormValidator.appendI18n = function () {
validationMessages.append.apply(validationMessages, [].slice.call(arguments));
};
/**
* Sets the language of the error messages. pt_PT and en_US are available, but you can add new languages by using append()
*
* See the `Ink.Util.I18n.lang()` setter
*
* @method setLanguage
* @param language The language to set i18n to.
*/
FormValidator.setLanguage = function (language) {
validationMessages.lang(language);
};
/**
* Method used to get the existing defined validation functions
*
* @method getRules
* @return {Object} Object with the rules defined
* @public
* @static
*/
FormValidator.getRules = function(){
return validationFunctions;
};
FormValidator.prototype = {
_init: function(){
},
/**
* Function that searches for the elements of the form, based in the
* this._options.searchFor configuration.
*
* @method getElements
* @return {Object} An object with the elements in the form, indexed by name/id
* @public
*/
getElements: function(){
this._formElements = {};
var formElements = Selector.select( this._options.searchFor, this._rootElement );
if( formElements.length ){
var i, element;
for( i=0; i<formElements.length; i+=1 ){
element = formElements[i];
var dataAttrs = Element.data( element );
if( !("rules" in dataAttrs) ){
continue;
}
var options = {
form: this
};
var key;
if( ("name" in element) && element.name ){
key = element.name;
} else if( ("id" in element) && element.id ){
key = element.id;
} else {
key = 'element_' + Math.floor(Math.random()*100);
element.id = key;
}
if( !(key in this._formElements) ){
this._formElements[key] = [ new FormElement( element, options ) ];
} else {
this._formElements[key].push( new FormElement( element, options ) );
}
}
}
return this._formElements;
},
/**
* Runs the validate function of each FormElement in the this._formElements
* object.
* Also, based on the this._options.beforeValidation, this._options.onError
* and this._options.onSuccess, this callbacks are executed when defined.
*
* @method validate
* @param {Event} event window.event object
* @return {Boolean}
* @public
*/
validate: function( event ){
Event.stop(event);
if( typeof this._options.beforeValidation === 'function' ){
this._options.beforeValidation();
}
this.getElements();
var errorElements = [];
for( var key in this._formElements ){
if( this._formElements.hasOwnProperty(key) ){
for( var counter = 0; counter < this._formElements[key].length; counter+=1 ){
if( !this._formElements[key][counter].validate() ) {
errorElements.push(this._formElements[key][counter]);
}
}
}
}
if( errorElements.length === 0 ){
if( typeof this._options.onSuccess === 'function' ){
this._options.onSuccess();
}
return true;
} else {
if( typeof this._options.onError === 'function' ){
this._options.onError( errorElements );
}
InkArray.each( this._markedErrorElements, Ink.bind(Css.removeClassName, Css, 'validation'));
InkArray.each( this._markedErrorElements, Ink.bind(Css.removeClassName, Css, 'error'));
InkArray.each( this._errorMessages, Element.remove);
this._errorMessages = [];
this._markedErrorElements = [];
InkArray.each( errorElements, Ink.bind(function( formElement ){
var controlGroupElement;
var controlElement;
if( Css.hasClassName(formElement.getElement(),'control-group') ){
controlGroupElement = formElement.getElement();
controlElement = Ink.s('.control',formElement.getElement());
} else {
controlGroupElement = Element.findUpwardsByClass(formElement.getElement(),'control-group');
controlElement = Element.findUpwardsByClass(formElement.getElement(),'control');
}
if (!controlElement || !controlGroupElement) {
controlElement = controlGroupElement = formElement.getElement();
}
Css.addClassName( controlGroupElement, 'validation' );
Css.addClassName( controlGroupElement, 'error' );
this._markedErrorElements.push(controlGroupElement);
var paragraph = document.createElement('p');
Css.addClassName(paragraph,'tip');
Element.insertAfter(paragraph, controlElement);
var errors = formElement.getErrors();
var errorArr = [];
for (var k in errors) {
if (errors.hasOwnProperty(k)) {
errorArr.push(errors[k]);
}
}
paragraph.innerHTML = errorArr.join('<br/>');
this._errorMessages.push(paragraph);
}, this));
return false;
}
}
};
/**
* Returns the FormValidator's Object
*/
return FormValidator;
});
/**
* @module Ink.UI.FormValidator_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.FormValidator', '1', ['Ink.Dom.Css_1','Ink.Util.Validator_1'], function( Css, InkValidator ) {
'use strict';
/**
* @class Ink.UI.FormValidator
* @version 1
*/
var FormValidator = {
/**
* Specifies the version of the component
*
* @property version
* @type {String}
* @readOnly
* @public
*/
version: '1',
/**
* Available flags to use in the validation process.
* The keys are the 'rules', and their values are objects with the key 'msg', determining
* what is the error message.
*
* @property _flagMap
* @type {Object}
* @readOnly
* @private
*/
_flagMap: {
//'ink-fv-required': {msg: 'Campo obrigatório'},
'ink-fv-required': {msg: 'Required field'},
//'ink-fv-email': {msg: 'E-mail inválido'},
'ink-fv-email': {msg: 'Invalid e-mail address'},
//'ink-fv-url': {msg: 'URL inválido'},
'ink-fv-url': {msg: 'Invalid URL'},
//'ink-fv-number': {msg: 'Número inválido'},
'ink-fv-number': {msg: 'Invalid number'},
//'ink-fv-phone_pt': {msg: 'Número de telefone inválido'},
'ink-fv-phone_pt': {msg: 'Invalid phone number'},
//'ink-fv-phone_cv': {msg: 'Número de telefone inválido'},
'ink-fv-phone_cv': {msg: 'Invalid phone number'},
//'ink-fv-phone_mz': {msg: 'Número de telefone inválido'},
'ink-fv-phone_mz': {msg: 'Invalid phone number'},
//'ink-fv-phone_ao': {msg: 'Número de telefone inválido'},
'ink-fv-phone_ao': {msg: 'Invalid phone number'},
//'ink-fv-date': {msg: 'Data inválida'},
'ink-fv-date': {msg: 'Invalid date'},
//'ink-fv-confirm': {msg: 'Confirmação inválida'},
'ink-fv-confirm': {msg: 'Confirmation does not match'},
'ink-fv-custom': {msg: ''}
},
/**
* This property holds all form elements for later validation
*
* @property elements
* @type {Object}
* @public
*/
elements: {},
/**
* This property holds the objects needed to cross-check for the 'confirm' rule
*
* @property confirmElms
* @type {Object}
* @public
*/
confirmElms: {},
/**
* This property holds the previous elements in the confirmElms property, but with a
* true/false specifying if it has the class ink-fv-confirm.
*
* @property hasConfirm
* @type {Object}
*/
hasConfirm: {},
/**
* Defined class name to use in error messages label
*
* @property _errorClassName
* @type {String}
* @readOnly
* @private
*/
_errorClassName: 'tip',
/**
* @property _errorValidationClassName
* @type {String}
* @readOnly
* @private
*/
_errorValidationClassName: 'validaton',
/**
* @property _errorTypeWarningClassName
* @type {String}
* @readOnly
* @private
*/
_errorTypeWarningClassName: 'warning',
/**
* @property _errorTypeErrorClassName
* @type {String}
* @readOnly
* @private
*/
_errorTypeErrorClassName: 'error',
/**
* Check if a form is valid or not
*
* @method validate
* @param {DOMElement|String} elm DOM form element or form id
* @param {Object} options Options for
* @param {Function} [options.onSuccess] function to run when form is valid
* @param {Function} [options.onError] function to run when form is not valid
* @param {Array} [options.customFlag] custom flags to use to validate form fields
* @public
* @return {Boolean}
*/
validate: function(elm, options)
{
this._free();
options = Ink.extendObj({
onSuccess: false,
onError: false,
customFlag: false,
confirmGroup: []
}, options || {});
if(typeof(elm) === 'string') {
elm = document.getElementById(elm);
}
if(elm === null){
return false;
}
this.element = elm;
if(typeof(this.element.id) === 'undefined' || this.element.id === null || this.element.id === '') {
// generate a random ID
this.element.id = 'ink-fv_randomid_'+(Math.round(Math.random() * 99999));
}
this.custom = options.customFlag;
this.confirmGroup = options.confirmGroup;
var fail = this._validateElements();
if(fail.length > 0) {
if(options.onError) {
options.onError(fail);
} else {
this._showError(elm, fail);
}
return false;
} else {
if(!options.onError) {
this._clearError(elm);
}
this._clearCache();
if(options.onSuccess) {
options.onSuccess();
}
return true;
}
},
/**
* Reset previously generated validation errors
*
* @method reset
* @public
*/
reset: function()
{
this._clearError();
this._clearCache();
},
/**
* Cleans the object
*
* @method _free
* @private
*/
_free: function()
{
this.element = null;
//this.elements = [];
this.custom = false;
this.confirmGroup = false;
},
/**
* Cleans the properties responsible for caching
*
* @method _clearCache
* @private
*/
_clearCache: function()
{
this.element = null;
this.elements = [];
this.custom = false;
this.confirmGroup = false;
},
/**
* Gets the form elements and stores them in the caching properties
*
* @method _getElements
* @private
*/
_getElements: function()
{
//this.elements = [];
// if(typeof(this.elements[this.element.id]) !== 'undefined') {
// return;
// }
this.elements[this.element.id] = [];
this.confirmElms[this.element.id] = [];
//console.log(this.element);
//console.log(this.element.elements);
var formElms = this.element.elements;
var curElm = false;
for(var i=0, totalElm = formElms.length; i < totalElm; i++) {
curElm = formElms[i];
if(curElm.getAttribute('type') !== null && curElm.getAttribute('type').toLowerCase() === 'radio') {
if(this.elements[this.element.id].length === 0 ||
(
curElm.getAttribute('type') !== this.elements[this.element.id][(this.elements[this.element.id].length - 1)].getAttribute('type') &&
curElm.getAttribute('name') !== this.elements[this.element.id][(this.elements[this.element.id].length - 1)].getAttribute('name')
)) {
for(var flag in this._flagMap) {
if(Css.hasClassName(curElm, flag)) {
this.elements[this.element.id].push(curElm);
break;
}
}
}
} else {
for(var flag2 in this._flagMap) {
if(Css.hasClassName(curElm, flag2) && flag2 !== 'ink-fv-confirm') {
/*if(flag2 == 'ink-fv-confirm') {
this.confirmElms[this.element.id].push(curElm);
this.hasConfirm[this.element.id] = true;
}*/
this.elements[this.element.id].push(curElm);
break;
}
}
if(Css.hasClassName(curElm, 'ink-fv-confirm')) {
this.confirmElms[this.element.id].push(curElm);
this.hasConfirm[this.element.id] = true;
}
}
}
//debugger;
},
/**
* Runs the validation for each element
*
* @method _validateElements
* @private
*/
_validateElements: function()
{
var oGroups;
this._getElements();
//console.log('HAS CONFIRM', this.hasConfirm);
if(typeof(this.hasConfirm[this.element.id]) !== 'undefined' && this.hasConfirm[this.element.id] === true) {
oGroups = this._makeConfirmGroups();
}
var errors = [];
var curElm = false;
var customErrors = false;
var inArray;
for(var i=0, totalElm = this.elements[this.element.id].length; i < totalElm; i++) {
inArray = false;
curElm = this.elements[this.element.id][i];
if(!curElm.disabled) {
for(var flag in this._flagMap) {
if(Css.hasClassName(curElm, flag)) {
if(flag !== 'ink-fv-custom' && flag !== 'ink-fv-confirm') {
if(!this._isValid(curElm, flag)) {
if(!inArray) {
errors.push({elm: curElm, errors:[flag]});
inArray = true;
} else {
errors[(errors.length - 1)].errors.push(flag);
}
}
} else if(flag !== 'ink-fv-confirm'){
customErrors = this._isCustomValid(curElm);
if(customErrors.length > 0) {
errors.push({elm: curElm, errors:[flag], custom: customErrors});
}
} else if(flag === 'ink-fv-confirm'){
}
}
}
}
}
errors = this._validateConfirmGroups(oGroups, errors);
//console.log(InkDumper.returnDump(errors));
return errors;
},
/**
* Runs the 'confirm' validation for each group of elements
*
* @method _validateConfirmGroups
* @param {Array} oGroups Array/Object that contains the group of confirm objects
* @param {Array} errors Array that will store the errors
* @private
* @return {Array} Array of errors that was passed as 2nd parameter (either changed, or not, depending if errors were found).
*/
_validateConfirmGroups: function(oGroups, errors)
{
//console.log(oGroups);
var curGroup = false;
for(var i in oGroups) {
if (oGroups.hasOwnProperty(i)) {
curGroup = oGroups[i];
if(curGroup.length === 2) {
if(curGroup[0].value !== curGroup[1].value) {
errors.push({elm:curGroup[1], errors:['ink-fv-confirm']});
}
}
}
}
return errors;
},
/**
* Creates the groups of 'confirm' objects
*
* @method _makeConfirmGroups
* @private
* @return {Array|Boolean} Returns the array of confirm elements or false on error.
*/
_makeConfirmGroups: function()
{
var oGroups;
if(this.confirmGroup && this.confirmGroup.length > 0) {
oGroups = {};
var curElm = false;
var curGroup = false;
//this.confirmElms[this.element.id];
for(var i=0, total=this.confirmElms[this.element.id].length; i < total; i++) {
curElm = this.confirmElms[this.element.id][i];
for(var j=0, totalG=this.confirmGroup.length; j < totalG; j++) {
curGroup = this.confirmGroup[j];
if(Css.hasClassName(curElm, curGroup)) {
if(typeof(oGroups[curGroup]) === 'undefined') {
oGroups[curGroup] = [curElm];
} else {
oGroups[curGroup].push(curElm);
}
}
}
}
return oGroups;
} else {
if(this.confirmElms[this.element.id].length === 2) {
oGroups = {
"ink-fv-confirm": [
this.confirmElms[this.element.id][0],
this.confirmElms[this.element.id][1]
]
};
}
return oGroups;
}
return false;
},
/**
* Validates an element with a custom validation
*
* @method _isCustomValid
* @param {DOMElemenmt} elm Element to be validated
* @private
* @return {Array} Array of errors. If no errors are found, results in an empty array.
*/
_isCustomValid: function(elm)
{
var customErrors = [];
var curFlag = false;
for(var i=0, tCustom = this.custom.length; i < tCustom; i++) {
curFlag = this.custom[i];
if(Css.hasClassName(elm, curFlag.flag)) {
if(!curFlag.callback(elm, curFlag.msg)) {
customErrors.push({flag: curFlag.flag, msg: curFlag.msg});
}
}
}
return customErrors;
},
/**
* Runs the normal validation functions for a specific element
*
* @method _isValid
* @param {DOMElement} elm DOMElement that will be validated
* @param {String} fieldType Rule to be validated. This must be one of the keys present in the _flagMap property.
* @private
* @return {Boolean} The result of the validation.
*/
_isValid: function(elm, fieldType)
{
switch(fieldType) {
case 'ink-fv-required':
if(elm.nodeName.toLowerCase() === 'select') {
if(elm.selectedIndex > 0) {
return true;
} else {
return false;
}
}
if(elm.getAttribute('type') !== 'checkbox' && elm.getAttribute('type') !== 'radio') {
if(this._trim(elm.value) !== '') {
return true;
}
} else if(elm.getAttribute('type') === 'checkbox') {
if(elm.checked === true) {
return true;
}
} else if(elm.getAttribute('type') === 'radio') { // get top radio
var aFormRadios = elm.form[elm.name];
if(typeof(aFormRadios.length) === 'undefined') {
aFormRadios = [aFormRadios];
}
var isChecked = false;
for(var i=0, totalRadio = aFormRadios.length; i < totalRadio; i++) {
if(aFormRadios[i].checked === true) {
isChecked = true;
}
}
return isChecked;
}
break;
case 'ink-fv-email':
if(this._trim(elm.value) === '') {
if(Css.hasClassName(elm, 'ink-fv-required')) {
return false;
} else {
return true;
}
} else {
if(InkValidator.mail(elm.value)) {
return true;
}
}
break;
case 'ink-fv-url':
if(this._trim(elm.value) === '') {
if(Css.hasClassName(elm, 'ink-fv-required')) {
return false;
} else {
return true;
}
} else {
if(InkValidator.url(elm.value)) {
return true;
}
}
break;
case 'ink-fv-number':
if(this._trim(elm.value) === '') {
if(Css.hasClassName(elm, 'ink-fv-required')) {
return false;
} else {
return true;
}
} else {
if(!isNaN(Number(elm.value))) {
return true;
}
}
break;
case 'ink-fv-phone_pt':
if(this._trim(elm.value) === '') {
if(Css.hasClassName(elm, 'ink-fv-required')) {
return false;
} else {
return true;
}
} else {
if(InkValidator.isPTPhone(elm.value)) {
return true;
}
}
break;
case 'ink-fv-phone_cv':
if(this._trim(elm.value) === '') {
if(Css.hasClassName(elm, 'ink-fv-required')) {
return false;
} else {
return true;
}
} else {
if(InkValidator.isCVPhone(elm.value)) {
return true;
}
}
break;
case 'ink-fv-phone_ao':
if(this._trim(elm.value) === '') {
if(Css.hasClassName(elm, 'ink-fv-required')) {
return false;
} else {
return true;
}
} else {
if(InkValidator.isAOPhone(elm.value)) {
return true;
}
}
break;
case 'ink-fv-phone_mz':
if(this._trim(elm.value) === '') {
if(Css.hasClassName(elm, 'ink-fv-required')) {
return false;
} else {
return true;
}
} else {
if(InkValidator.isMZPhone(elm.value)) {
return true;
}
}
break;
case 'ink-fv-date':
if(this._trim(elm.value) === '') {
if(Css.hasClassName(elm, 'ink-fv-required')) {
return false;
} else {
return true;
}
} else {
var Element = Ink.getModule('Ink.Dom.Element',1);
var dataset = Element.data( elm );
var validFormat = 'yyyy-mm-dd';
if( Css.hasClassName(elm, 'ink-datepicker') && ("format" in dataset) ){
validFormat = dataset.format;
} else if( ("validFormat" in dataset) ){
validFormat = dataset.validFormat;
}
if( !(validFormat in InkValidator._dateParsers ) ){
var validValues = [];
for( var val in InkValidator._dateParsers ){
if (InkValidator._dateParsers.hasOwnProperty(val)) {
validValues.push(val);
}
}
throw "The attribute data-valid-format must be one of the following values: " + validValues.join(',');
}
return InkValidator.isDate( validFormat, elm.value );
}
break;
case 'ink-fv-custom':
break;
}
return false;
},
/**
* Makes the necessary changes to the markup to show the errors of a given element
*
* @method _showError
* @param {DOMElement} formElm The form element to be changed to show the errors
* @param {Array} aFail An array with the errors found.
* @private
*/
_showError: function(formElm, aFail)
{
this._clearError(formElm);
//ink-warning-field
//console.log(aFail);
var curElm = false;
for(var i=0, tFail = aFail.length; i < tFail; i++) {
curElm = aFail[i].elm;
if(curElm.getAttribute('type') !== 'radio') {
var newLabel = document.createElement('p');
//newLabel.setAttribute('for',curElm.id);
//newLabel.className = this._errorClassName;
//newLabel.className += ' ' + this._errorTypeErrorClassName;
Css.addClassName(newLabel, this._errorClassName);
Css.addClassName(newLabel, this._errorTypeErrorClassName);
if(aFail[i].errors[0] !== 'ink-fv-custom') {
newLabel.innerHTML = this._flagMap[aFail[i].errors[0]].msg;
} else {
newLabel.innerHTML = aFail[i].custom[0].msg;
}
if(curElm.getAttribute('type') !== 'checkbox') {
curElm.nextSibling.parentNode.insertBefore(newLabel, curElm.nextSibling);
if(Css.hasClassName(curElm.parentNode, 'control')) {
Css.addClassName(curElm.parentNode.parentNode, 'validation');
if(aFail[i].errors[0] === 'ink-fv-required') {
Css.addClassName(curElm.parentNode.parentNode, 'error');
} else {
Css.addClassName(curElm.parentNode.parentNode, 'warning');
}
}
} else {
/* // TODO checkbox... does not work with this CSS
curElm.parentNode.appendChild(newLabel);
if(Css.hasClassName(curElm.parentNode.parentNode, 'control-group')) {
Css.addClassName(curElm.parentNode.parentNode, 'control');
Css.addClassName(curElm.parentNode.parentNode, 'validation');
Css.addClassName(curElm.parentNode.parentNode, 'error');
}*/
}
} else {
if(Css.hasClassName(curElm.parentNode.parentNode, 'control-group')) {
Css.addClassName(curElm.parentNode.parentNode, 'validation');
Css.addClassName(curElm.parentNode.parentNode, 'error');
}
}
}
},
/**
* Clears the error of a given element. Normally executed before any validation, for all elements, as a reset.
*
* @method _clearErrors
* @param {DOMElement} formElm Form element to be cleared.
* @private
*/
_clearError: function(formElm)
{
//return;
var aErrorLabel = formElm.getElementsByTagName('p');
var curElm = false;
for(var i = (aErrorLabel.length - 1); i >= 0; i--) {
curElm = aErrorLabel[i];
if(Css.hasClassName(curElm, this._errorClassName)) {
if(Css.hasClassName(curElm.parentNode, 'control')) {
Css.removeClassName(curElm.parentNode.parentNode, 'validation');
Css.removeClassName(curElm.parentNode.parentNode, 'error');
Css.removeClassName(curElm.parentNode.parentNode, 'warning');
}
if(Css.hasClassName(curElm,'tip') && Css.hasClassName(curElm,'error')){
curElm.parentNode.removeChild(curElm);
}
}
}
var aErrorLabel2 = formElm.getElementsByTagName('ul');
for(i = (aErrorLabel2.length - 1); i >= 0; i--) {
curElm = aErrorLabel2[i];
if(Css.hasClassName(curElm, 'control-group')) {
Css.removeClassName(curElm, 'validation');
Css.removeClassName(curElm, 'error');
}
}
},
/**
* Removes unnecessary spaces to the left or right of a string
*
* @method _trim
* @param {String} stri String to be trimmed
* @private
* @return {String|undefined} String trimmed.
*/
_trim: function(str)
{
if(typeof(str) === 'string')
{
return str.replace(/^\s+|\s+$|\n+$/g, '');
}
}
};
return FormValidator;
});
/**
* @module Ink.UI.Droppable_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule("Ink.UI.Droppable","1",["Ink.Dom.Element_1", "Ink.Dom.Event_1", "Ink.Dom.Css_1", "Ink.UI.Aux_1", "Ink.Util.Array_1", "Ink.Dom.Selector_1"], function( InkElement, InkEvent, Css, Aux, InkArray, Selector) {
// Higher order functions
var hAddClassName = function (element) {
return function (className) {return Css.addClassName(element, className);};
};
var hRemoveClassName = function (element) {
return function (className) {return Css.removeClassName(element, className);};
};
/**
* @class Ink.UI.Droppable
* @version 1
* @static
*/
var Droppable = {
/**
* Flag that determines if it's in debug mode or not
*
* @property debug
* @type {Boolean}
* @private
*/
debug: false,
/**
* Array with the data of each element (`{element: ..., data: ..., options: ...}`)
*
* @property _droppables
* @type {Array}
* @private
*/
_droppables: [],
/**
* Array of data for each draggable. (`{element: ..., data: ...}`)
*
* @property _draggables
* @type {Array}
* @private
*/
_draggables: [],
/**
* Makes an element droppable and adds it to the stack of droppable elements.
* Can consider it a constructor of droppable elements, but where no Droppable object is returned.
*
* In the following arguments, any events/callbacks you may pass, can be either functions or strings. If the 'move' or 'copy' strings are passed, the draggable gets moved into this droppable. If 'revert' is passed, an acceptable droppable is moved back to the element it came from.
*
* @method add
* @param {String|DOMElement} element Target element
* @param {Object} [options] options object
* @param {String} [options.hoverClass] Classname(s) applied when an acceptable draggable element is hovering the element
* @param {String} [options.accept] Selector for choosing draggables which can be dropped in this droppable.
* @param {Function} [options.onHover] callback called when an acceptable draggable element is hovering the droppable. Gets the draggable and the droppable element as parameters.
* @param {Function|String} [options.onDrop] callback called when an acceptable draggable element is dropped. Gets the draggable, the droppable and the event as parameters.
* @param {Function|String} [options.onDropOut] callback called when a droppable is dropped outside this droppable. Gets the draggable, the droppable and the event as parameters. (see above for string options).
* @public
*
* @example
*
* <style type="text/css">
* .hover {
* border: 1px solid red;
* }
* .left, .right {
* float: left; width: 50%;
* outline: 1px solid gray;
* min-height: 2em;
* }
* </style>
* <ul class="left">
* <li>Draggable 1</li>
* <li>Draggable 2</li>
* <li>Draggable 3</li>
* </ul>
* <ul class="right">
* </ul>
* <script type="text/javascript">
* Ink.requireModules(['Ink.UI.Draggable_1', 'Ink.UI.Droppable_1'], function (Draggable, Droppable) {
* new Draggable('.left li:eq(0)', {});
* new Draggable('.left li:eq(1)', {});
* new Draggable('.left li:eq(2)', {});
* Droppable.add('.left', {onDrop: 'move', onDropOut: 'revert'});
* Droppable.add('.right', {onDrop: 'move', onDropOut: 'revert'});
* })
* </script>
*
*/
add: function(element, options) {
element = Aux.elOrSelector(element, 'Droppable.add target element');
var opt = Ink.extendObj( {
hoverClass: options.hoverclass /* old name */ || false,
accept: false,
onHover: false,
onDrop: false,
onDropOut: false
}, options || {}, InkElement.data(element));
if (typeof opt.hoverClass === 'string') {
opt.hoverClass = opt.hoverClass.split(/\s+/);
}
function cleanStyle(draggable) {
draggable.style.position = 'inherit';
}
var that = this;
var namedEventHandlers = {
move: function (draggable, droppable, event) {
cleanStyle(draggable);
droppable.appendChild(draggable);
},
copy: function (draggable, droppable, event) {
cleanStyle(draggable);
droppable.appendChild(draggable.cloneNode);
},
revert: function (draggable, droppable, event) {
that._findDraggable(draggable).originalParent.appendChild(draggable);
cleanStyle(draggable);
}
};
var name;
if (typeof opt.onHover === 'string') {
name = opt.onHover;
opt.onHover = namedEventHandlers[name];
if (opt.onHover === undefined) {
throw new Error('Unknown hover event handler: ' + name);
}
}
if (typeof opt.onDrop === 'string') {
name = opt.onDrop;
opt.onDrop = namedEventHandlers[name];
if (opt.onDrop === undefined) {
throw new Error('Unknown drop event handler: ' + name);
}
}
if (typeof opt.onDropOut === 'string') {
name = opt.onDropOut;
opt.onDropOut = namedEventHandlers[name];
if (opt.onDropOut === undefined) {
throw new Error('Unknown dropOut event handler: ' + name);
}
}
var elementData = {
element: element,
data: {},
options: opt
};
this._droppables.push(elementData);
this._update(elementData);
},
/**
* find droppable data about `element`. this data is added in `.add`
*
* @method _findData
* @param {DOMElement} element Needle
* @return {object} Droppable data of the element
* @private
*/
_findData: function (element) {
var elms = this._droppables;
for (var i = 0, len = elms.length; i < len; i++) {
if (elms[i].element === element) {
return elms[i];
}
}
},
/**
* Find draggable data about `element`
*
* @method _findDraggable
* @param {DOMElement} element Needle
* @return {Object} Draggable data queried
* @private
*/
_findDraggable: function (element) {
var elms = this._draggables;
for (var i = 0, len = elms.length; i < len; i++) {
if (elms[i].element === element) {
return elms[i];
}
}
},
/**
* Invoke every time a drag starts
*
* @method updateAll
* @private
*/
updateAll: function() {
InkArray.each(this._droppables, Droppable._update);
},
/**
* Updates location and size of droppable element
*
* @method update * @param {String|DOMElement} element - target element
* @private
*/
update: function(element) {
this._update(this._findData(element));
},
_update: function(elementData) {
var data = elementData.data;
var element = elementData.element;
data.left = InkElement.offsetLeft(element);
data.top = InkElement.offsetTop( element);
data.right = data.left + InkElement.elementWidth( element);
data.bottom = data.top + InkElement.elementHeight(element);
},
/**
* Removes an element from the droppable stack and removes the droppable behavior
*
* @method remove
* @param {String|DOMElement} elOrSelector Droppable element to disable.
* @return {Boolean} Whether the object was found and deleted
* @public
*/
remove: function(el) {
el = Aux.elOrSelector(el);
var len = this._droppables.length;
for (var i = 0; i < len; i++) {
if (this._droppables[i].element === el) {
this._droppables.splice(i, 1);
break;
}
}
return len !== this._droppables.length;
},
/**
* Method called by a draggable to execute an action on a droppable
*
* @method action
* @param {Object} coords coordinates where the action happened
* @param {String} type type of action. drag or drop.
* @param {Object} ev Event object
* @param {Object} draggable draggable element
* @private
*/
action: function(coords, type, ev, draggable) {
// check all droppable elements
InkArray.each(this._droppables, Ink.bind(function(elementData) {
var data = elementData.data;
var opt = elementData.options;
var element = elementData.element;
if (opt.accept && !Selector.matches(opt.accept, [draggable]).length) {
return;
}
if (type === 'drag' && !this._findDraggable(draggable)) {
this._draggables.push({
element: draggable,
originalParent: draggable.parentNode
});
}
// check if our draggable is over our droppable
if (coords.x >= data.left && coords.x <= data.right &&
coords.y >= data.top && coords.y <= data.bottom) {
// INSIDE
if (type === 'drag') {
if (opt.hoverClass) {
InkArray.each(opt.hoverClass,
hAddClassName(element));
}
if (opt.onHover) {
opt.onHover(draggable, element);
}
} else if (type === 'drop') {
if (opt.hoverClass) {
InkArray.each(opt.hoverClass,
hRemoveClassName(element));
}
if (opt.onDrop) {
opt.onDrop(draggable, element, ev);
}
}
} else {
// OUTSIDE
if (type === 'drag' && opt.hoverClass) {
InkArray.each(opt.hoverClass, hRemoveClassName(element));
} else if (type === 'drop') {
if(opt.onDropOut){
opt.onDropOut(draggable, element, ev);
}
}
}
}, this));
}
};
return Droppable;
});
/*
* @module Ink.UI.Draggable_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule("Ink.UI.Draggable","1",["Ink.Dom.Element_1", "Ink.Dom.Event_1", "Ink.Dom.Css_1", "Ink.Dom.Browser_1", "Ink.Dom.Selector_1", "Ink.UI.Aux_1"],function( InkElement, InkEvent, Css, Browser, Selector, Aux) {
var x = 0,
y = 1; // For accessing coords in [x, y] arrays
// Get a value between two boundaries
function between (val, min, max) {
val = Math.min(val, max);
val = Math.max(val, min);
return val;
}
/**
* @class Ink.UI.Draggable
* @version 1
* @constructor
* @param {String|DOMElement} target Target element.
* @param {Object} [options] Optional object for configuring the component
* @param {String} [options.constraint] Movement constraint. None by default. Can be `vertical`, `horizontal`, or `both`.
* @param {String|DomElement} [options.constraintElm] Constrain dragging to be within this element. None by default.
* @param {Number} [options.top,left,right,bottom] Limits for constraining draggable movement.
* @param {String|DOMElement} [options.handle] if specified, this element will be used as a handle for dragging.
* @param {Boolean} [options.revert] if true, reverts the draggable to the original position when dragging stops
* @param {String} [options.cursor] cursor type (CSS `cursor` value) used when the mouse is over the draggable object
* @param {Number} [options.zIndex] zindex applied to the draggable element while dragged
* @param {Number} [options.fps] if defined, on drag will run every n frames per second only
* @param {DomElement} [options.droppableProxy] if set, a shallow copy of the droppableProxy will be put on document.body with transparent bg
* @param {String} [options.mouseAnchor] defaults to mouse cursor. can be 'left|center|right top|center|bottom'
* @param {String} [options.dragClass='drag'] class to add when the draggable is being dragged.
* @param {Function} [options.onStart] callback called when dragging starts
* @param {Function} [options.onEnd] callback called when dragging stops
* @param {Function} [options.onDrag] callback called while dragging, prior to position updates
* @param {Function} [options.onChange] callback called while dragging, after position updates
* @example
* Ink.requireModules( ['Ink.UI.Draggable_1'], function( Draggable ){
* new Draggable( '#myElementId' );
* });
*/
var Draggable = function(element, options) {
this.init(element, options);
};
Draggable.prototype = {
/**
* Init function called by the constructor
*
* @method _init
* @param {String|DOMElement} element ID of the element or DOM Element.
* @param {Object} [options] Options object for configuration of the module.
* @private
*/
init: function(element, options) {
var o = Ink.extendObj( {
constraint: false,
constraintElm: false,
top: false,
right: false,
bottom: false,
left: false,
handle: options.handler /* old option name */ || false,
revert: false,
cursor: 'move',
zindex: options.zindex /* old option name */ || 9999,
dragClass: 'drag',
onStart: false,
onEnd: false,
onDrag: false,
onChange: false,
droppableProxy: false,
mouseAnchor: undefined,
skipChildren: true,
fps: 100,
debug: false
}, options || {}, InkElement.data(element));
this.options = o;
this.element = Aux.elOrSelector(element);
this.constraintElm = o.constraintElm && Aux.elOrSelector(o.constraintElm);
this.handle = false;
this.elmStartPosition = false;
this.active = false;
this.dragged = false;
this.prevCoords = false;
this.placeholder = false;
this.position = false;
this.zindex = false;
this.firstDrag = true;
if (o.fps) {
this.deltaMs = 1000 / o.fps;
this.lastRunAt = 0;
}
this.handlers = {};
this.handlers.start = Ink.bindEvent(this._onStart,this);
this.handlers.dragFacade = Ink.bindEvent(this._onDragFacade,this);
this.handlers.drag = Ink.bindEvent(this._onDrag,this);
this.handlers.end = Ink.bindEvent(this._onEnd,this);
this.handlers.selectStart = function(event) { InkEvent.stop(event); return false; };
// set handle
this.handle = (this.options.handle) ?
Aux.elOrSelector(this.options.handle) : this.element;
this.handle.style.cursor = o.cursor;
InkEvent.observe(this.handle, 'touchstart', this.handlers.start);
InkEvent.observe(this.handle, 'mousedown', this.handlers.start);
if (Browser.IE) {
InkEvent.observe(this.element, 'selectstart', this.handlers.selectStart);
}
},
/**
* Removes the ability of the element of being dragged
*
* @method destroy
* @public
*/
destroy: function() {
InkEvent.stopObserving(this.handle, 'touchstart', this.handlers.start);
InkEvent.stopObserving(this.handle, 'mousedown', this.handlers.start);
if (Browser.IE) {
InkEvent.stopObserving(this.element, 'selectstart', this.handlers.selectStart);
}
},
/**
* Gets coordinates for a given event (with added page scroll)
*
* @method _getCoords
* @param {Object} e window.event object.
* @return {Array} Array where the first position is the x coordinate, the second is the y coordinate
* @private
*/
_getCoords: function(e) {
var ps = [InkElement.scrollWidth(), InkElement.scrollHeight()];
return {
x: (e.touches ? e.touches[0].clientX : e.clientX) + ps[x],
y: (e.touches ? e.touches[0].clientY : e.clientY) + ps[y]
};
},
/**
* Clones src element's relevant properties to dst
*
* @method _cloneStyle
* @param {DOMElement} src Element from where we're getting the styles
* @param {DOMElement} dst Element where we're placing the styles.
* @private
*/
_cloneStyle: function(src, dst) {
dst.className = src.className;
dst.style.borderWidth = '0';
dst.style.padding = '0';
dst.style.position = 'absolute';
dst.style.width = InkElement.elementWidth(src) + 'px';
dst.style.height = InkElement.elementHeight(src) + 'px';
dst.style.left = InkElement.elementLeft(src) + 'px';
dst.style.top = InkElement.elementTop(src) + 'px';
dst.style.cssFloat = Css.getStyle(src, 'float');
dst.style.display = Css.getStyle(src, 'display');
},
/**
* onStart event handler
*
* @method _onStart
* @param {Object} e window.event object
* @return {Boolean|void} In some cases return false. Otherwise is void
* @private
*/
_onStart: function(e) {
if (!this.active && InkEvent.isLeftClick(e) || typeof e.button === 'undefined') {
var tgtEl = InkEvent.element(e);
if (this.options.skipChildren && tgtEl !== this.handle) { return; }
InkEvent.stop(e);
Css.addClassName(this.element, this.options.dragClass);
this.elmStartPosition = [
InkElement.elementLeft(this.element),
InkElement.elementTop( this.element)
];
var pos = [
parseInt(Css.getStyle(this.element, 'left'), 10),
parseInt(Css.getStyle(this.element, 'top'), 10)
];
var dims = InkElement.elementDimensions(this.element);
this.originalPosition = [ pos[x] ? pos[x]: null, pos[y] ? pos[y] : null ];
this.delta = this._getCoords(e); // mouse coords at beginning of drag
this.active = true;
this.position = Css.getStyle(this.element, 'position');
this.zindex = Css.getStyle(this.element, 'zIndex');
var div = document.createElement('div');
div.style.position = this.position;
div.style.width = dims[x] + 'px';
div.style.height = dims[y] + 'px';
div.style.marginTop = Css.getStyle(this.element, 'margin-top');
div.style.marginBottom = Css.getStyle(this.element, 'margin-bottom');
div.style.marginLeft = Css.getStyle(this.element, 'margin-left');
div.style.marginRight = Css.getStyle(this.element, 'margin-right');
div.style.borderWidth = '0';
div.style.padding = '0';
div.style.cssFloat = Css.getStyle(this.element, 'float');
div.style.display = Css.getStyle(this.element, 'display');
div.style.visibility = 'hidden';
this.delta2 = [ this.delta.x - this.elmStartPosition[x], this.delta.y - this.elmStartPosition[y] ]; // diff between top-left corner of obj and mouse
if (this.options.mouseAnchor) {
var parts = this.options.mouseAnchor.split(' ');
var ad = [dims[x], dims[y]]; // starts with 'right bottom'
if (parts[0] === 'left') { ad[x] = 0; } else if(parts[0] === 'center') { ad[x] = parseInt(ad[x]/2, 10); }
if (parts[1] === 'top') { ad[y] = 0; } else if(parts[1] === 'center') { ad[y] = parseInt(ad[y]/2, 10); }
this.applyDelta = [this.delta2[x] - ad[x], this.delta2[y] - ad[y]];
}
var dragHandlerName = this.options.fps ? 'dragFacade' : 'drag';
this.placeholder = div;
if (this.options.onStart) { this.options.onStart(this.element, e); }
if (this.options.droppableProxy) { // create new transparent div to optimize DOM traversal during drag
this.proxy = document.createElement('div');
dims = [
window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
];
var fs = this.proxy.style;
fs.width = dims[x] + 'px';
fs.height = dims[y] + 'px';
fs.position = 'fixed';
fs.left = '0';
fs.top = '0';
fs.zIndex = this.options.zindex + 1;
fs.backgroundColor = '#FF0000';
Css.setOpacity(this.proxy, 0);
var firstEl = document.body.firstChild;
while (firstEl && firstEl.nodeType !== 1) { firstEl = firstEl.nextSibling; }
document.body.insertBefore(this.proxy, firstEl);
InkEvent.observe(this.proxy, 'mousemove', this.handlers[dragHandlerName]);
InkEvent.observe(this.proxy, 'touchmove', this.handlers[dragHandlerName]);
}
else {
InkEvent.observe(document, 'mousemove', this.handlers[dragHandlerName]);
}
this.element.style.position = 'absolute';
this.element.style.zIndex = this.options.zindex;
this.element.parentNode.insertBefore(this.placeholder, this.element);
this._onDrag(e);
InkEvent.observe(document, 'mouseup', this.handlers.end);
InkEvent.observe(document, 'touchend', this.handlers.end);
return false;
}
},
/**
* Function that gets the timestamp of the current run from time to time. (FPS)
*
* @method _onDragFacade
* @param {Object} window.event object.
* @private
*/
_onDragFacade: function(e) {
var now = +new Date();
if (!this.lastRunAt || now > this.lastRunAt + this.deltaMs) {
this.lastRunAt = now;
this._onDrag(e);
}
},
/**
* Function that handles the dragging movement
*
* @method _onDrag
* @param {Object} window.event object.
* @private
*/
_onDrag: function(e) {
if (this.active) {
InkEvent.stop(e);
this.dragged = true;
var mouseCoords = this._getCoords(e),
mPosX = mouseCoords.x,
mPosY = mouseCoords.y,
o = this.options,
newX = false,
newY = false;
if (this.prevCoords && mPosX !== this.prevCoords.x || mPosY !== this.prevCoords.y) {
if (o.onDrag) { o.onDrag(this.element, e); }
this.prevCoords = mouseCoords;
newX = this.elmStartPosition[x] + mPosX - this.delta.x;
newY = this.elmStartPosition[y] + mPosY - this.delta.y;
var draggableSize = InkElement.elementDimensions(this.element);
if (this.constraintElm) {
var offset = InkElement.offset(this.constraintElm);
var size = InkElement.elementDimensions(this.constraintElm);
var constTop = offset[y] + (o.top || 0),
constBottom = offset[y] + size[y] - (o.bottom || 0),
constLeft = offset[x] + (o.left || 0),
constRight = offset[x] + size[x] - (o.right || 0);
newY = between(newY, constTop, constBottom - draggableSize[y]);
newX = between(newX, constLeft, constRight - draggableSize[x]);
} else if (o.constraint) {
var right = o.right === false ? InkElement.pageWidth() - draggableSize[x] : o.right,
left = o.left === false ? 0 : o.left,
top = o.top === false ? 0 : o.top,
bottom = o.bottom === false ? InkElement.pageHeight() - draggableSize[y] : o.bottom;
if (o.constraint === 'horizontal' || o.constraint === 'both') {
newX = between(newX, left, right);
}
if (o.constraint === 'vertical' || o.constraint === 'both') {
newY = between(newY, top, bottom);
}
}
var Droppable = Ink.getModule('Ink.UI.Droppable_1');
if (this.firstDrag) {
if (Droppable) { Droppable.updateAll(); }
/*this.element.style.position = 'absolute';
this.element.style.zIndex = this.options.zindex;
this.element.parentNode.insertBefore(this.placeholder, this.element);*/
this.firstDrag = false;
}
if (newX) { this.element.style.left = newX + 'px'; }
if (newY) { this.element.style.top = newY + 'px'; }
if (Droppable) {
// apply applyDelta defined on drag init
var mouseCoords2 = this.options.mouseAnchor ?
{x: mPosX - this.applyDelta[x], y: mPosY - this.applyDelta[y]} :
mouseCoords;
Droppable.action(mouseCoords2, 'drag', e, this.element);
}
if (o.onChange) { o.onChange(this); }
}
}
},
/**
* Function that handles the end of the dragging process
*
* @method _onEnd
* @param {Object} window.event object.
* @private
*/
_onEnd: function(e) {
InkEvent.stopObserving(document, 'mousemove', this.handlers.drag);
InkEvent.stopObserving(document, 'touchmove', this.handlers.drag);
if (this.options.fps) {
this._onDrag(e);
}
Css.removeClassName(this.element, this.options.dragClass);
if (this.active && this.dragged) {
if (this.options.droppableProxy) { // remove transparent div...
document.body.removeChild(this.proxy);
}
if (this.pt) { // remove debugging element...
InkElement.remove(this.pt);
this.pt = undefined;
}
/*if (this.options.revert) {
this.placeholder.parentNode.removeChild(this.placeholder);
}*/
if(this.placeholder) {
InkElement.remove(this.placeholder);
}
if (this.options.revert) {
this.element.style.position = this.position;
if (this.zindex !== null) {
this.element.style.zIndex = this.zindex;
}
else {
this.element.style.zIndex = 'auto';
} // restore default zindex of it had none
this.element.style.left = (this.originalPosition[x]) ? this.originalPosition[x] + 'px' : '';
this.element.style.top = (this.originalPosition[y]) ? this.originalPosition[y] + 'px' : '';
}
if (this.options.onEnd) {
this.options.onEnd(this.element, e);
}
var Droppable = Ink.getModule('Ink.UI.Droppable_1');
if (Droppable) {
Droppable.action(this._getCoords(e), 'drop', e, this.element);
}
this.position = false;
this.zindex = false;
this.firstDrag = true;
}
this.active = false;
this.dragged = false;
}
};
return Draggable;
});
/**
* @module Ink.UI.DatePicker_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.DatePicker', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1','Ink.Util.Date_1', 'Ink.Dom.Browser_1'], function(Aux, Event, Css, Element, Selector, InkArray, InkDate ) {
'use strict';
/**
* @class Ink.UI.DatePicker
* @constructor
* @version 1
*
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {String} [options.instance] unique id for the datepicker
* @param {String} [options.format] Date format string
* @param {String} [options.cssClass] CSS class to be applied to the datepicker
* @param {String} [options.position] position the datepicker. Accept right or bottom, default is right
* @param {Boolean} [options.onFocus] if the datepicker should open when the target element is focused
* @param {Function} [options.onYearSelected] callback function to execute when the year is selected
* @param {Function} [options.onMonthSelected] callback function to execute when the month is selected
* @param {Function} [options.validDayFn] callback function to execute when 'rendering' the day (in the month view)
* @param {String} [options.startDate] Date to define init month. Must be in yyyy-mm-dd format
* @param {Function} [options.onSetDate] callback to execute when set date
* @param {Boolean} [options.displayInSelect] whether to display the component in a select. defaults to false.
* @param {Boolean} [options.showClose] whether to display the close button or not. defaults to true.
* @param {Boolean} [options.showClean] whether to display the clean button or not. defaults to true.
* @param {String} [options.yearRange] enforce limits to year for the Date, ex: '1990:2020' (deprecated)
* @param {String} [options.dateRange] enforce limits to year, month and day for the Date, ex: '1990-08-25:2020-11'
* @param {Number} [options.startWeekDay] day to use as first column on the calendar view. Defaults to Monday (1)
* @param {String} [options.closeText] text to display on close button. defaults to 'Fechar'
* @param {String} [options.cleanText] text to display on clean button. defaults to 'Limpar'
* @param {String} [options.prevLinkText] text to display on the previous button. defaults to '«'
* @param {String} [options.nextLinkText] text to display on the previous button. defaults to '«'
* @param {String} [options.ofText] text to display between month and year. defaults to ' de '
* @param {Object} [options.month] Hash of month names. Defaults to portuguese month names. January is 1.
* @param {Object} [options.wDay] Hash of weekdays. Defaults to portuguese month names. Sunday is 0.
*
* @example
* <input type="text" id="dPicker" />
* <script>
* Ink.requireModules(['Ink.Dom.Selector_1','Ink.UI.DatePicker_1'],function( Selector, DatePicker ){
* var datePickerElement = Ink.s('#dPicker');
* var datePickerObj = new DatePicker( datePickerElement );
* });
* </script>
*/
var DatePicker = function(selector, options) {
if (selector) {
this._dataField = Aux.elOrSelector(selector, '1st argument');
}
this._options = Ink.extendObj({
instance: 'scdp_' + Math.round(99999*Math.random()),
format: 'yyyy-mm-dd',
cssClass: 'sapo_component_datepicker',
position: 'right',
onFocus: true,
onYearSelected: undefined,
onMonthSelected: undefined,
validDayFn: undefined,
startDate: false, // format yyyy-mm-dd
onSetDate: false,
displayInSelect: false,
showClose: true,
showClean: true,
yearRange: false,
dateRange: false,
startWeekDay: 1,
closeText: 'Close',
cleanText: 'Clear',
prevLinkText: '«',
nextLinkText: '»',
ofText: ' de ',
month: {
1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:'September',
10:'October',
11:'November',
12:'December'
},
wDay: {
0:'Sunday',
1:'Monday',
2:'Tuesday',
3:'Wednesday',
4:'Thursday',
5:'Friday',
6:'Saturday'
}
}, Element.data(this._dataField) || {});
this._options = Ink.extendObj(this._options, options || {});
this._options.format = this._dateParsers[ this._options.format ] || this._options.format;
this._hoverPicker = false;
this._picker = null;
if (this._options.pickerField) {
this._picker = Aux.elOrSelector(this._options.pickerField, 'pickerField');
}
this._today = new Date();
this._day = this._today.getDate( );
this._month = this._today.getMonth( );
this._year = this._today.getFullYear( );
this._setMinMax( this._options.dateRange || this._options.yearRange );
this._data = new Date( Date.UTC.apply( this , this._checkDateRange( this._year , this._month , this._day ) ) );
if(this._options.startDate && typeof this._options.startDate === 'string' && /\d\d\d\d\-\d\d\-\d\d/.test(this._options.startDate)) {
this.setDate( this._options.startDate );
}
this._init();
this._render();
if ( !this._options.startDate ){
if( this._dataField && typeof this._dataField.value === 'string' && this._dataField.value){
this.setDate( this._dataField.value );
}
}
Aux.registerInstance(this, this._containerObject, 'datePicker');
};
DatePicker.prototype = {
version: '0.1',
/**
* Initialization function. Called by the constructor and
* receives the same parameters.
*
* @method _init
* @private
*/
_init: function(){
Ink.extendObj(this._options,this._lang || {});
},
/**
* Renders the DatePicker's markup
*
* @method _render
* @private
*/
_render: function() {
/*jshint maxstatements:100, maxcomplexity:30 */
this._containerObject = document.createElement('div');
this._containerObject.id = this._options.instance;
this._containerObject.className = 'sapo_component_datepicker';
var dom = document.getElementsByTagName('body')[0];
if(this._options.showClose || this._options.showClean){
this._superTopBar = document.createElement("div");
this._superTopBar.className = 'sapo_cal_top_options';
if(this._options.showClean){
var clean = document.createElement('a');
clean.className = 'clean';
clean.innerHTML = this._options.cleanText;
this._superTopBar.appendChild(clean);
}
if(this._options.showClose){
var close = document.createElement('a');
close.className = 'close';
close.innerHTML = this._options.closeText;
this._superTopBar.appendChild(close);
}
this._containerObject.appendChild(this._superTopBar);
}
var calendarTop = document.createElement("div");
calendarTop.className = 'sapo_cal_top';
this._monthDescContainer = document.createElement("div");
this._monthDescContainer.className = 'sapo_cal_month_desc';
this._monthPrev = document.createElement('div');
this._monthPrev.className = 'sapo_cal_prev';
this._monthPrev.innerHTML ='<a href="#prev" class="change_month_prev">' + this._options.prevLinkText + '</a>';
this._monthNext = document.createElement('div');
this._monthNext.className = 'sapo_cal_next';
this._monthNext.innerHTML ='<a href="#next" class="change_month_next">' + this._options.nextLinkText + '</a>';
calendarTop.appendChild(this._monthPrev);
calendarTop.appendChild(this._monthDescContainer);
calendarTop.appendChild(this._monthNext);
this._monthContainer = document.createElement("div");
this._monthContainer.className = 'sapo_cal_month';
this._containerObject.appendChild(calendarTop);
this._containerObject.appendChild(this._monthContainer);
this._monthSelector = document.createElement('ul');
this._monthSelector.className = 'sapo_cal_month_selector';
var ulSelector;
var liMonth;
for(var i=1; i<=12; i++){
if ((i-1) % 4 === 0) {
ulSelector = document.createElement('ul');
}
liMonth = document.createElement('li');
liMonth.innerHTML = '<a href="#" class="sapo_calmonth_' + ( (String(i).length === 2) ? i : "0" + i) + '">' + this._options.month[i].substring(0,3) + '</a>';
ulSelector.appendChild(liMonth);
if (i % 4 === 0) {
this._monthSelector.appendChild(ulSelector);
}
}
this._containerObject.appendChild(this._monthSelector);
this._yearSelector = document.createElement('ul');
this._yearSelector.className = 'sapo_cal_year_selector';
this._containerObject.appendChild(this._yearSelector);
if(!this._options.onFocus || this._options.displayInSelect){
if(!this._options.pickerField){
this._picker = document.createElement('a');
this._picker.href = '#open_cal';
this._picker.innerHTML = 'open';
this._picker.style.position = 'absolute';
this._picker.style.top = Element.elementTop(this._dataField);
this._picker.style.left = Element.elementLeft(this._dataField) + (Element.elementWidth(this._dataField) || 0) + 5 + 'px';
this._dataField.parentNode.appendChild(this._picker);
this._picker.className = 'sapo_cal_date_picker';
} else {
this._picker = Aux.elOrSelector(this._options.pickerField, 'pickerField');
}
}
if(this._options.displayInSelect){
if (this._options.dayField && this._options.monthField && this._options.yearField || this._options.pickerField) {
this._options.dayField = Aux.elOrSelector(this._options.dayField, 'dayField');
this._options.monthField = Aux.elOrSelector(this._options.monthField, 'monthField');
this._options.yearField = Aux.elOrSelector(this._options.yearField, 'yearField');
}
else {
throw "To use display in select you *MUST* to set dayField, monthField, yearField and pickerField!";
}
}
dom.insertBefore(this._containerObject, dom.childNodes[0]);
// this._dataField.parentNode.appendChild(this._containerObject, dom.childNodes[0]);
if (!this._picker) {
Event.observe(this._dataField,'focus',Ink.bindEvent(function(){
this._containerObject = Element.clonePosition(this._containerObject, this._dataField);
if ( this._options.position === 'bottom' )
{
this._containerObject.style.top = Element.elementHeight(this._dataField) + Element.offsetTop(this._dataField) + 'px';
this._containerObject.style.left = Element.offset(this._dataField)[0] +'px';
}
else
{
this._containerObject.style.top = Element.offset(this._dataField)[1] +'px';
this._containerObject.style.left = Element.elementWidth(this._dataField) + Element.offset(this._dataField)[0] +'px';
}
//dom.appendChild(this._containerObject);
this._updateDate();
this._showMonth();
this._containerObject.style.display = 'block';
},this));
}
else {
Event.observe(this._picker,'click',Ink.bindEvent(function(e){
Event.stop(e);
this._containerObject = Element.clonePosition(this._containerObject,this._picker);
this._updateDate();
this._showMonth();
this._containerObject.style.display = 'block';
},this));
}
if(!this._options.displayInSelect){
Event.observe(this._dataField,'change', Ink.bindEvent(function() {
this._updateDate( );
this._showDefaultView( );
this.setDate( );
if ( !this._hoverPicker )
{
this._containerObject.style.display = 'none';
}
},this));
Event.observe(this._dataField,'blur', Ink.bindEvent(function() {
if ( !this._hoverPicker )
{
this._containerObject.style.display = 'none';
}
},this));
}
else {
Event.observe(this._options.dayField,'change', Ink.bindEvent(function(){
var yearSelected = this._options.yearField[this._options.yearField.selectedIndex].value;
if(yearSelected !== '' && yearSelected !== 0) {
this._updateDate();
this._showDefaultView();
}
},this));
Event.observe(this._options.monthField,'change', Ink.bindEvent(function(){
var yearSelected = this._options.yearField[this._options.yearField.selectedIndex].value;
if(yearSelected !== '' && yearSelected !== 0){
this._updateDate();
this._showDefaultView();
}
},this));
Event.observe(this._options.yearField,'change', Ink.bindEvent(function(){
this._updateDate();
this._showDefaultView();
},this));
}
Event.observe(document,'click',Ink.bindEvent(function(e){
if (e.target === undefined) { e.target = e.srcElement; }
if (!Element.descendantOf(this._containerObject, e.target) && e.target !== this._dataField) {
if (!this._picker) {
this._containerObject.style.display = 'none';
}
else if (e.target !== this._picker &&
(!this._options.displayInSelect ||
(e.target !== this._options.dayField && e.target !== this._options.monthField && e.target !== this._options.yearField) ) ) {
if (!this._options.dayField ||
(!Element.descendantOf(this._options.dayField, e.target) &&
!Element.descendantOf(this._options.monthField, e.target) &&
!Element.descendantOf(this._options.yearField, e.target) ) ) {
this._containerObject.style.display = 'none';
}
}
}
},this));
this._showMonth();
this._monthChanger = document.createElement('a');
this._monthChanger.href = '#monthchanger';
this._monthChanger.className = 'sapo_cal_link_month';
this._monthChanger.innerHTML = this._options.month[this._month + 1];
this._deText = document.createElement('span');
this._deText.innerHTML = this._options._deText;
this._yearChanger = document.createElement('a');
this._yearChanger.href = '#yearchanger';
this._yearChanger.className = 'sapo_cal_link_year';
this._yearChanger.innerHTML = this._year;
this._monthDescContainer.innerHTML = '';
this._monthDescContainer.appendChild(this._monthChanger);
this._monthDescContainer.appendChild(this._deText);
this._monthDescContainer.appendChild(this._yearChanger);
Event.observe(this._containerObject,'mouseover',Ink.bindEvent(function(e)
{
Event.stop( e );
this._hoverPicker = true;
},this));
Event.observe(this._containerObject,'mouseout',Ink.bindEvent(function(e)
{
Event.stop( e );
this._hoverPicker = false;
},this));
Event.observe(this._containerObject,'click',Ink.bindEvent(function(e){
if(typeof(e.target) === 'undefined'){
e.target = e.srcElement;
}
var className = e.target.className;
var isInactive = className.indexOf( 'sapo_cal_off' ) !== -1;
Event.stop(e);
if( className.indexOf('sapo_cal_') === 0 && !isInactive ){
var day = className.substr( 9 , 2 );
if( Number( day ) ) {
this.setDate( this._year + '-' + ( this._month + 1 ) + '-' + day );
this._containerObject.style.display = 'none';
} else if(className === 'sapo_cal_link_month'){
this._monthContainer.style.display = 'none';
this._yearSelector.style.display = 'none';
this._monthPrev.childNodes[0].className = 'action_inactive';
this._monthNext.childNodes[0].className = 'action_inactive';
this._setActiveMonth();
this._monthSelector.style.display = 'block';
} else if(className === 'sapo_cal_link_year'){
this._monthPrev.childNodes[0].className = 'action_inactive';
this._monthNext.childNodes[0].className = 'action_inactive';
this._monthSelector.style.display = 'none';
this._monthContainer.style.display = 'none';
this._showYearSelector();
this._yearSelector.style.display = 'block';
}
} else if( className.indexOf("sapo_calmonth_") === 0 && !isInactive ){
var month=className.substr(14,2);
if(Number(month)){
this._month = month - 1;
// if( typeof this._options.onMonthSelected === 'function' ){
// this._options.onMonthSelected(this, {
// 'year': this._year,
// 'month' : this._month
// });
// }
this._monthSelector.style.display = 'none';
this._monthPrev.childNodes[0].className = 'change_month_prev';
this._monthNext.childNodes[0].className = 'change_month_next';
if ( this._year < this._yearMin || this._year === this._yearMin && this._month <= this._monthMin ){
this._monthPrev.childNodes[0].className = 'action_inactive';
}
else if( this._year > this._yearMax || this._year === this._yearMax && this._month >= this._monthMax ){
this._monthNext.childNodes[0].className = 'action_inactive';
}
this._updateCal();
this._monthContainer.style.display = 'block';
}
} else if( className.indexOf("sapo_calyear_") === 0 && !isInactive ){
var year=className.substr(13,4);
if(Number(year)){
this._year = year;
if( typeof this._options.onYearSelected === 'function' ){
this._options.onYearSelected(this, {
'year': this._year
});
}
this._monthPrev.childNodes[0].className = 'action_inactive';
this._monthNext.childNodes[0].className = 'action_inactive';
this._yearSelector.style.display='none';
this._setActiveMonth();
this._monthSelector.style.display='block';
}
} else if( className.indexOf('change_month_') === 0 && !isInactive ){
if(className === 'change_month_next'){
this._updateCal(1);
} else if(className === 'change_month_prev'){
this._updateCal(-1);
}
} else if( className.indexOf('change_year_') === 0 && !isInactive ){
if(className === 'change_year_next'){
this._showYearSelector(1);
} else if(className === 'change_year_prev'){
this._showYearSelector(-1);
}
} else if(className === 'clean'){
if(this._options.displayInSelect){
this._options.yearField.selectedIndex = 0;
this._options.monthField.selectedIndex = 0;
this._options.dayField.selectedIndex = 0;
} else {
this._dataField.value = '';
}
} else if(className === 'close'){
this._containerObject.style.display = 'none';
}
this._updateDescription();
},this));
},
/**
* Sets the range of dates allowed to be selected in the Date Picker
*
* @method _setMinMax
* @param {String} dateRange Two dates separated by a ':'. Example: 2013-01-01:2013-12-12
* @private
*/
_setMinMax : function( dateRange )
{
var auxDate;
if( dateRange )
{
var dates = dateRange.split( ':' );
var pattern = /^(\d{4})((\-)(\d{1,2})((\-)(\d{1,2}))?)?$/;
if ( dates[ 0 ] )
{
if ( dates[ 0 ] === 'NOW' )
{
this._yearMin = this._today.getFullYear( );
this._monthMin = this._today.getMonth( ) + 1;
this._dayMin = this._today.getDate( );
}
else if ( pattern.test( dates[ 0 ] ) )
{
auxDate = dates[ 0 ].split( '-' );
this._yearMin = Math.floor( auxDate[ 0 ] );
this._monthMin = Math.floor( auxDate[ 1 ] ) || 1;
this._dayMin = Math.floor( auxDate[ 2 ] ) || 1;
if ( 1 < this._monthMin && this._monthMin > 12 )
{
this._monthMin = 1;
this._dayMin = 1;
}
if ( 1 < this._dayMin && this._dayMin > this._daysInMonth( this._yearMin , this._monthMin ) )
{
this._dayMin = 1;
}
}
else
{
this._yearMin = Number.MIN_VALUE;
this._monthMin = 1;
this._dayMin = 1;
}
}
if ( dates[ 1 ] )
{
if ( dates[ 1 ] === 'NOW' )
{
this._yearMax = this._today.getFullYear( );
this._monthMax = this._today.getMonth( ) + 1;
this._dayMax = this._today.getDate( );
}
else if ( pattern.test( dates[ 1 ] ) )
{
auxDate = dates[ 1 ].split( '-' );
this._yearMax = Math.floor( auxDate[ 0 ] );
this._monthMax = Math.floor( auxDate[ 1 ] ) || 12;
this._dayMax = Math.floor( auxDate[ 2 ] ) || this._daysInMonth( this._yearMax , this._monthMax );
if ( 1 < this._monthMax && this._monthMax > 12 )
{
this._monthMax = 12;
this._dayMax = 31;
}
var MDay = this._daysInMonth( this._yearMax , this._monthMax );
if ( 1 < this._dayMax && this._dayMax > MDay )
{
this._dayMax = MDay;
}
}
else
{
this._yearMax = Number.MAX_VALUE;
this._monthMax = 12;
this._dayMax = 31;
}
}
if ( !( this._yearMax >= this._yearMin && (this._monthMax > this._monthMin || ( (this._monthMax === this._monthMin) && (this._dayMax >= this._dayMin) ) ) ) )
{
this._yearMin = Number.MIN_VALUE;
this._monthMin = 1;
this._dayMin = 1;
this._yearMax = Number.MAX_VALUE;
this._monthMax = 12;
this._dayMaXx = 31;
}
}
else
{
this._yearMin = Number.MIN_VALUE;
this._monthMin = 1;
this._dayMin = 1;
this._yearMax = Number.MAX_VALUE;
this._monthMax = 12;
this._dayMax = 31;
}
},
/**
* Checks if a date is between the valid range.
* Starts by checking if the date passed is valid. If not, will fallback to the 'today' date.
* Then checks if the all params are inside of the date range specified. If not, it will fallback to the nearest valid date (either Min or Max).
*
* @method _checkDateRange
* @param {Number} year Year with 4 digits (yyyy)
* @param {Number} month Month
* @param {Number} day Day
* @return {Array} Array with the final processed date.
* @private
*/
_checkDateRange : function( year , month , day )
{
if ( !this._isValidDate( year , month + 1 , day ) )
{
year = this._today.getFullYear( );
month = this._today.getMonth( );
day = this._today.getDate( );
}
if ( year > this._yearMax )
{
year = this._yearMax;
month = this._monthMax - 1;
day = this._dayMax;
}
else if ( year < this._yearMin )
{
year = this._yearMin;
month = this._monthMin - 1;
day = this._dayMin;
}
if ( year === this._yearMax && month + 1 > this._monthMax )
{
month = this._monthMax - 1;
day = this._dayMax;
}
else if ( year === this._yearMin && month + 1 < this._monthMin )
{
month = this._monthMin - 1;
day = this._dayMin;
}
if ( year === this._yearMax && month + 1 === this._monthMax && day > this._dayMax ){ day = this._dayMax; }
else if ( year === this._yearMin && month + 1 === this._monthMin && day < this._dayMin ){ day = this._dayMin; }
else if ( day > this._daysInMonth( year , month + 1 ) ){ day = this._daysInMonth( year , month + 1 ); }
return [ year , month , day ];
},
/**
* Sets the markup in the default view mode (showing the days).
* Also disables the previous and next buttons in case they don't meet the range requirements.
*
* @method _showDefaultView
* @private
*/
_showDefaultView: function(){
this._yearSelector.style.display = 'none';
this._monthSelector.style.display = 'none';
this._monthPrev.childNodes[0].className = 'change_month_prev';
this._monthNext.childNodes[0].className = 'change_month_next';
if ( this._year < this._yearMin || this._year === this._yearMin && this._month + 1 <= this._monthMin ){
this._monthPrev.childNodes[0].className = 'action_inactive';
}
else if( this._year > this._yearMax || this._year === this._yearMax && this._month + 1 >= this._monthMax ){
this._monthNext.childNodes[0].className = 'action_inactive';
}
this._monthContainer.style.display = 'block';
},
/**
* Updates the date shown on the datepicker
*
* @method _updateDate
* @private
*/
_updateDate: function(){
var dataParsed;
if(!this._options.displayInSelect){
if(this._dataField.value !== ''){
if(this._isDate(this._options.format,this._dataField.value)){
dataParsed = this._getDataArrayParsed(this._dataField.value);
dataParsed = this._checkDateRange( dataParsed[ 0 ] , dataParsed[ 1 ] - 1 , dataParsed[ 2 ] );
this._year = dataParsed[ 0 ];
this._month = dataParsed[ 1 ];
this._day = dataParsed[ 2 ];
}else{
this._dataField.value = '';
this._year = this._data.getFullYear( );
this._month = this._data.getMonth( );
this._day = this._data.getDate( );
}
this._data.setFullYear( this._year , this._month , this._day );
this._dataField.value = this._writeDateInFormat( );
}
} else {
dataParsed = [];
if(this._isValidDate(
dataParsed[0] = this._options.yearField[this._options.yearField.selectedIndex].value,
dataParsed[1] = this._options.monthField[this._options.monthField.selectedIndex].value,
dataParsed[2] = this._options.dayField[this._options.dayField.selectedIndex].value
)){
dataParsed = this._checkDateRange( dataParsed[ 0 ] , dataParsed[ 1 ] - 1 , dataParsed[ 2 ] );
this._year = dataParsed[ 0 ];
this._month = dataParsed[ 1 ];
this._day = dataParsed[ 2 ];
} else {
dataParsed = this._checkDateRange( dataParsed[ 0 ] , dataParsed[ 1 ] - 1 , 1 );
if(this._isValidDate( dataParsed[ 0 ], dataParsed[ 1 ] + 1 ,dataParsed[ 2 ] )){
this._year = dataParsed[ 0 ];
this._month = dataParsed[ 1 ];
this._day = this._daysInMonth(dataParsed[0],dataParsed[1]);
this.setDate();
}
}
}
this._updateDescription();
this._showMonth();
},
/**
* Updates the date description shown at the top of the datepicker
*
* @method _updateDescription
* @private
*/
_updateDescription: function(){
this._monthChanger.innerHTML = this._options.month[ this._month + 1 ];
this._deText.innerHTML = this._options.ofText;
this._yearChanger.innerHTML = this._year;
},
/**
* Renders the year selector view of the datepicker
*
* @method _showYearSelector
* @private
*/
_showYearSelector: function(){
if (arguments.length){
var year = + this._year + arguments[0]*10;
year=year-year%10;
if ( year>this._yearMax || year+9<this._yearMin ){
return;
}
this._year = + this._year + arguments[0]*10;
}
var str = "<li>";
var ano_base = this._year-(this._year%10);
for (var i=0; i<=11; i++){
if (i % 4 === 0){
str+='<ul>';
}
if (!i || i === 11){
if ( i && (ano_base+i-1)<=this._yearMax && (ano_base+i-1)>=this._yearMin ){
str+='<li><a href="#year_next" class="change_year_next">' + this._options.nextLinkText + '</a></li>';
} else if( (ano_base+i-1)<=this._yearMax && (ano_base+i-1)>=this._yearMin ){
str+='<li><a href="#year_prev" class="change_year_prev">' + this._options.prevLinkText + '</a></li>';
} else {
str +='<li> </li>';
}
} else {
if ( (ano_base+i-1)<=this._yearMax && (ano_base+i-1)>=this._yearMin ){
str+='<li><a href="#" class="sapo_calyear_' + (ano_base+i-1) + (((ano_base+i-1) === this._data.getFullYear()) ? ' sapo_cal_on' : '') + '">' + (ano_base+i-1) +'</a></li>';
} else {
str+='<li><a href="#" class="sapo_cal_off">' + (ano_base+i-1) +'</a></li>';
}
}
if ((i+1) % 4 === 0) {
str+='</ul>';
}
}
str += "</li>";
this._yearSelector.innerHTML = str;
},
/**
* This function returns the given date in an array format
*
* @method _getDataArrayParsed
* @param {String} dateStr A date on a string.
* @private
* @return {Array} The given date in an array format
*/
_getDataArrayParsed: function(dateStr){
var arrData = [];
var data = InkDate.set( this._options.format , dateStr );
if (data) {
arrData = [ data.getFullYear( ) , data.getMonth( ) + 1 , data.getDate( ) ];
}
return arrData;
},
/**
* Checks if a date is valid
*
* @method _isValidDate
* @param {Number} year
* @param {Number} month
* @param {Number} day
* @private
* @return {Boolean} True if the date is valid, false otherwise
*/
_isValidDate: function(year, month, day){
var yearRegExp = /^\d{4}$/;
var validOneOrTwo = /^\d{1,2}$/;
return (
yearRegExp.test(year) &&
validOneOrTwo.test(month) &&
validOneOrTwo.test(day) &&
month >= 1 &&
month <= 12 &&
day >= 1 &&
day <= this._daysInMonth(year,month)
);
},
/**
* Checks if a given date is an valid format.
*
* @method _isDate
* @param {String} format A date format.
* @param {String} dateStr A date on a string.
* @private
* @return {Boolean} True if the given date is valid according to the given format
*/
_isDate: function(format, dateStr){
try {
if (typeof format === 'undefined'){
return false;
}
var data = InkDate.set( format , dateStr );
if( data && this._isValidDate( data.getFullYear( ) , data.getMonth( ) + 1 , data.getDate( ) ) ){
return true;
}
} catch (ex) {}
return false;
},
/**
* This method returns the date written with the format specified on the options
*
* @method _writeDateInFormat
* @private
* @return {String} Returns the current date of the object in the specified format
*/
_writeDateInFormat:function(){
return InkDate.get( this._options.format , this._data );
},
/**
* This method allows the user to set the DatePicker's date on run-time.
*
* @method setDate
* @param {String} dateString A date string in yyyy-mm-dd format.
* @public
*/
setDate : function( dateString )
{
if ( typeof dateString === 'string' && /\d{4}-\d{1,2}-\d{1,2}/.test( dateString ) )
{
var auxDate = dateString.split( '-' );
this._year = auxDate[ 0 ];
this._month = auxDate[ 1 ] - 1;
this._day = auxDate[ 2 ];
}
this._setDate( );
},
/**
* Sets the chosen date on the target input field
*
* @method _setDate
* @param {DOMElement} objClicked Clicked object inside the DatePicker's calendar.
* @private
*/
_setDate : function( objClicked ){
if( typeof objClicked !== 'undefined' && objClicked.className && objClicked.className.indexOf('sapo_cal_') === 0 )
{
this._day = objClicked.className.substr( 9 , 2 );
}
this._data.setFullYear.apply( this._data , this._checkDateRange( this._year , this._month , this._day ) );
if(!this._options.displayInSelect){
this._dataField.value = this._writeDateInFormat();
} else {
this._options.dayField.value = this._data.getDate();
this._options.monthField.value = this._data.getMonth()+1;
this._options.yearField.value = this._data.getFullYear();
}
if(this._options.onSetDate) {
this._options.onSetDate( this , { date : this._data } );
}
},
/**
* Makes the necessary work to update the calendar
* when choosing a different month
*
* @method _updateCal
* @param {Number} inc Indicates previous or next month
* @private
*/
_updateCal: function(inc){
if( typeof this._options.onMonthSelected === 'function' ){
this._options.onMonthSelected(this, {
'year': this._year,
'month' : this._month
});
}
this._updateMonth(inc);
this._showMonth();
},
/**
* Function that returns the number of days on a given month on a given year
*
* @method _daysInMonth
* @param {Number} _y - year
* @param {Number} _m - month
* @private
* @return {Number} The number of days on a given month on a given year
*/
_daysInMonth: function(_y,_m){
var nDays = 31;
switch (_m) {
case 2:
nDays = ((_y % 400 === 0) || (_y % 4 === 0 && _y % 100 !== 0)) ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11:
nDays = 30;
break;
}
return nDays;
},
/**
* Updates the calendar when a different month is chosen
*
* @method _updateMonth
* @param {Number} incValue - indicates previous or next month
* @private
*/
_updateMonth: function(incValue){
if(typeof incValue === 'undefined') {
incValue = "0";
}
var mes = this._month + 1;
var ano = this._year;
switch(incValue){
case -1:
if (mes===1){
if(ano === this._yearMin){ return; }
mes=12;
ano--;
}
else {
mes--;
}
this._year = ano;
this._month = mes - 1;
break;
case 1:
if(mes === 12){
if(ano === this._yearMax){ return; }
mes=1;
ano++;
}
else{
mes++;
}
this._year = ano;
this._month = mes - 1;
break;
default:
}
},
/**
* Key-value object that (for a given key) points to the correct parsing format for the DatePicker
* @property _dateParsers
* @type {Object}
* @readOnly
*/
_dateParsers: {
'yyyy-mm-dd' : 'Y-m-d' ,
'yyyy/mm/dd' : 'Y/m/d' ,
'yy-mm-dd' : 'y-m-d' ,
'yy/mm/dd' : 'y/m/d' ,
'dd-mm-yyyy' : 'd-m-Y' ,
'dd/mm/yyyy' : 'd/m/Y' ,
'dd-mm-yy' : 'd-m-y' ,
'dd/mm/yy' : 'd/m/y' ,
'mm/dd/yyyy' : 'm/d/Y' ,
'mm-dd-yyyy' : 'm-d-Y'
},
/**
* Renders the current month
*
* @method _showMonth
* @private
*/
_showMonth: function(){
/*jshint maxstatements:100, maxcomplexity:20 */
var i, j;
var mes = this._month + 1;
var ano = this._year;
var maxDay = this._daysInMonth(ano,mes);
var wDayFirst = (new Date( ano , mes - 1 , 1 )).getDay();
var startWeekDay = this._options.startWeekDay || 0;
this._monthPrev.childNodes[0].className = 'change_month_prev';
this._monthNext.childNodes[0].className = 'change_month_next';
if ( ano < this._yearMin || ano === this._yearMin && mes <= this._monthMin ){
this._monthPrev.childNodes[0].className = 'action_inactive';
}
else if( ano > this._yearMax || ano === this._yearMax && mes >= this._monthMax ){
this._monthNext.childNodes[0].className = 'action_inactive';
}
if(startWeekDay && Number(startWeekDay)){
if(startWeekDay > wDayFirst) {
wDayFirst = 7 + startWeekDay - wDayFirst;
} else {
wDayFirst += startWeekDay;
}
}
var html = '';
html += '<ul class="sapo_cal_header">';
for(i=0; i<7; i++){
html+='<li>' + this._options.wDay[i + (((startWeekDay+i)>6) ? startWeekDay-7 : startWeekDay )].substring(0,1) + '</li>';
}
html+='</ul>';
var counter = 0;
html+='<ul>';
if(wDayFirst){
for(j = startWeekDay; j < wDayFirst - startWeekDay; j++) {
if (!counter){
html+='<ul>';
}
html+='<li class="sapo_cal_empty"> </li>';
counter++;
}
}
for (i = 1; i <= maxDay; i++) {
if (counter === 7){
counter=0;
html+='<ul>';
}
var idx = 'sapo_cal_' + ((String(i).length === 2) ? i : "0" + i);
idx += ( ano === this._yearMin && mes === this._monthMin && i < this._dayMin ||
ano === this._yearMax && mes === this._monthMax && i > this._dayMax ||
ano === this._yearMin && mes < this._monthMin ||
ano === this._yearMax && mes > this._monthMax ||
ano < this._yearMin || ano > this._yearMax || ( this._options.validDayFn && !this._options.validDayFn.call( this, new Date( ano , mes - 1 , i) ) ) ) ? " sapo_cal_off" :
(this._data.getFullYear( ) === ano && this._data.getMonth( ) === mes - 1 && i === this._day) ? " sapo_cal_on" : "";
html+='<li><a href="#" class="' + idx + '">' + i + '</a></li>';
counter++;
if(counter === 7){
html+='</ul>';
}
}
if (counter !== 7){
for(i = counter; i < 7; i++){
html+='<li class="sapo_cal_empty"> </li>';
}
html+='</ul>';
}
html+='</ul>';
this._monthContainer.innerHTML = html;
},
/**
* This method sets the active month
*
* @method _setActiveMonth
* @param {DOMElement} parent DOMElement where all the months are.
* @private
*/
_setActiveMonth: function(parent){
if (typeof parent === 'undefined') {
parent = this._monthSelector;
}
var length = parent.childNodes.length;
if (parent.className && parent.className.match(/sapo_calmonth_/)) {
var year = this._year;
var month = parent.className.substr( 14 , 2 );
if ( year === this._data.getFullYear( ) && month === this._data.getMonth( ) + 1 )
{
Css.addClassName( parent , 'sapo_cal_on' );
Css.removeClassName( parent , 'sapo_cal_off' );
}
else
{
Css.removeClassName( parent , 'sapo_cal_on' );
if ( year === this._yearMin && month < this._monthMin ||
year === this._yearMax && month > this._monthMax ||
year < this._yearMin ||
year > this._yearMax )
{
Css.addClassName( parent , 'sapo_cal_off' );
}
else
{
Css.removeClassName( parent , 'sapo_cal_off' );
}
}
}
else if (length !== 0){
for (var i = 0; i < length; i++) {
this._setActiveMonth(parent.childNodes[i]);
}
}
},
/**
* Prototype's method to allow the 'i18n files' to change all objects' language at once.
* @param {Object} options Object with the texts' configuration.
* @param {String} closeText Text of the close anchor
* @param {String} cleanText Text of the clean text anchor
* @param {String} prevLinkText "Previous" link's text
* @param {String} nextLinkText "Next" link's text
* @param {String} ofText The text "of", present in 'May of 2013'
* @param {Object} month An object with keys from 1 to 12 that have the full months' names
* @param {Object} wDay An object with keys from 0 to 6 that have the full weekdays' names
* @public
*/
lang: function( options ){
this._lang = options;
},
/**
* This calls the rendering of the selected month.
*
* @method showMonth
* @public
*/
showMonth: function(){
this._showMonth();
},
/**
* Returns true if the calendar sceen is in 'select day' mode
*
* @return {Boolean} True if the calendar sceen is in 'select day' mode
* @public
*/
isMonthRendered: function(){
var header = Selector.select('.sapo_cal_header',this._containerObject)[0];
return ( (Css.getStyle(header.parentNode,'display') !== 'none') && (Css.getStyle(header.parentNode.parentNode,'display') !== 'none') );
}
};
return DatePicker;
});
/**
* @module Ink.UI.Close_1
* @author inkdev AT sapo.pt
*/
Ink.createModule('Ink.UI.Close', '1', ['Ink.Dom.Event_1','Ink.Dom.Element_1'], function(InkEvent, InkElement) {
'use strict';
/**
* Subscribes clicks on the document.body. If and only if you clicked on an element
* having class "ink-close" or "ink-dismiss", will go up the DOM hierarchy looking for an element with any
* of the following classes: "ink-alert", "ink-alert-block".
* If it is found, it is removed from the DOM.
*
* One should call close once per page (full page refresh).
*
* @class Ink.UI.Close
* @constructor
* @example
* <script>
* Ink.requireModules(['Ink.UI.Close_1'],function( Close ){
* new Close();
* });
* </script>
*/
var Close = function() {
InkEvent.observe(document.body, 'click', function(ev) {
var el = InkEvent.element(ev);
el = InkElement.findUpwardsByClass(el, 'ink-close') ||
InkElement.findUpwardsByClass(el, 'ink-dismiss');
if (!el) {
return; // ink-close or ink-dismiss class not found
}
var toRemove = el;
toRemove = InkElement.findUpwardsByClass(el, 'ink-alert') ||
InkElement.findUpwardsByClass(el, 'ink-alert-block');
if (toRemove) {
InkEvent.stop(ev);
InkElement.remove(toRemove);
}
});
};
return Close;
});
/**
* @module Ink.UI.Carousel_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.Carousel', '1',
['Ink.UI.Aux_1', 'Ink.Dom.Event_1', 'Ink.Dom.Css_1', 'Ink.Dom.Element_1', 'Ink.UI.Pagination_1', 'Ink.Dom.Browser_1', 'Ink.Dom.Selector_1'],
function(Aux, InkEvent, Css, InkElement, Pagination, Browser/*, Selector*/) {
'use strict';
/*
* TODO:
* keyboardSupport
* swipe
*/
/**
* @class Ink.UI.Carousel_1
* @constructor
*
* @param {String|DOMElement} selector
* @param {Object} [options]
* @param {String} [options.axis='x'] Can be `'x'` or `'y'`, for a horizontal or vertical carousel
* @param {Boolean} [options.center=false] Center the carousel.
* @TODO @param {Boolean} [options.keyboardSupport=false] Enable keyboard support
* @param {String|DOMElement|Ink.UI.Pagination_1} [options.pagination] Either an `<ul>` element to add pagination markup to, or an `Ink.UI.Pagination` instance to use.
* @param {Function} [options.onChange] Callback for when the page is changed.
*/
var Carousel = function(selector, options) {
this._handlers = {
paginationChange: Ink.bind(this._onPaginationChange, this),
windowResize: Ink.bind(this.refit, this)
};
InkEvent.observe(window, 'resize', this._handlers.windowResize);
this._element = Aux.elOrSelector(selector, '1st argument');
this._options = Ink.extendObj({
axis: 'x',
hideLast: false,
center: false,
keyboardSupport:false,
pagination: null,
onChange: null
}, options || {}, InkElement.data(this._element));
this._isY = (this._options.axis === 'y');
var rEl = this._element;
var ulEl = Ink.s('ul.stage', rEl);
this._ulEl = ulEl;
InkElement.removeTextNodeChildren(ulEl);
if (this._options.hideLast) {
var hiderEl = document.createElement('div');
hiderEl.className = 'hider';
this._element.appendChild(hiderEl);
hiderEl.style.position = 'absolute';
hiderEl.style[ this._isY ? 'left' : 'top' ] = '0'; // fix to top..
hiderEl.style[ this._isY ? 'right' : 'bottom' ] = '0'; // and bottom...
hiderEl.style[ this._isY ? 'bottom' : 'right' ] = '0'; // and move to the end.
this._hiderEl = hiderEl;
}
this.refit();
if (this._isY) {
// Override white-space: no-wrap which is only necessary to make sure horizontal stuff stays horizontal, but breaks stuff intended to be vertical.
this._ulEl.style.whiteSpace = 'normal';
}
if (this._options.pagination) {
if (Aux.isDOMElement(this._options.pagination) || typeof this._options.pagination === 'string') {
// if dom element or css selector string...
this._pagination = new Pagination(this._options.pagination, {
size: this._numPages,
onChange: this._handlers.paginationChange
});
} else {
// assumes instantiated pagination
this._pagination = this._options.pagination;
this._pagination._options.onChange = this._handlers.paginationChange;
this._pagination.setSize(this._numPages);
this._pagination.setCurrent(0);
}
}
};
Carousel.prototype = {
/**
* Measure the carousel once again, adjusting the involved elements'
* sizes. Called automatically when the window resizes, in order to
* cater for changes from responsive media queries, for instance.
*
* @method refit
*/
refit: function() {
this._liEls = Ink.ss('li.slide', this._ulEl);
var numItems = this._liEls.length;
this._ctnLength = this._size(this._element);
this._elLength = this._size(this._liEls[0]);
this._itemsPerPage = Math.floor( this._ctnLength / this._elLength );
this._numPages = Math.ceil( numItems / this._itemsPerPage );
this._deltaLength = this._itemsPerPage * this._elLength;
if (this._isY) {
this._element.style.width = this._liEls[0].offsetWidth + 'px';
this._ulEl.style.width = this._liEls[0].offsetWidth + 'px';
} else {
this._ulEl.style.height = this._liEls[0].offsetHeight + 'px';
}
this._center();
this._updateHider();
this._IE7();
if (this._pagination) {
this._pagination.setSize(this._numPages);
this._pagination.setCurrent(0);
}
},
_size: function (elm) {
var dims = InkElement.outerDimensions(elm)
return this._isY ? dims[1] : dims[0];
},
_center: function() {
if (!this._options.center) { return; }
var gap = Math.floor( (this._ctnLength - (this._elLength * this._itemsPerPage) ) / 2 );
var pad;
if (this._isY) {
pad = [gap, 'px 0'];
}
else {
pad = ['0 ', gap, 'px'];
}
this._ulEl.style.padding = pad.join('');
},
_updateHider: function() {
if (!this._hiderEl) { return; }
var gap = Math.floor( this._ctnLength - (this._elLength * this._itemsPerPage) );
if (this._options.center) {
gap /= 2;
}
this._hiderEl.style[ this._isY ? 'height' : 'width' ] = gap + 'px';
},
/**
* Refit stuff for IE7 because it won't support inline-block.
*
* @method _IE7
* @private
*/
_IE7: function () {
if (Browser.IE && '' + Browser.version.split('.')[0] === '7') {
var numPages = this._numPages;
var slides = Ink.ss('li.slide', this._ulEl);
var stl = function (prop, val) {slides[i].style[prop] = val; };
for (var i = 0, len = slides.length; i < len; i++) {
stl('position', 'absolute');
stl(this._isY ? 'top' : 'left', (i * this._elLength) + 'px');
}
}
},
_onPaginationChange: function(pgn) {
var currPage = pgn.getCurrent();
this._ulEl.style[ this._options.axis === 'y' ? 'top' : 'left'] = ['-', currPage * this._deltaLength, 'px'].join('');
if (this._options.onChange) {
this._options.onChange.call(this, currPage);
}
}
};
return Carousel;
});
/**
* @module Ink.UI.Modal_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.Modal', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) {
'use strict';
/**
* @class Ink.UI.Modal
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {String} [options.width] Default/Initial width. Ex: '600px'
* @param {String} [options.height] Default/Initial height. Ex: '400px'
* @param {String} [options.shadeClass] Custom class to be added to the div.ink-shade
* @param {String} [options.modalClass] Custom class to be added to the div.ink-modal
* @param {String} [options.trigger] CSS Selector to target elements that will trigger the Modal.
* @param {String} [options.triggerEvent] Trigger's event to be listened. 'click' is the default value. Ex: 'mouseover', 'touchstart'...
* @param {Boolean} [options.autoDisplay=true] Display the Modal automatically when constructed.
* @param {String} [options.markup] Markup to be placed in the Modal when created
* @param {Function} [options.onShow] Callback function to run when the Modal is opened.
* @param {Function} [options.onDismiss] Callback function to run when the Modal is closed. Return `false` to cancel dismissing the Modal.
* @param {Boolean} [options.closeOnClick] Determines if the Modal should close when clicked outside of it. 'false' by default.
* @param {Boolean} [options.responsive] Determines if the Modal should behave responsively (adapt to smaller viewports).
* @param {Boolean} [options.disableScroll] Determines if the Modal should 'disable' the page's scroll (not the Modal's body).
*
* @example
* <div class="ink-shade fade">
* <div id="test" class="ink-modal fade" data-trigger="#bModal" data-width="800px" data-height="400px">
* <div class="modal-header">
* <button class="modal-close ink-dismiss"></button>
* <h5>Modal windows can have headers</h5>
* </div>
* <div class="modal-body" id="modalContent">
* <h3>Please confirm your previous choice</h3>
* <p>"No," said Peleg, "and he hasn't been baptized right either, or it would have washed some of that devil's blue off his face."</p>
* <p>
* <img src="http://placehold.it/800x400" style="width: 100%;" alt="">
* </p>
* <p>"Do tell, now," cried Bildad, "is this Philistine a regular member of Deacon Deuteronomy's meeting? I never saw him going there, and I pass it every Lord's day."</p>
* <p>"I don't know anything about Deacon Deuteronomy or his meeting," said I; "all I know is, that Queequeg here is a born member of the First Congregational Church. He is a deacon himself, Queequeg is."</p>
* </div>
* <div class="modal-footer">
* <div class="push-right">
* <button class="ink-button info">Confirm</button>
* <button class="ink-button caution ink-dismiss">Cancel</button>
* </div>
* </div>
* </div>
* </div>
* <a href="#" id="bModal">Open modal</a>
* <script>
* Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Modal_1'], function( Selector, Modal ){
* var modalElement = Ink.s('#test');
* var modalObj = new Modal( modalElement );
* });
* </script>
*/
var Modal = function(selector, options) {
if( (typeof selector !== 'string') && (typeof selector !== 'object') && (typeof options.markup === 'undefined') ){
throw 'Invalid Modal selector';
} else if(typeof selector === 'string'){
if( selector !== '' ){
this._element = Selector.select(selector);
if( this._element.length === 0 ){
/**
* From a developer's perspective this should be like it is...
* ... from a user's perspective, if it doesn't find elements, should just ignore it, no?
*/
throw 'The Modal selector has not returned any elements';
} else {
this._element = this._element[0];
}
}
} else if( !!selector ){
this._element = selector;
}
this._options = {
/**
* Width, height and markup really optional, as they can be obtained by the element
*/
width: undefined,
height: undefined,
/**
* To add extra classes
*/
shadeClass: undefined,
modalClass: undefined,
/**
* Optional trigger properties
*/
trigger: undefined,
triggerEvent: 'click',
autoDisplay: true,
/**
* Remaining options
*/
markup: undefined,
onShow: undefined,
onDismiss: undefined,
closeOnClick: false,
responsive: true,
disableScroll: true
};
this._handlers = {
click: Ink.bindEvent(this._onClick, this),
keyDown: Ink.bindEvent(this._onKeyDown, this),
resize: Ink.bindEvent(this._onResize, this)
};
this._wasDismissed = false;
/**
* Modal Markup
*/
if( this._element ){
this._markupMode = Css.hasClassName(this._element,'ink-modal'); // Check if the full modal comes from the markup
} else {
this._markupMode = false;
}
if( !this._markupMode ){
this._modalShadow = document.createElement('div');
this._modalShadowStyle = this._modalShadow.style;
this._modalDiv = document.createElement('div');
this._modalDivStyle = this._modalDiv.style;
if( !!this._element ){
this._options.markup = this._element.innerHTML;
}
/**
* Not in full markup mode, let's set the classes and css configurations
*/
Css.addClassName( this._modalShadow,'ink-shade' );
Css.addClassName( this._modalDiv,'ink-modal' );
Css.addClassName( this._modalDiv,'ink-space' );
/**
* Applying the main css styles
*/
// this._modalDivStyle.position = 'absolute';
this._modalShadow.appendChild( this._modalDiv);
document.body.appendChild( this._modalShadow );
} else {
this._modalDiv = this._element;
this._modalDivStyle = this._modalDiv.style;
this._modalShadow = this._modalDiv.parentNode;
this._modalShadowStyle = this._modalShadow.style;
this._contentContainer = Selector.select(".modal-body",this._modalDiv);
if( !this._contentContainer.length ){
throw 'Missing div with class "modal-body"';
}
this._contentContainer = this._contentContainer[0];
this._options.markup = this._contentContainer.innerHTML;
/**
* First, will handle the least important: The dataset
*/
this._options = Ink.extendObj(this._options,Element.data(this._element));
}
/**
* Now, the most important, the initialization options
*/
this._options = Ink.extendObj(this._options,options || {});
if( !this._markupMode ){
this.setContentMarkup(this._options.markup);
}
if( typeof this._options.shadeClass === 'string' ){
InkArray.each( this._options.shadeClass.split(' '), Ink.bind(function( item ){
Css.addClassName( this._modalShadow, item.trim() );
}, this));
}
if( typeof this._options.modalClass === 'string' ){
InkArray.each( this._options.modalClass.split(' '), Ink.bind(function( item ){
Css.addClassName( this._modalDiv, item.trim() );
}, this));
}
if( ("trigger" in this._options) && ( typeof this._options.trigger !== 'undefined' ) ){
var triggerElement,i;
if( typeof this._options.trigger === 'string' ){
triggerElement = Selector.select( this._options.trigger );
if( triggerElement.length > 0 ){
for( i=0; i<triggerElement.length; i++ ){
Event.observe( triggerElement[i], this._options.triggerEvent, Ink.bindEvent(this.open, this) );
}
}
}
} else if ( this._options.autoDisplay ) {
this.open();
}
};
Modal.prototype = {
/**
* Responsible for repositioning the modal
*
* @method _reposition
* @private
*/
_reposition: function(){
this._modalDivStyle.top = this._modalDivStyle.left = '50%';
this._modalDivStyle.marginTop = '-' + ( ~~( Element.elementHeight(this._modalDiv)/2) ) + 'px';
this._modalDivStyle.marginLeft = '-' + ( ~~( Element.elementWidth(this._modalDiv)/2) ) + 'px';
},
/**
* Responsible for resizing the modal
*
* @method _onResize
* @param {Boolean|Event} runNow Its executed in the begining to resize/reposition accordingly to the viewport. But usually it's an event object.
* @private
*/
_onResize: function( runNow ){
if( typeof runNow === 'boolean' ){
this._timeoutResizeFunction.call(this);
} else if( !this._resizeTimeout && (typeof runNow === 'object') ){
this._resizeTimeout = setTimeout(Ink.bind(this._timeoutResizeFunction, this),250);
}
},
/**
* Timeout Resize Function
*
* @method _timeoutResizeFunction
* @private
*/
_timeoutResizeFunction: function(){
/**
* Getting the current viewport size
*/
var
elem = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body,
currentViewportHeight = parseInt(elem.clientHeight,10),
currentViewportWidth = parseInt(elem.clientWidth,10)
;
if( ( currentViewportWidth > this.originalStatus.width ) /* && ( parseInt(this._modalDivStyle.maxWidth,10) >= Element.elementWidth(this._modalDiv) )*/ ){
/**
* The viewport width has expanded
*/
this._modalDivStyle.width = this._modalDivStyle.maxWidth;
} else {
/**
* The viewport width has not changed or reduced
*/
//this._modalDivStyle.width = (( currentViewportWidth * this.originalStatus.width ) / this.originalStatus.viewportWidth ) + 'px';
this._modalDivStyle.width = (~~( currentViewportWidth * 0.9)) + 'px';
}
if( (currentViewportHeight > this.originalStatus.height) && (parseInt(this._modalDivStyle.maxHeight,10) >= Element.elementHeight(this._modalDiv) ) ){
/**
* The viewport height has expanded
*/
//this._modalDivStyle.maxHeight =
this._modalDivStyle.height = this._modalDivStyle.maxHeight;
} else {
/**
* The viewport height has not changed, or reduced
*/
this._modalDivStyle.height = (~~( currentViewportHeight * 0.9)) + 'px';
}
this._resizeContainer();
this._reposition();
this._resizeTimeout = undefined;
},
/**
* Navigation click handler
*
* @method _onClick
* @param {Event} ev
* @private
*/
_onClick: function(ev) {
var tgtEl = Event.element(ev);
if (Css.hasClassName(tgtEl, 'ink-close') || Css.hasClassName(tgtEl, 'ink-dismiss') ||
Element.findUpwardsByClass(tgtEl, 'ink-close') || Element.findUpwardsByClass(tgtEl, 'ink-dismiss') ||
(
this._options.closeOnClick &&
(!Element.descendantOf(this._shadeElement, tgtEl) || (tgtEl === this._shadeElement))
)
) {
var
alertsInTheModal = Selector.select('.ink-alert',this._shadeElement),
alertsLength = alertsInTheModal.length
;
for( var i = 0; i < alertsLength; i++ ){
if( Element.descendantOf(alertsInTheModal[i], tgtEl) ){
return;
}
}
Event.stop(ev);
this.dismiss();
}
},
/**
* Responsible for handling the escape key pressing.
*
* @method _onKeyDown
* @param {Event} ev
* @private
*/
_onKeyDown: function(ev) {
if (ev.keyCode !== 27 || this._wasDismissed) { return; }
this.dismiss();
},
/**
* Responsible for setting the size of the modal (and position) based on the viewport.
*
* @method _resizeContainer
* @private
*/
_resizeContainer: function()
{
this._contentElement.style.overflow = this._contentElement.style.overflowX = this._contentElement.style.overflowY = 'hidden';
var containerHeight = Element.elementHeight(this._modalDiv);
this._modalHeader = Selector.select('.modal-header',this._modalDiv);
if( this._modalHeader.length>0 ){
this._modalHeader = this._modalHeader[0];
containerHeight -= Element.elementHeight(this._modalHeader);
}
this._modalFooter = Selector.select('.modal-footer',this._modalDiv);
if( this._modalFooter.length>0 ){
this._modalFooter = this._modalFooter[0];
containerHeight -= Element.elementHeight(this._modalFooter);
}
this._contentContainer.style.height = containerHeight + 'px';
if( containerHeight !== Element.elementHeight(this._contentContainer) ){
this._contentContainer.style.height = ~~(containerHeight - (Element.elementHeight(this._contentContainer) - containerHeight)) + 'px';
}
if( this._markupMode ){ return; }
this._contentContainer.style.overflow = this._contentContainer.style.overflowX = 'hidden';
this._contentContainer.style.overflowY = 'auto';
this._contentElement.style.overflow = this._contentElement.style.overflowX = this._contentElement.style.overflowY = 'visible';
},
/**
* Responsible for 'disabling' the page scroll
*
* @method _disableScroll
* @private
*/
_disableScroll: function()
{
this._oldScrollPos = Element.scroll();
this._onScrollBinded = Ink.bindEvent(function(event) {
var tgtEl = Event.element(event);
if( !Element.descendantOf(this._modalShadow, tgtEl) ){
Event.stop(event);
window.scrollTo(this._oldScrollPos[0], this._oldScrollPos[1]);
}
},this);
Event.observe(window, 'scroll', this._onScrollBinded);
Event.observe(document, 'touchmove', this._onScrollBinded);
},
/**************
* PUBLIC API *
**************/
/**
* Display this Modal. Useful if you have initialized the modal
* @method open
* @param {Event} [event] (internal) In case its fired by the internal trigger.
*/
open: function(event) {
if( event ){ Event.stop(event); }
var elem = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body;
this._resizeTimeout = null;
Css.addClassName( this._modalShadow,'ink-shade' );
this._modalShadowStyle.display = this._modalDivStyle.display = 'block';
setTimeout(Ink.bind(function(){
Css.addClassName( this._modalShadow,'visible' );
Css.addClassName( this._modalDiv,'visible' );
}, this),100);
/**
* Fallback to the old one
*/
this._contentElement = this._modalDiv;
this._shadeElement = this._modalShadow;
if( !this._markupMode ){
/**
* Setting the content of the modal
*/
this.setContentMarkup( this._options.markup );
}
/**
* If any size has been user-defined, let's set them as max-width and max-height
*/
if( typeof this._options.width !== 'undefined' ){
this._modalDivStyle.width = this._options.width;
if( this._options.width.indexOf('%') === -1 ){
this._modalDivStyle.maxWidth = Element.elementWidth(this._modalDiv) + 'px';
}
} else {
this._modalDivStyle.maxWidth = this._modalDivStyle.width = Element.elementWidth(this._modalDiv)+'px';
}
if( parseInt(elem.clientWidth,10) <= parseInt(this._modalDivStyle.width,10) ){
this._modalDivStyle.width = (~~(parseInt(elem.clientWidth,10)*0.9))+'px';
}
if( typeof this._options.height !== 'undefined' ){
this._modalDivStyle.height = this._options.height;
if( this._options.height.indexOf('%') === -1 ){
this._modalDivStyle.maxHeight = Element.elementHeight(this._modalDiv) + 'px';
}
} else {
this._modalDivStyle.maxHeight = this._modalDivStyle.height = Element.elementHeight(this._modalDiv) + 'px';
}
if( parseInt(elem.clientHeight,10) <= parseInt(this._modalDivStyle.height,10) ){
this._modalDivStyle.height = (~~(parseInt(elem.clientHeight,10)*0.9))+'px';
}
this.originalStatus = {
viewportHeight: parseInt(elem.clientHeight,10),
viewportWidth: parseInt(elem.clientWidth,10),
width: parseInt(this._modalDivStyle.maxWidth,10),
height: parseInt(this._modalDivStyle.maxHeight,10)
};
/**
* Let's 'resize' it:
*/
if(this._options.responsive) {
this._onResize(true);
Event.observe( window,'resize',this._handlers.resize );
} else {
this._resizeContainer();
this._reposition();
}
if (this._options.onShow) {
this._options.onShow(this);
}
if(this._options.disableScroll) {
this._disableScroll();
}
// subscribe events
Event.observe(this._shadeElement, 'click', this._handlers.click);
Event.observe(document, 'keydown', this._handlers.keyDown);
Aux.registerInstance(this, this._shadeElement, 'modal');
this._wasDismissed = false;
},
/**
* Dismisses the modal
*
* @method dismiss
* @public
*/
dismiss: function() {
if (this._options.onDismiss) {
var ret = this._options.onDismiss(this);
if (ret === false) { return; }
}
this._wasDismissed = true;
if(this._options.disableScroll) {
Event.stopObserving(window, 'scroll', this._onScrollBinded);
Event.stopObserving(document, 'touchmove', this._onScrollBinded);
}
if( this._options.responsive ){
Event.stopObserving(window, 'resize', this._handlers.resize);
}
// this._modalShadow.parentNode.removeChild(this._modalShadow);
if( !this._markupMode ){
this._modalShadow.parentNode.removeChild(this._modalShadow);
this.destroy();
} else {
Css.removeClassName( this._modalDiv, 'visible' );
Css.removeClassName( this._modalShadow, 'visible' );
var
dismissInterval,
transitionEndFn = Ink.bindEvent(function(){
if( !dismissInterval ){ return; }
this._modalShadowStyle.display = 'none';
Event.stopObserving(document,'transitionend',transitionEndFn);
Event.stopObserving(document,'oTransitionEnd',transitionEndFn);
Event.stopObserving(document,'webkitTransitionEnd',transitionEndFn);
clearInterval(dismissInterval);
dismissInterval = undefined;
}, this)
;
Event.observe(document,'transitionend',transitionEndFn);
Event.observe(document,'oTransitionEnd',transitionEndFn);
Event.observe(document,'webkitTransitionEnd',transitionEndFn);
if( !dismissInterval ){
dismissInterval = setInterval(Ink.bind(function(){
if( this._modalShadowStyle.opacity > 0 ){
return;
} else {
this._modalShadowStyle.display = 'none';
clearInterval(dismissInterval);
dismissInterval = undefined;
}
}, this),500);
}
}
},
/**
* Removes the modal from the DOM
*
* @method destroy
* @public
*/
destroy: function() {
Aux.unregisterInstance(this._instanceId);
},
/**
* Returns the content DOM element
*
* @method getContentElement
* @return {DOMElement} Modal main cointainer.
* @public
*/
getContentElement: function() {
return this._contentContainer;
},
/**
* Replaces the content markup
*
* @method setContentMarkup
* @param {String} contentMarkup
* @public
*/
setContentMarkup: function(contentMarkup) {
if( !this._markupMode ){
this._modalDiv.innerHTML = [contentMarkup].join('');
this._contentContainer = Selector.select(".modal-body",this._modalDiv);
if( !this._contentContainer.length ){
// throw 'Missing div with class "modal-body"';
var tempHeader = Selector.select(".modal-header",this._modalDiv);
var tempFooter = Selector.select(".modal-footer",this._modalDiv);
InkArray.each(tempHeader,Ink.bind(function( element ){ element.parentNode.removeChild(element); },this));
InkArray.each(tempFooter,Ink.bind(function( element ){ element.parentNode.removeChild(element); },this));
var body = document.createElement('div');
Css.addClassName(body,'modal-body');
body.innerHTML = this._modalDiv.innerHTML;
this._modalDiv.innerHTML = '';
InkArray.each(tempHeader,Ink.bind(function( element ){ this._modalDiv.appendChild(element); },this));
this._modalDiv.appendChild(body);
InkArray.each(tempFooter,Ink.bind(function( element ){ this._modalDiv.appendChild(element); },this));
this._contentContainer = Selector.select(".modal-body",this._modalDiv);
}
this._contentContainer = this._contentContainer[0];
} else {
this._contentContainer.innerHTML = [contentMarkup].join('');
}
this._contentElement = this._modalDiv;
this._resizeContainer();
}
};
return Modal;
});
/**
* @module Ink.UI.ProgressBar_1
* @author inkdev AT sapo.pt
* @version 1
*/
Ink.createModule('Ink.UI.ProgressBar', '1', ['Ink.Dom.Selector_1','Ink.Dom.Element_1'], function( Selector, Element ) {
'use strict';
/**
* Associated to a .ink-progress-bar element, it provides the necessary
* method - setValue() - for the user to change the element's value.
*
* @class Ink.UI.ProgressBar
* @constructor
* @version 1
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {Number} [options.startValue] Percentage of the bar that is filled. Range between 0 and 100. Default: 0
* @param {Function} [options.onStart] Callback that is called when a change of value is started
* @param {Function} [options.onEnd] Callback that is called when a change of value ends
*
* @example
* <div class="ink-progress-bar grey" data-start-value="70%">
* <span class="caption">I am a grey progress bar</span>
* <div class="bar grey"></div>
* </div>
* <script>
* Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.ProgressBar_1'], function( Selector, ProgressBar ){
* var progressBarElement = Ink.s('.ink-progress-bar');
* var progressBarObj = new ProgressBar( progressBarElement );
* });
* </script>
*/
var ProgressBar = function( selector, options ){
if( typeof selector !== 'object' ){
if( typeof selector !== 'string' ){
throw '[Ink.UI.ProgressBar] :: Invalid selector';
} else {
this._element = Selector.select(selector);
if( this._element.length < 1 ){
throw "[Ink.UI.ProgressBar] :: Selector didn't find any elements";
}
this._element = this._element[0];
}
} else {
this._element = selector;
}
this._options = Ink.extendObj({
'startValue': 0,
'onStart': function(){},
'onEnd': function(){}
},Element.data(this._element));
this._options = Ink.extendObj( this._options, options || {});
this._value = this._options.startValue;
this._init();
};
ProgressBar.prototype = {
/**
* Init function called by the constructor
*
* @method _init
* @private
*/
_init: function(){
this._elementBar = Selector.select('.bar',this._element);
if( this._elementBar.length < 1 ){
throw '[Ink.UI.ProgressBar] :: Bar element not found';
}
this._elementBar = this._elementBar[0];
this._options.onStart = Ink.bind(this._options.onStart,this);
this._options.onEnd = Ink.bind(this._options.onEnd,this);
this.setValue( this._options.startValue );
},
/**
* Sets the value of the Progressbar
*
* @method setValue
* @param {Number} newValue Numeric value, between 0 and 100, that represents the percentage of the bar.
* @public
*/
setValue: function( newValue ){
this._options.onStart( this._value);
newValue = parseInt(newValue,10);
if( isNaN(newValue) || (newValue < 0) ){
newValue = 0;
} else if( newValue>100 ){
newValue = 100;
}
this._value = newValue;
this._elementBar.style.width = this._value + '%';
this._options.onEnd( this._value );
}
};
return ProgressBar;
});
|
src/components/App.js | dominic-blain/viper-visualizer | import React from 'react';
import ReactDOM from 'react-dom';
import ActionCreators from '../actions/ActionCreators';
import { Provider, connect } from 'react-redux';
import store from '../store/store.js';
import styles from '../styles/main.less';
import { version } from '../../package.json';
// Components
import Toolbar from './Toolbar';
import Article from './Article';
import KeyHandler from './KeyHandler';
class App extends React.Component {
componentWillMount() {
store.dispatch(ActionCreators.getFontList());
store.dispatch(ActionCreators.loadProject());
}
render() {
return (
<Provider store={store}>
<div>
<Toolbar />
<Article />
<KeyHandler />
<div className="app-version">
<a target="_blank" href="https://github.com/dominic-blain/viper-visualizer">
{'v' + version}
</a>
</div>
</div>
</Provider>
);
}
};
export default App;
|
src/components/pages/AuctionBidPage.js | mm-taigarevolution/tas_web_app | import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as auctionActions from '../../actions/auctionActions';
import * as timerActions from '../../actions/timerActions';
import * as bidActions from '../../actions/bidActions';
import BidControl from '../controls/stateless/BidControl';
import {toastr} from 'react-redux-toastr';
class AuctionBidPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
bidBusy: false,
closedToastShown: false
};
this.onBidAmountChanged = this.onBidAmountChanged.bind(this);
this.onCancelRequired = this.onCancelRequired.bind(this);
this.onBidRequired = this.onBidRequired.bind(this);
}
componentDidMount() {
this.props.timerActions.startTimer();
}
componentWillReceiveProps(nextProps) {
let active = nextProps.auctionItem.active;
let errorOccurred = nextProps.errorOccurred;
let isBusy = nextProps.isBusy;
if(this.state.bidBusy)
{
if(!isBusy) {
if(errorOccurred){
toastr.error('Bid failed');
}
else{
this.context.router.history.goBack();
toastr.info('Bid completed', 'Your bid is now the highest one!');
}
this.setState({bidBusy: false});
}
}
else if(!active &&
!this.state.closedToastShown){
toastr.info('Bid closed');
this.setState({closedToastShown: true});
}
}
componentWillUnmount() {
this.props.timerActions.stopTimer();
}
onBidAmountChanged(e) {
e.preventDefault();
this.props.bidActions.putBidDraftAmount(parseInt(e.target.value));
}
onCancelRequired() {
let route = '/' + this.props.auctionItem.id;
this.context.router.history.push(route);
}
onBidRequired() {
this.setState({bidBusy: true});
this.props.bidActions.bidAuctionItem(this.props.bidDraft);
}
render() {
let loggedIn = this.props.user.loggedIn;
let auctionItem = this.props.auctionItem;
let bidDraft = this.props.bidDraft;
let isBusy = this.state.bidBusy;
return (
<div>
{!loggedIn &&
<p>User must be logged in before making the bid.</p>
}
{loggedIn &&
<BidControl auctionItem={auctionItem}
bidDraft={bidDraft}
isBusy={isBusy}
onBidAmountChanged={this.onBidAmountChanged}
onCancelRequired={this.onCancelRequired}
onBidRequired={this.onBidRequired}/>
}
</div>
);
}
}
//
// Context types for the page
//
AuctionBidPage.contextTypes = {
router: PropTypes.object
};
AuctionBidPage.propTypes = {
auctionItem: PropTypes.object.isRequired,
user: PropTypes.object.isRequired,
bidDraft: PropTypes.object.isRequired,
isBusy: PropTypes.bool,
errorOccurred: PropTypes.bool,
auctionActions: PropTypes.object.isRequired,
timerActions: PropTypes.object.isRequired,
bidActions: PropTypes.object.isRequired,
bidBusy: PropTypes.bool,
closedToastShown: PropTypes.bool
};
function mapStateToProps(state) {
return {
auctionItem: state.auctionItem,
user: state.user,
bidDraft: state.bidDraft,
isBusy: state.busy.isBusy,
errorOccurred: state.errorOccurred
};
}
function mapDispatchToProps(dispatch) {
return {
auctionActions: bindActionCreators(auctionActions, dispatch),
timerActions: bindActionCreators(timerActions, dispatch),
bidActions: bindActionCreators(bidActions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(AuctionBidPage);
|
src/svg-icons/action/change-history.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionChangeHistory = (props) => (
<SvgIcon {...props}>
<path d="M12 7.77L18.39 18H5.61L12 7.77M12 4L2 20h20L12 4z"/>
</SvgIcon>
);
ActionChangeHistory = pure(ActionChangeHistory);
ActionChangeHistory.displayName = 'ActionChangeHistory';
ActionChangeHistory.muiName = 'SvgIcon';
export default ActionChangeHistory;
|
ajax/libs/react-instantsearch/3.2.1/Dom.js | cdnjs/cdnjs | /*! ReactInstantSearch 3.2.1 | © Algolia, inc. | https://community.algolia.com/instantsearch.js/react/ */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["Dom"] = factory(require("react"), require("react-dom"));
else
root["ReactInstantSearch"] = root["ReactInstantSearch"] || {}, root["ReactInstantSearch"]["Dom"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_0__, __WEBPACK_EXTERNAL_MODULE_424__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 427);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_0__;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEqual2 = __webpack_require__(104);
var _isEqual3 = _interopRequireDefault(_isEqual2);
var _has2 = __webpack_require__(74);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.default = createConnector;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(54);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* @typedef {object} ConnectorDescription
* @property {string} displayName - the displayName used by the wrapper
* @property {function} refine - a function to filter the local state
* @property {function} getSearchParameters - function transforming the local state to a SearchParameters
* @property {function} getMetadata - metadata of the widget
* @property {function} transitionState - hook after the state has changed
* @property {function} getProvidedProps - transform the state into props passed to the wrapped component.
* Receives (props, widgetStates, searchState, metadata) and returns the local state.
* @property {function} getId - Receives props and return the id that will be used to identify the widget
* @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state.
* @property {object} propTypes - PropTypes forwarded to the wrapped component.
* @property {object} defaultProps - default values for the props
*/
/**
* Connectors are the HOC used to transform React components
* into InstantSearch widgets.
* In order to simplify the construction of such connectors
* `createConnector` takes a description and transform it into
* a connector.
* @param {ConnectorDescription} connectorDesc the description of the connector
* @return {Connector} a function that wraps a component into
* an instantsearch connected one.
*/
function createConnector(connectorDesc) {
if (!connectorDesc.displayName) {
throw new Error('`createConnector` requires you to provide a `displayName` property.');
}
var hasRefine = (0, _has3.default)(connectorDesc, 'refine');
var hasSearchForFacetValues = (0, _has3.default)(connectorDesc, 'searchForFacetValues');
var hasSearchParameters = (0, _has3.default)(connectorDesc, 'getSearchParameters');
var hasMetadata = (0, _has3.default)(connectorDesc, 'getMetadata');
var hasTransitionState = (0, _has3.default)(connectorDesc, 'transitionState');
var hasCleanUp = (0, _has3.default)(connectorDesc, 'cleanUp');
var isWidget = hasSearchParameters || hasMetadata || hasTransitionState;
return function (Composed) {
var _class, _temp, _initialiseProps;
return _temp = _class = function (_Component) {
_inherits(Connector, _Component);
function Connector(props, context) {
_classCallCheck(this, Connector);
var _this = _possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context));
_initialiseProps.call(_this);
var _context$ais = context.ais,
store = _context$ais.store,
widgetsManager = _context$ais.widgetsManager;
_this.state = {
props: _this.getProvidedProps(props)
};
_this.unsubscribe = store.subscribe(function () {
_this.setState({
props: _this.getProvidedProps(_this.props)
});
});
var getSearchParameters = hasSearchParameters ? function (searchParameters) {
return connectorDesc.getSearchParameters(searchParameters, _this.props, store.getState().widgets);
} : null;
var getMetadata = hasMetadata ? function (nextWidgetsState) {
return connectorDesc.getMetadata(_this.props, nextWidgetsState);
} : null;
var transitionState = hasTransitionState ? function (prevWidgetsState, nextWidgetsState) {
return connectorDesc.transitionState.call(_this, _this.props, prevWidgetsState, nextWidgetsState);
} : null;
if (isWidget) {
_this.unregisterWidget = widgetsManager.registerWidget({
getSearchParameters: getSearchParameters, getMetadata: getMetadata, transitionState: transitionState
});
}
return _this;
}
_createClass(Connector, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (!(0, _isEqual3.default)(this.props, nextProps)) {
this.setState({
props: this.getProvidedProps(nextProps)
});
if (isWidget) {
// Since props might have changed, we need to re-run getSearchParameters
// and getMetadata with the new props.
this.context.ais.widgetsManager.update();
if (connectorDesc.transitionState) {
this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets));
}
}
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.unsubscribe();
if (isWidget) {
this.unregisterWidget();
if (hasCleanUp) {
var newState = connectorDesc.cleanUp(this.props, this.context.ais.store.getState().widgets);
this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), {
widgets: newState
}));
this.context.ais.onInternalStateUpdate(newState);
}
}
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var propsEqual = (0, _utils.shallowEqual)(this.props, nextProps);
if (this.state.props === null || nextState.props === null) {
if (this.state.props === nextState.props) {
return !propsEqual;
}
return true;
}
return !propsEqual || !(0, _utils.shallowEqual)(this.state.props, nextState.props);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
if (this.state.props === null) {
return null;
}
var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {};
var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues,
searchForFacetValues: function searchForFacetValues(facetName, query) {
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`searchForItems`, this will break in the next major version.');
}
_this2.searchForFacetValues(facetName, query);
} } : {};
return _react2.default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps));
}
}]);
return Connector;
}(_react.Component), _class.displayName = connectorDesc.displayName + '(' + (0, _utils.getDisplayName)(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = {
// @TODO: more precise state manager propType
ais: _react.PropTypes.object.isRequired
}, _initialiseProps = function _initialiseProps() {
var _this3 = this;
this.getProvidedProps = function (props) {
var store = _this3.context.ais.store;
var _store$getState = store.getState(),
results = _store$getState.results,
searching = _store$getState.searching,
error = _store$getState.error,
widgets = _store$getState.widgets,
metadata = _store$getState.metadata,
resultsFacetValues = _store$getState.resultsFacetValues;
var searchState = { results: results, searching: searching, error: error };
return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues);
};
this.refine = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this3.context.ais.onInternalStateUpdate(connectorDesc.refine.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.searchForFacetValues = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.createURL = function () {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return _this3.context.ais.createHrefForState(connectorDesc.refine.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.cleanUp = function () {
return connectorDesc.cleanUp.apply(connectorDesc, arguments);
};
}, _temp;
};
}
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(72);
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseClone = __webpack_require__(257),
baseUnset = __webpack_require__(279),
castPath = __webpack_require__(20),
copyObject = __webpack_require__(21),
customOmitClone = __webpack_require__(303),
flatRest = __webpack_require__(156),
getAllKeysIn = __webpack_require__(93);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
module.exports = omit;
/***/ }),
/* 5 */
/***/ (function(module, exports) {
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ }),
/* 6 */
/***/ (function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
var baseKeys = __webpack_require__(88),
getTag = __webpack_require__(67),
isArguments = __webpack_require__(30),
isArray = __webpack_require__(1),
isArrayLike = __webpack_require__(13),
isBuffer = __webpack_require__(31),
isPrototype = __webpack_require__(45),
isTypedArray = __webpack_require__(36);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
setTag = '[object Set]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
module.exports = isEmpty;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(15),
getRawTag = __webpack_require__(158),
objectToString = __webpack_require__(185);
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(84),
baseKeys = __webpack_require__(88),
isArrayLike = __webpack_require__(13);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(137),
getValue = __webpack_require__(160);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ }),
/* 11 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
module.exports = arrayMap;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
var baseMatches = __webpack_require__(266),
baseMatchesProperty = __webpack_require__(267),
identity = __webpack_require__(23),
isArray = __webpack_require__(1),
property = __webpack_require__(336);
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
module.exports = baseIteratee;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(18),
isLength = __webpack_require__(47);
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = classNames;
var _classnames = __webpack_require__(415);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var prefix = 'ais';
function classNames(block) {
return function () {
for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) {
elements[_key] = arguments[_key];
}
return {
className: (0, _classnames2.default)(elements.filter(function (element) {
return element !== undefined && element !== false;
}).map(function (element) {
return prefix + '-' + block + '__' + element;
}))
};
};
}
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseIteratee = __webpack_require__(12),
baseMap = __webpack_require__(139),
isArray = __webpack_require__(1);
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, baseIteratee(iteratee, 3));
}
module.exports = map;
/***/ }),
/* 17 */
/***/ (function(module, exports) {
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObject = __webpack_require__(5);
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(23),
overRest = __webpack_require__(186),
setToString = __webpack_require__(99);
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
module.exports = baseRest;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(1),
isKey = __webpack_require__(68),
stringToPath = __webpack_require__(197),
toString = __webpack_require__(70);
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
module.exports = castPath;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(86),
baseAssignValue = __webpack_require__(40);
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
module.exports = copyObject;
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(24);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = toKey;
/***/ }),
/* 23 */
/***/ (function(module, exports) {
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
module.exports = isSymbol;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(170),
listCacheDelete = __webpack_require__(171),
listCacheGet = __webpack_require__(172),
listCacheHas = __webpack_require__(173),
listCacheSet = __webpack_require__(174);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(17);
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(167);
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
module.exports = getMapData;
/***/ }),
/* 28 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(135),
isObjectLike = __webpack_require__(6);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3),
stubFalse = __webpack_require__(207);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(53)(module)))
/***/ }),
/* 32 */
/***/ (function(module, exports) {
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
module.exports = replaceHolders;
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(81),
baseEach = __webpack_require__(59),
castFunction = __webpack_require__(144),
isArray = __webpack_require__(1);
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, castFunction(iteratee));
}
module.exports = forEach;
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _has2 = __webpack_require__(74);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = translatable;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(54);
var _propTypes = __webpack_require__(400);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function translatable(defaultTranslations) {
return function (Composed) {
function Translatable(props) {
var translations = props.translations,
otherProps = _objectWithoutProperties(props, ['translations']);
var translate = function translate(key) {
for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
var translation = translations && (0, _has3.default)(translations, key) ? translations[key] : defaultTranslations[key];
if (typeof translation === 'function') {
return translation.apply(undefined, params);
}
return translation;
};
return _react2.default.createElement(Composed, _extends({ translate: translate }, otherProps));
}
Translatable.displayName = 'Translatable(' + (0, _utils.getDisplayName)(Composed) + ')';
Translatable.propTypes = {
translations: (0, _propTypes.withKeysPropType)(Object.keys(defaultTranslations))
};
return Translatable;
};
}
/***/ }),
/* 35 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(138),
baseUnary = __webpack_require__(43),
nodeUtil = __webpack_require__(184);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(175),
mapCacheDelete = __webpack_require__(176),
mapCacheGet = __webpack_require__(177),
mapCacheHas = __webpack_require__(178),
mapCacheSet = __webpack_require__(179);
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(25),
stackClear = __webpack_require__(192),
stackDelete = __webpack_require__(193),
stackGet = __webpack_require__(194),
stackHas = __webpack_require__(195),
stackSet = __webpack_require__(196);
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(153);
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
module.exports = baseAssignValue;
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
var baseFor = __webpack_require__(133),
keys = __webpack_require__(9);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(131),
baseIsNaN = __webpack_require__(264),
strictIndexOf = __webpack_require__(318);
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
module.exports = baseIndexOf;
/***/ }),
/* 43 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
/***/ }),
/* 44 */
/***/ (function(module, exports) {
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = func;
return object.placeholder;
}
module.exports = getHolder;
/***/ }),
/* 45 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
var createFind = __webpack_require__(299),
findIndex = __webpack_require__(199);
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = createFind(findIndex);
module.exports = find;
/***/ }),
/* 47 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isArray = __webpack_require__(1),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var stringTag = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
module.exports = isString;
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(84),
baseKeysIn = __webpack_require__(265),
isArrayLike = __webpack_require__(13);
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
module.exports = keysIn;
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
var arrayReduce = __webpack_require__(85),
baseEach = __webpack_require__(59),
baseIteratee = __webpack_require__(12),
baseReduce = __webpack_require__(274),
isArray = __webpack_require__(1);
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
module.exports = reduce;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
var toFinite = __webpack_require__(217);
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
module.exports = toInteger;
/***/ }),
/* 52 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 53 */
/***/ (function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if(!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.shallowEqual = shallowEqual;
exports.isSpecialClick = isSpecialClick;
exports.capitalize = capitalize;
exports.assertFacetDefined = assertFacetDefined;
exports.getDisplayName = getDisplayName;
// From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
function isSpecialClick(event) {
var isMiddleClick = event.button === 1;
return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
}
function capitalize(key) {
return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1);
}
function assertFacetDefined(searchParameters, searchResults, facet) {
var wasRequested = searchParameters.isConjunctiveFacet(facet) || searchParameters.isDisjunctiveFacet(facet);
var wasReceived = Boolean(searchResults.getFacetByName(facet));
if (searchResults.nbHits > 0 && wasRequested && !wasReceived) {
// eslint-disable-next-line no-console
console.warn('A component requested values for facet "' + facet + '", but no facet ' + 'values were retrieved from the API. This means that you should add ' + ('the attribute "' + facet + '" to the list of attributes for faceting in ') + 'your index settings.');
}
}
function getDisplayName(Component) {
return Component.displayName || Component.name || 'UnknownComponent';
}
var resolved = Promise.resolve();
var defer = exports.defer = function defer(f) {
resolved.then(f);
};
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(38),
setCacheAdd = __webpack_require__(187),
setCacheHas = __webpack_require__(188);
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;
/***/ }),
/* 56 */
/***/ (function(module, exports) {
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
module.exports = apply;
/***/ }),
/* 57 */
/***/ (function(module, exports) {
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
module.exports = arrayPush;
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(5);
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
module.exports = baseCreate;
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(41),
createBaseEach = __webpack_require__(295);
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
module.exports = baseEach;
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(20),
toKey = __webpack_require__(22);
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
module.exports = baseGet;
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqualDeep = __webpack_require__(136),
isObjectLike = __webpack_require__(6);
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
module.exports = baseIsEqual;
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(15),
arrayMap = __webpack_require__(11),
isArray = __webpack_require__(1),
isSymbol = __webpack_require__(24);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = baseToString;
/***/ }),
/* 63 */
/***/ (function(module, exports) {
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
/***/ }),
/* 64 */
/***/ (function(module, exports) {
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = copyArray;
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(58),
isObject = __webpack_require__(5);
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
module.exports = createCtor;
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(82),
stubArray = __webpack_require__(108);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
module.exports = getSymbols;
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(123),
Map = __webpack_require__(37),
Promise = __webpack_require__(126),
Set = __webpack_require__(127),
WeakMap = __webpack_require__(80),
baseGetTag = __webpack_require__(8),
toSource = __webpack_require__(73);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
module.exports = getTag;
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(1),
isSymbol = __webpack_require__(24);
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
module.exports = isKey;
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(42),
toInteger = __webpack_require__(51);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
module.exports = indexOf;
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(62);
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
module.exports = toString;
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(55),
arraySome = __webpack_require__(129),
cacheHas = __webpack_require__(63);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
module.exports = equalArrays;
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(52)))
/***/ }),
/* 73 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
module.exports = toSource;
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
var baseHas = __webpack_require__(134),
hasPath = __webpack_require__(95);
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
module.exports = has;
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
exports.arrayToObject = function (source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function (target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if (typeof target === 'object') {
target[source] = true;
} else {
return [target, source];
}
return target;
}
if (typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = exports.arrayToObject(target, options);
}
if (Array.isArray(target) && Array.isArray(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
if (target[i] && typeof target[i] === 'object') {
target[i] = exports.merge(target[i], item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (Object.prototype.hasOwnProperty.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.encode = function (str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D || // -
c === 0x2E || // .
c === 0x5F || // _
c === 0x7E || // ~
(c >= 0x30 && c <= 0x39) || // 0-9
(c >= 0x41 && c <= 0x5A) || // a-z
(c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)];
}
return out;
};
exports.compact = function (obj, references) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
refs.push(obj);
if (Array.isArray(obj)) {
var compacted = [];
for (var i = 0; i < obj.length; ++i) {
if (obj[i] && typeof obj[i] === 'object') {
compacted.push(exports.compact(obj[i], refs));
} else if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
}
return compacted;
}
var keys = Object.keys(obj);
keys.forEach(function (key) {
obj[key] = exports.compact(obj[key], refs);
});
return obj;
};
exports.isRegExp = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var keys = __webpack_require__(9);
var intersection = __webpack_require__(329);
var forOwn = __webpack_require__(327);
var forEach = __webpack_require__(33);
var filter = __webpack_require__(101);
var map = __webpack_require__(16);
var reduce = __webpack_require__(50);
var omit = __webpack_require__(4);
var indexOf = __webpack_require__(69);
var isNaN = __webpack_require__(216);
var isArray = __webpack_require__(1);
var isEmpty = __webpack_require__(7);
var isEqual = __webpack_require__(104);
var isUndefined = __webpack_require__(204);
var isString = __webpack_require__(48);
var isFunction = __webpack_require__(18);
var find = __webpack_require__(46);
var trim = __webpack_require__(208);
var defaults = __webpack_require__(100);
var merge = __webpack_require__(106);
var valToNumber = __webpack_require__(247);
var filterState = __webpack_require__(243);
var RefinementList = __webpack_require__(242);
/**
* like _.find but using _.isEqual to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into
* @param {any} searchedValue the value we're looking for
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find(array, function(currentValue) {
return isEqual(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters(newParameters) {
var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {};
/**
* Targeted index. This parameter is mandatory.
* @member {string}
*/
this.index = params.index || '';
// Query
/**
* Query string of the instant search. The empty string is a valid query.
* @member {string}
* @see https://www.algolia.com/doc/rest#param-query
*/
this.query = params.query || '';
// Facets
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || [];
// Refinements
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsRefinements = params.facetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* excluded from the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters excluded for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsExcludes = params.facetsExcludes || {};
/**
* This attribute contains all the filters that need to be
* applied on the disjunctive facets. Each facet must be properly
* defined in the `disjunctiveFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* applied on the numeric attributes.
*
* The key is the name of the attribute, and the value is the
* filters to apply to this attribute.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `numericFilters` attribute.
* @member {Object.<string, SearchParameters.OperatorList>}
*/
this.numericRefinements = params.numericRefinements || {};
/**
* This attribute contains all the tags used to refine the query.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `tagFilters` attribute.
* @member {string[]}
*/
this.tagRefinements = params.tagRefinements || [];
/**
* This attribute contains all the filters that need to be
* applied on the hierarchical facets. Each facet must be properly
* defined in the `hierarchicalFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name. The FacetList values
* are structured as a string that contain the values for each level
* seperated by the configured separator.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {};
/**
* Contains the numeric filters in the raw format of the Algolia API. Setting
* this parameter is not compatible with the usage of numeric filters methods.
* @see https://www.algolia.com/doc/javascript#numericFilters
* @member {string}
*/
this.numericFilters = params.numericFilters;
/**
* Contains the tag filters in the raw format of the Algolia API. Setting this
* parameter is not compatible with the of the add/remove/toggle methods of the
* tag api.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.tagFilters = params.tagFilters;
/**
* Contains the optional tag filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalTagFilters = params.optionalTagFilters;
/**
* Contains the optional facet filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalFacetFilters = params.optionalFacetFilters;
// Misc. parameters
/**
* Number of hits to be returned by the search API
* @member {number}
* @see https://www.algolia.com/doc/rest#param-hitsPerPage
*/
this.hitsPerPage = params.hitsPerPage;
/**
* Number of values for each facetted attribute
* @member {number}
* @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet
*/
this.maxValuesPerFacet = params.maxValuesPerFacet;
/**
* The current page number
* @member {number}
* @see https://www.algolia.com/doc/rest#param-page
*/
this.page = params.page || 0;
/**
* How the query should be treated by the search engine.
* Possible values: prefixAll, prefixLast, prefixNone
* @see https://www.algolia.com/doc/rest#param-queryType
* @member {string}
*/
this.queryType = params.queryType;
/**
* How the typo tolerance behave in the search engine.
* Possible values: true, false, min, strict
* @see https://www.algolia.com/doc/rest#param-typoTolerance
* @member {string}
*/
this.typoTolerance = params.typoTolerance;
/**
* Number of characters to wait before doing one character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo
* @member {number}
*/
this.minWordSizefor1Typo = params.minWordSizefor1Typo;
/**
* Number of characters to wait before doing a second character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos
* @member {number}
*/
this.minWordSizefor2Typos = params.minWordSizefor2Typos;
/**
* Configure the precision of the proximity ranking criterion
* @see https://www.algolia.com/doc/rest#param-minProximity
*/
this.minProximity = params.minProximity;
/**
* Should the engine allow typos on numerics.
* @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens
* @member {boolean}
*/
this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens;
/**
* Should the plurals be ignored
* @see https://www.algolia.com/doc/rest#param-ignorePlurals
* @member {boolean}
*/
this.ignorePlurals = params.ignorePlurals;
/**
* Restrict which attribute is searched.
* @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes
* @member {string}
*/
this.restrictSearchableAttributes = params.restrictSearchableAttributes;
/**
* Enable the advanced syntax.
* @see https://www.algolia.com/doc/rest#param-advancedSyntax
* @member {boolean}
*/
this.advancedSyntax = params.advancedSyntax;
/**
* Enable the analytics
* @see https://www.algolia.com/doc/rest#param-analytics
* @member {boolean}
*/
this.analytics = params.analytics;
/**
* Tag of the query in the analytics.
* @see https://www.algolia.com/doc/rest#param-analyticsTags
* @member {string}
*/
this.analyticsTags = params.analyticsTags;
/**
* Enable the synonyms
* @see https://www.algolia.com/doc/rest#param-synonyms
* @member {boolean}
*/
this.synonyms = params.synonyms;
/**
* Should the engine replace the synonyms in the highlighted results.
* @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight
* @member {boolean}
*/
this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight;
/**
* Add some optional words to those defined in the dashboard
* @see https://www.algolia.com/doc/rest#param-optionalWords
* @member {string}
*/
this.optionalWords = params.optionalWords;
/**
* Possible values are "lastWords" "firstWords" "allOptional" "none" (default)
* @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults
* @member {string}
*/
this.removeWordsIfNoResults = params.removeWordsIfNoResults;
/**
* List of attributes to retrieve
* @see https://www.algolia.com/doc/rest#param-attributesToRetrieve
* @member {string}
*/
this.attributesToRetrieve = params.attributesToRetrieve;
/**
* List of attributes to highlight
* @see https://www.algolia.com/doc/rest#param-attributesToHighlight
* @member {string}
*/
this.attributesToHighlight = params.attributesToHighlight;
/**
* Code to be embedded on the left part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPreTag
* @member {string}
*/
this.highlightPreTag = params.highlightPreTag;
/**
* Code to be embedded on the right part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPostTag
* @member {string}
*/
this.highlightPostTag = params.highlightPostTag;
/**
* List of attributes to snippet
* @see https://www.algolia.com/doc/rest#param-attributesToSnippet
* @member {string}
*/
this.attributesToSnippet = params.attributesToSnippet;
/**
* Enable the ranking informations in the response, set to 1 to activate
* @see https://www.algolia.com/doc/rest#param-getRankingInfo
* @member {number}
*/
this.getRankingInfo = params.getRankingInfo;
/**
* Remove duplicates based on the index setting attributeForDistinct
* @see https://www.algolia.com/doc/rest#param-distinct
* @member {boolean|number}
*/
this.distinct = params.distinct;
/**
* Center of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundLatLng
* @member {string}
*/
this.aroundLatLng = params.aroundLatLng;
/**
* Center of the search, retrieve from the user IP.
* @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP
* @member {boolean}
*/
this.aroundLatLngViaIP = params.aroundLatLngViaIP;
/**
* Radius of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundRadius
* @member {number}
*/
this.aroundRadius = params.aroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundPrecision
* @member {number}
*/
this.minimumAroundRadius = params.minimumAroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-minimumAroundRadius
* @member {number}
*/
this.aroundPrecision = params.aroundPrecision;
/**
* Geo search inside a box.
* @see https://www.algolia.com/doc/rest#param-insideBoundingBox
* @member {string}
*/
this.insideBoundingBox = params.insideBoundingBox;
/**
* Geo search inside a polygon.
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.insidePolygon = params.insidePolygon;
/**
* Allows to specify an ellipsis character for the snippet when we truncate the text
* (added before and after if truncated).
* The default value is an empty string and we recommend to set it to "…"
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.snippetEllipsisText = params.snippetEllipsisText;
/**
* Allows to specify some attributes name on which exact won't be applied.
* Attributes are separated with a comma (for example "name,address" ), you can also use a
* JSON string array encoding (for example encodeURIComponent('["name","address"]') ).
* By default the list is empty.
* @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes
* @member {string|string[]}
*/
this.disableExactOnAttributes = params.disableExactOnAttributes;
/**
* Applies 'exact' on single word queries if the word contains at least 3 characters
* and is not a stop word.
* Can take two values: true or false.
* By default, its set to false.
* @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery
* @member {boolean}
*/
this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery;
// Undocumented parameters, still needed otherwise we fail
this.offset = params.offset;
this.length = params.length;
var self = this;
forOwn(params, function checkForUnknownParameter(paramValue, paramName) {
if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) {
self[paramName] = paramValue;
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = keys(new SearchParameters());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters._parseNumbers = function(partialState) {
// Do not reparse numbers in SearchParameters, they ought to be parsed already
if (partialState instanceof SearchParameters) return partialState;
var numbers = {};
var numberKeys = [
'aroundPrecision',
'aroundRadius',
'getRankingInfo',
'minWordSizefor2Typos',
'minWordSizefor1Typo',
'page',
'maxValuesPerFacet',
'distinct',
'minimumAroundRadius',
'hitsPerPage',
'minProximity'
];
forEach(numberKeys, function(k) {
var value = partialState[k];
if (isString(value)) {
var parsedValue = parseFloat(value);
numbers[k] = isNaN(parsedValue) ? value : parsedValue;
}
});
if (partialState.numericRefinements) {
var numericRefinements = {};
forEach(partialState.numericRefinements, function(operators, attribute) {
numericRefinements[attribute] = {};
forEach(operators, function(values, operator) {
var parsedValues = map(values, function(v) {
if (isArray(v)) {
return map(v, function(vPrime) {
if (isString(vPrime)) {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (isString(v)) {
return parseFloat(v);
}
return v;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge({}, partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters(newParameters);
forEach(newParameters.hierarchicalFacets, function(facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) {
instance = instance.clearRefinements(facet.name);
}
// get it again in case it has been cleared
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) {
instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters.validate = function(currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
return new Error(
'[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' +
'an error, if it is really what you want, you should first clear the tags with clearTags method.');
}
if (currentState.tagRefinements.length > 0 && params.tagFilters) {
return new Error(
'[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' +
'an error, if it is not, you should first clear the tags with clearTags method.');
}
if (currentState.numericFilters && params.numericRefinements && !isEmpty(params.numericRefinements)) {
return new Error(
"[Numeric filters] Can't switch from the advanced to the managed API. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
if (!isEmpty(currentState.numericRefinements) && params.numericFilters) {
return new Error(
"[Numeric filters] Can't switch from the managed API to the advanced. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
return null;
};
SearchParameters.prototype = {
constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @method
* @param {undefined|string|SearchParameters.clearCallback} [attribute] optionnal string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
clearRefinements: function clearRefinements(attribute) {
var clear = RefinementList.clearRefinement;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'),
facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'),
disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'),
hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet')
});
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
clearTags: function clearTags() {
if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: undefined,
tagRefinements: []
});
},
/**
* Set the index.
* @method
* @param {string} index the index name
* @return {SearchParameters}
*/
setIndex: function setIndex(index) {
if (index === this.index) return this;
return this.setQueryParameters({
index: index
});
},
/**
* Query setter
* @method
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({
query: newQuery
});
},
/**
* Page setter
* @method
* @param {number} newPage new page number
* @return {SearchParameters}
*/
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({
page: newPage
});
},
/**
* Facets setter
* The facets are the simple facets, used for conjunctive (and) facetting.
* @method
* @param {string[]} facets all the attributes of the algolia records used for conjunctive facetting
* @return {SearchParameters}
*/
setFacets: function setFacets(facets) {
return this.setQueryParameters({
facets: facets
});
},
/**
* Disjunctive facets setter
* Change the list of disjunctive (or) facets the helper chan handle.
* @method
* @param {string[]} facets all the attributes of the algolia records used for disjunctive facetting
* @return {SearchParameters}
*/
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({
disjunctiveFacets: facets
});
},
/**
* HitsPerPage setter
* Hits per page represents the number of hits retrieved for this query
* @method
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
setHitsPerPage: function setHitsPerPage(n) {
if (this.hitsPerPage === n) return this;
return this.setQueryParameters({
hitsPerPage: n
});
},
/**
* typoTolerance setter
* Set the value of typoTolerance
* @method
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({
typoTolerance: typoTolerance
});
},
/**
* Add a numeric filter for a given attribute
* When value is an array, they are combined with OR
* When value is a single value, it will combined with AND
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number | number[]} value value of the filter
* @return {SearchParameters}
* @example
* // for price = 50 or 40
* searchparameter.addNumericRefinement('price', '=', [50, 40]);
* @example
* // for size = 38 and 40
* searchparameter.addNumericRefinement('size', '=', 38);
* searchparameter.addNumericRefinement('size', '=', 40);
*/
addNumericRefinement: function(attribute, operator, v) {
var value = valToNumber(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge({}, this.numericRefinements);
mod[attribute] = merge({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice();
// Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getConjunctiveRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsRefinements[facetName] || [];
},
/**
* Get the list of disjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getDisjunctiveRefinements: function(facetName) {
if (!this.isDisjunctiveFacet(facetName)) {
throw new Error(
facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration'
);
}
return this.disjunctiveFacetsRefinements[facetName] || [];
},
/**
* Get the list of hierarchical refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getHierarchicalRefinement: function(facetName) {
// we send an array but we currently do not support multiple
// hierarchicalRefinements for a hierarchicalFacet
return this.hierarchicalFacetsRefinements[facetName] || [];
},
/**
* Get the list of exclude refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getExcludeRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsExcludes[facetName] || [];
},
/**
* Remove all the numeric filter for a given (attribute, operator)
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number} [number] the value to be removed
* @return {SearchParameters}
*/
removeNumericRefinement: function(attribute, operator, paramValue) {
if (paramValue !== undefined) {
var paramValueAsNumber = valToNumber(paramValue);
if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator && isEqual(value.val, paramValueAsNumber);
})
});
} else if (operator !== undefined) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator;
})
});
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute;
})
});
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
getNumericRefinements: function(facetName) {
return this.numericRefinements[facetName] || {};
},
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
getNumericRefinement: function(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
/**
* Clear numeric filters.
* @method
* @private
* @param {string|SearchParameters.clearCallback} [attribute] optionnal string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.<string, OperatorList>}
*/
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (isUndefined(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(this.numericRefinements, attribute);
} else if (isFunction(attribute)) {
return reduce(this.numericRefinements, function(memo, operators, key) {
var operatorList = {};
forEach(operators, function(values, operator) {
var outValues = [];
forEach(values, function(value) {
var predicateResult = attribute({val: value, op: operator}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (!isEmpty(outValues)) operatorList[operator] = outValues;
});
if (!isEmpty(operatorList)) memo[key] = operatorList;
return memo;
}, {});
}
},
/**
* Add a facet to the facets attribute of the helper configuration, if it
* isn't already present.
* @method
* @param {string} facet facet name to add
* @return {SearchParameters}
*/
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
facets: this.facets.concat([facet])
});
},
/**
* Add a disjunctive facet to the disjunctiveFacets attribute of the helper
* configuration, if it isn't already present.
* @method
* @param {string} facet disjunctive facet name to add
* @return {SearchParameters}
*/
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.concat([facet])
});
},
/**
* Add a hierarchical facet to the hierarchicalFacets attribute of the helper
* configuration.
* @method
* @param {object} hierarchicalFacet hierarchical facet to add
* @return {SearchParameters}
* @throws will throw an error if a hierarchical facet with the same name was already declared
*/
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) {
throw new Error(
'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');
}
return this.setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])
});
},
/**
* Add a refinement on a "normal" facet
* @method
* @param {string} facet attribute to apply the facetting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addFacetRefinement: function addFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Exclude a value from a "normal" facet
* @method
* @param {string} facet attribute to apply the exclusion on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addExcludeRefinement: function addExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Adds a refinement on a disjunctive facet.
* @method
* @param {string} facet attribute to apply the facetting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.addRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* addTagRefinement adds a tag to the list used to filter the results
* @param {string} tag tag to be added
* @return {SearchParameters}
*/
addTagRefinement: function addTagRefinement(tag) {
if (this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.concat(tag)
};
return this.setQueryParameters(modification);
},
/**
* Remove a facet from the facets attribute of the helper configuration, if it
* is present.
* @method
* @param {string} facet facet name to remove
* @return {SearchParameters}
*/
removeFacet: function removeFacet(facet) {
if (!this.isConjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
facets: filter(this.facets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a disjunctive facet from the disjunctiveFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet disjunctive facet name to remove
* @return {SearchParameters}
*/
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
disjunctiveFacets: filter(this.disjunctiveFacets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a hierarchical facet from the hierarchicalFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet hierarchical facet name to remove
* @return {SearchParameters}
*/
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
hierarchicalFacets: filter(this.hierarchicalFacets, function(f) {
return f.name !== facet;
})
});
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
* refinement for the given value, otherwise it will clear all the refinement
* values for the facetted attribute.
* @method
* @param {string} facet name of the attribute used for facetting
* @param {string} [value] value used to filter
* @return {SearchParameters}
*/
removeFacetRefinement: function removeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Remove a negative refinement on a facet
* @method
* @param {string} facet name of the attribute used for facetting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Remove a refinement on a disjunctive facet
* @method
* @param {string} facet name of the attribute used for facetting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.removeRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Remove a tag from the list of tag refinements
* @method
* @param {string} tag the tag to remove
* @return {SearchParameters}
*/
removeTagRefinement: function removeTagRefinement(tag) {
if (!this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; })
};
return this.setQueryParameters(modification);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
* @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement}
*/
toggleRefinement: function toggleRefinement(facet, value) {
return this.toggleFacetRefinement(facet, value);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
*/
toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
if (this.isHierarchicalFacet(facet)) {
return this.toggleHierarchicalFacetRefinement(facet, value);
} else if (this.isConjunctiveFacet(facet)) {
return this.toggleConjunctiveFacetRefinement(facet, value);
} else if (this.isDisjunctiveFacet(facet)) {
return this.toggleDisjunctiveFacetRefinement(facet, value);
}
throw new Error('Cannot refine the undeclared facet ' + facet +
'; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.toggleRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet));
var mod = {};
var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined &&
this.hierarchicalFacetsRefinements[facet].length > 0 && (
// remove current refinement:
// refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0] === value ||
// remove a parent refinement of the current refinement:
// - refinement was 'beer > IPA > Flying dog'
// - call is toggleRefine('beer > IPA')
// - refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0
);
if (upOneOrMultipleLevel) {
if (value.indexOf(separator) === -1) {
// go back to root level
mod[facet] = [];
} else {
mod[facet] = [value.slice(0, value.lastIndexOf(separator))];
}
} else {
mod[facet] = [value];
}
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Adds a refinement on a hierarchical facet.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is refined
*/
addHierarchicalFacetRefinement: function(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is already refined.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is not refined
*/
removeHierarchicalFacetRefinement: function(facet) {
if (!this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is not refined.');
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Switch the tag refinement
* @method
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) {
return this.removeTagRefinement(tag);
}
return this.addTagRefinement(tag);
},
/**
* Test if the facet name is from one of the disjunctive facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isDisjunctiveFacet: function(facet) {
return indexOf(this.disjunctiveFacets, facet) > -1;
},
/**
* Test if the facet name is from one of the hierarchical facets
* @method
* @param {string} facetName facet name to test
* @return {boolean}
*/
isHierarchicalFacet: function(facetName) {
return this.getHierarchicalFacetByName(facetName) !== undefined;
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isConjunctiveFacet: function(facet) {
return indexOf(this.facets, facet) > -1;
},
/**
* Returns true if the facet is refined, either for a specific value or in
* general.
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} value, optionnal value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isFacetRefined: function isFacetRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsRefinements, facet, value);
},
/**
* Returns true if the facet contains exclusions or if a specific value is
* excluded.
*
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} [value] optionnal value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isExcludeRefined: function isExcludeRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsExcludes, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} value optionnal, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} value optionnal, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var refinements = this.getHierarchicalRefinement(facet);
if (!value) {
return refinements.length > 0;
}
return indexOf(refinements, value) !== -1;
},
/**
* Test if the triple (attribute, operator, value) is already refined.
* If only the attribute and the operator are provided, it tests if the
* contains any refinement value.
* @method
* @param {string} attribute attribute for which the refinement is applied
* @param {string} [operator] operator of the refinement
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (isUndefined(value) && isUndefined(operator)) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined = this.numericRefinements[attribute] &&
!isUndefined(this.numericRefinements[attribute][operator]);
if (isUndefined(value) || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber(value);
var isAttributeValueDefined = !isUndefined(
findArray(this.numericRefinements[attribute][operator], parsedValue)
);
return isOperatorDefined && isAttributeValueDefined;
},
/**
* Returns true if the tag refined, false otherwise
* @method
* @param {string} tag the tag to check
* @return {boolean}
*/
isTagRefined: function isTagRefined(tag) {
return indexOf(this.tagRefinements, tag) !== -1;
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
// attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection(
keys(this.numericRefinements),
this.disjunctiveFacets
);
return keys(this.disjunctiveFacetsRefinements)
.concat(disjunctiveNumericRefinedFacets)
.concat(this.getRefinedHierarchicalFacets());
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
return intersection(
// enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
map(this.hierarchicalFacets, 'name'),
keys(this.hierarchicalFacetsRefinements)
);
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return filter(this.disjunctiveFacets, function(f) {
return indexOf(refinedFacets, f) === -1;
});
},
managedParameters: [
'index',
'facets', 'disjunctiveFacets', 'facetsRefinements',
'facetsExcludes', 'disjunctiveFacetsRefinements',
'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
forOwn(this, function(paramValue, paramName) {
if (indexOf(managedParameters, paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* Let the user retrieve any parameter value from the SearchParameters
* @param {string} paramName name of the parameter
* @return {any} the value of the parameter
*/
getQueryParameter: function getQueryParameter(paramName) {
if (!this.hasOwnProperty(paramName)) {
throw new Error(
"Parameter '" + paramName + "' is not an attribute of SearchParameters " +
'(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)');
}
return this[paramName];
},
/**
* Let the user set a specific value for a given parameter. Will return the
* same instance if the parameter is invalid or if the value is the same as the
* previous one.
* @method
* @param {string} parameter the parameter name
* @param {any} value the value to be set, must be compliant with the definition
* of the attribute on the object
* @return {SearchParameters} the updated state
*/
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
/**
* Let the user set any of the parameters with a plain object.
* @method
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters.validate(this, params);
if (error) {
throw error;
}
var parsedParams = SearchParameters._parseNumbers(params);
return this.mutateMe(function mergeWith(newInstance) {
var ks = keys(params);
forEach(ks, function(k) {
newInstance[k] = parsedParams[k];
});
return newInstance;
});
},
/**
* Returns an object with only the selected attributes.
* @param {string[]} filters filters to retrieve only a subset of the state. It
* accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage)
* or attributes of the index with the notation 'attribute:nameOfMyAttribute'
* @return {object}
*/
filter: function(filters) {
return filterState(this, filters);
},
/**
* Helper function to make it easier to build new instances from a mutating
* function
* @private
* @param {function} fn newMutableState -> previousState -> () function that will
* change the value of the newMutable to the desired state
* @return {SearchParameters} a new instance with the specified modifications applied
*/
mutateMe: function mutateMe(fn) {
var newState = new this.constructor(this);
fn(newState, this);
return newState;
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSortBy: function(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc'];
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSeparator: function(hierarchicalFacet) {
return hierarchicalFacet.separator || ' > ';
},
/**
* Helper function to get the hierarchicalFacet prefix path or null
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.rootPath or null as default
*/
_getHierarchicalRootPath: function(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
/**
* Helper function to check if we show the parent level of the hierarchicalFacet
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.showParentLevel or true as default
*/
_getHierarchicalShowParentLevel: function(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === 'boolean') {
return hierarchicalFacet.showParentLevel;
}
return true;
},
/**
* Helper function to get the hierarchicalFacet by it's name
* @param {string} hierarchicalFacetName
* @return {object} a hierarchicalFacet
*/
getHierarchicalFacetByName: function(hierarchicalFacetName) {
return find(
this.hierarchicalFacets,
{name: hierarchicalFacetName}
);
},
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
getHierarchicalFacetBreadcrumb: function(facetName) {
if (!this.isHierarchicalFacet(facetName)) {
throw new Error(
'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`');
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(
this.getHierarchicalFacetByName(facetName)
);
var path = refinement.split(separator);
return map(path, trim);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
module.exports = SearchParameters;
/***/ }),
/* 77 */
/***/ (function(module, exports) {
module.exports = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(58),
baseLodash = __webpack_require__(89);
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
module.exports = LazyWrapper;
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
/***/ }),
/* 81 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
/***/ }),
/* 82 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = arrayFilter;
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(42);
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf(array, value, 0) > -1;
}
module.exports = arrayIncludes;
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(143),
isArguments = __webpack_require__(30),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(31),
isIndex = __webpack_require__(28),
isTypedArray = __webpack_require__(36);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/ }),
/* 85 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
module.exports = arrayReduce;
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(40),
eq = __webpack_require__(17);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignValue;
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(57),
isArray = __webpack_require__(1);
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
module.exports = baseGetAllKeys;
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(45),
nativeKeys = __webpack_require__(183);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
/***/ }),
/* 89 */
/***/ (function(module, exports) {
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
module.exports = baseLodash;
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
var Uint8Array = __webpack_require__(79);
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
module.exports = cloneArrayBuffer;
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(141),
createBind = __webpack_require__(297),
createCurry = __webpack_require__(298),
createHybrid = __webpack_require__(151),
createPartial = __webpack_require__(301),
getData = __webpack_require__(157),
mergeData = __webpack_require__(313),
setData = __webpack_require__(189),
setWrapToString = __webpack_require__(190),
toInteger = __webpack_require__(51);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
module.exports = createWrap;
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(87),
getSymbols = __webpack_require__(66),
keys = __webpack_require__(9);
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
module.exports = getAllKeys;
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(87),
getSymbolsIn = __webpack_require__(159),
keysIn = __webpack_require__(49);
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
module.exports = getAllKeysIn;
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(97);
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(20),
isArguments = __webpack_require__(30),
isArray = __webpack_require__(1),
isIndex = __webpack_require__(28),
isLength = __webpack_require__(47),
toKey = __webpack_require__(22);
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
module.exports = hasPath;
/***/ }),
/* 96 */
/***/ (function(module, exports) {
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
/***/ }),
/* 97 */
/***/ (function(module, exports) {
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
/***/ }),
/* 98 */
/***/ (function(module, exports) {
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetToString = __webpack_require__(276),
shortOut = __webpack_require__(191);
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
module.exports = setToString;
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(56),
assignInWith = __webpack_require__(323),
baseRest = __webpack_require__(19),
customDefaultsAssignIn = __webpack_require__(302);
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(args) {
args.push(undefined, customDefaultsAssignIn);
return apply(assignInWith, undefined, args);
});
module.exports = defaults;
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(82),
baseFilter = __webpack_require__(259),
baseIteratee = __webpack_require__(12),
isArray = __webpack_require__(1);
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, baseIteratee(predicate, 3));
}
module.exports = filter;
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(60);
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
module.exports = get;
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(13),
isObjectLike = __webpack_require__(6);
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
module.exports = isArrayLikeObject;
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(61);
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual;
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
getPrototype = __webpack_require__(94),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
module.exports = isPlainObject;
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
var baseMerge = __webpack_require__(268),
createAssigner = __webpack_require__(150);
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
module.exports = merge;
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
var baseOrderBy = __webpack_require__(270),
isArray = __webpack_require__(1);
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
module.exports = orderBy;
/***/ }),
/* 108 */
/***/ (function(module, exports) {
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
module.exports = stubArray;
/***/ }),
/* 109 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ }),
/* 110 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
var inherits = __webpack_require__(122);
function AlgoliaSearchError(message, extraProperties) {
var forEach = __webpack_require__(112);
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
module.exports = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timedout before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
/***/ }),
/* 112 */
/***/ (function(module, exports) {
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
var basePick = __webpack_require__(271),
flatRest = __webpack_require__(156);
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, paths) {
return object == null ? {} : basePick(object, paths);
});
module.exports = pick;
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEmpty2 = __webpack_require__(7);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* connectRange connector provides the logic to create connected
* components that will give the ability for a user to refine results using
* a numeric range.
* @name connectRange
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - Name of the attribute for faceting
* @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
*/
function getId(props) {
return props.attributeName;
}
var namespace = 'range';
function getCurrentRefinement(props, searchState) {
var id = getId(props);
if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') {
var _searchState$namespac = searchState[namespace][id],
min = _searchState$namespac.min,
max = _searchState$namespac.max;
if (typeof min === 'string') {
min = parseInt(min, 10);
}
if (typeof max === 'string') {
max = parseInt(max, 10);
}
return { min: min, max: max };
}
if (typeof props.defaultRefinement !== 'undefined') {
return props.defaultRefinement;
}
return {};
}
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaRange',
propTypes: {
id: _react.PropTypes.string,
attributeName: _react.PropTypes.string.isRequired,
defaultRefinement: _react.PropTypes.shape({
min: _react.PropTypes.number.isRequired,
max: _react.PropTypes.number.isRequired
}),
min: _react.PropTypes.number,
max: _react.PropTypes.number
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName;
var min = props.min,
max = props.max;
var hasMin = typeof min !== 'undefined';
var hasMax = typeof max !== 'undefined';
if (!hasMin || !hasMax) {
if (!searchResults.results) {
return {
canRefine: false
};
}
var stats = searchResults.results.getFacetByName(attributeName) ? searchResults.results.getFacetStats(attributeName) : null;
if (!stats) {
return {
canRefine: false
};
}
if (!hasMin) {
min = stats.min;
}
if (!hasMax) {
max = stats.max;
}
}
var count = searchResults.results ? searchResults.results.getFacetValues(attributeName).map(function (v) {
return {
value: v.name,
count: v.count
};
}) : [];
var _getCurrentRefinement = getCurrentRefinement(props, searchState),
_getCurrentRefinement2 = _getCurrentRefinement.min,
valueMin = _getCurrentRefinement2 === undefined ? min : _getCurrentRefinement2,
_getCurrentRefinement3 = _getCurrentRefinement.max,
valueMax = _getCurrentRefinement3 === undefined ? max : _getCurrentRefinement3;
return {
min: min,
max: max,
currentRefinement: { min: valueMin, max: valueMax },
count: count,
canRefine: count.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
if (!isFinite(nextRefinement.min) || !isFinite(nextRefinement.max)) {
throw new Error('You can\'t provide non finite values to the range connector');
}
return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, getId(props), nextRefinement))));
},
cleanUp: function cleanUp(props, searchState) {
var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props));
if ((0, _isEmpty3.default)(cleanState[namespace])) {
return (0, _omit3.default)(cleanState, namespace);
}
return cleanState;
},
getSearchParameters: function getSearchParameters(params, props, searchState) {
var attributeName = props.attributeName;
var currentRefinement = getCurrentRefinement(props, searchState);
params = params.addDisjunctiveFacet(attributeName);
var min = currentRefinement.min,
max = currentRefinement.max;
if (typeof min !== 'undefined') {
params = params.addNumericRefinement(attributeName, '>=', min);
}
if (typeof max !== 'undefined') {
params = params.addNumericRefinement(attributeName, '<=', max);
}
return params;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState);
var item = void 0;
var hasMin = typeof currentRefinement.min !== 'undefined';
var hasMax = typeof currentRefinement.max !== 'undefined';
if (hasMin || hasMax) {
var itemLabel = '';
if (hasMin) {
itemLabel += currentRefinement.min + ' <= ';
}
itemLabel += props.attributeName;
if (hasMax) {
itemLabel += ' <= ' + currentRefinement.max;
}
item = {
label: itemLabel,
currentRefinement: currentRefinement,
attributeName: props.attributeName,
value: function value(nextState) {
return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, {}))));
}
};
}
return {
id: id,
items: item ? [item] : []
};
}
});
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = __webpack_require__(237);
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = __webpack_require__(236);
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(52), __webpack_require__(110)))
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
module.exports = {
'default': 'RFC3986',
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return value;
}
},
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(33);
var compact = __webpack_require__(325);
var indexOf = __webpack_require__(69);
var findIndex = __webpack_require__(199);
var get = __webpack_require__(102);
var sumBy = __webpack_require__(338);
var find = __webpack_require__(46);
var includes = __webpack_require__(328);
var map = __webpack_require__(16);
var orderBy = __webpack_require__(107);
var defaults = __webpack_require__(100);
var merge = __webpack_require__(106);
var isArray = __webpack_require__(1);
var isFunction = __webpack_require__(18);
var partial = __webpack_require__(333);
var partialRight = __webpack_require__(334);
var formatSort = __webpack_require__(118);
var generateHierarchicalTree = __webpack_require__(245);
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
* @property {object} data the facetting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
/**
* @typedef SearchResults.HierarchicalFacet
* @type {object}
* @property {string} name name of the current value given the hierarchical level, trimmed.
* If root node, you get the facet name
* @property {number} count number of objets matching this hierarchical value
* @property {string} path the current hierarchical value full path
* @property {boolean} isRefined `true` if the current value was refined, `false` otherwise
* @property {HierarchicalFacet[]} data sub values for the current level
*/
/**
* @typedef SearchResults.FacetValue
* @type {object}
* @property {string} value the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric fitlers.
* @property {string} operator the operator used. Only for numeric filters.
* @property {number} count the number of computed hits for this filter. Only on facets.
* @property {boolean} exhaustive if the count is exhaustive
*/
function getIndices(obj) {
var indices = {};
forEach(obj, function(val, idx) { indices[val] = idx; });
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) {
return find(
hierarchicalFacets,
function facetKeyMatchesAttribute(hierarchicalFacet) {
return includes(hierarchicalFacet.attributes, hierarchicalAttributeName);
}
);
}
/*eslint-disable */
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {array.<object>} results the results from algolia client
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
/*eslint-enable */
function SearchResults(state, results) {
var mainSubResponse = results[0];
/**
* query used to generate the results
* @member {string}
*/
this.query = mainSubResponse.query;
/**
* The query as parsed by the engine given all the rules.
* @member {string}
*/
this.parsedQuery = mainSubResponse.parsedQuery;
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: full, partial or none depending on how the query terms match
* @member {object[]}
*/
this.hits = mainSubResponse.hits;
/**
* index where the results come from
* @member {string}
*/
this.index = mainSubResponse.index;
/**
* number of hits per page requested
* @member {number}
*/
this.hitsPerPage = mainSubResponse.hitsPerPage;
/**
* total number of hits of this query on the index
* @member {number}
*/
this.nbHits = mainSubResponse.nbHits;
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
this.nbPages = mainSubResponse.nbPages;
/**
* current page
* @member {number}
*/
this.page = mainSubResponse.page;
/**
* sum of the processing time of all the queries
* @member {number}
*/
this.processingTimeMS = sumBy(results, 'processingTimeMS');
/**
* The position if the position was guessed by IP.
* @member {string}
* @example "48.8637,2.3615",
*/
this.aroundLatLng = mainSubResponse.aroundLatLng;
/**
* The radius computed by Algolia.
* @member {string}
* @example "126792922",
*/
this.automaticRadius = mainSubResponse.automaticRadius;
/**
* String identifying the server used to serve this request.
* @member {string}
* @example "c7-use-2.algolia.net",
*/
this.serverUsed = mainSubResponse.serverUsed;
/**
* Boolean that indicates if the computation of the counts did time out.
* @member {boolean}
*/
this.timeoutCounts = mainSubResponse.timeoutCounts;
/**
* Boolean that indicates if the computation of the hits did time out.
* @member {boolean}
*/
this.timeoutHits = mainSubResponse.timeoutHits;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = map(state.hierarchicalFacets, function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var self = this;
// Since we send request only for disjunctive facets that have been refined,
// we get the facets informations from the first, general, response.
forEach(mainSubResponse.facets, function(facetValueObject, facetKey) {
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(
state.hierarchicalFacets,
facetKey
);
if (hierarchicalFacet) {
// Place the hierarchicalFacet data at the correct index depending on
// the attributes order that was defined at the helper initialization
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = indexOf(state.disjunctiveFacets, facetKey) !== -1;
var isFacetConjunctive = indexOf(state.facets, facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
});
// Make sure we do not keep holes within the hierarchical facets
this.hierarchicalFacets = compact(this.hierarchicalFacets);
// aggregate the refined disjunctive facets
forEach(disjunctiveFacets, function(disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
// There should be only item in facets.
forEach(result.facets, function(facetResults, dfacet) {
var position;
if (hierarchicalFacet) {
position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
self.hierarchicalFacets[position][attributeIndex].data = merge(
{},
self.hierarchicalFacets[position][attributeIndex].data,
facetResults
);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: defaults({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
forEach(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] &&
indexOf(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
});
// if we have some root level values for hierarchical facets, merge them
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are already at a root refinement (or no refinement at all), there is no
// root level values request
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) {
return;
}
var result = results[nextDisjunctiveResult];
forEach(result.facets, function(facetResults, dfacet) {
var position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
// when we always get root levels, if the hits refinement is `beers > IPA` (count: 5),
// then the disjunctive values will be `beers` (count: 100),
// but we do not want to display
// | beers (100)
// > IPA (5)
// We want
// | beers (5)
// > IPA (5)
var defaultData = {};
if (currentRefinement.length > 0) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaults(
defaultData,
facetResults,
self.hierarchicalFacets[position][attributeIndex].data
);
});
nextDisjunctiveResult++;
});
// add the excludes
forEach(state.facetsExcludes, function(excludes, facetName) {
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
forEach(excludes, function(facetValue) {
self.facets[position] = self.facets[position] || {name: facetName};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
this.hierarchicalFacets = map(this.hierarchicalFacets, generateHierarchicalTree(state));
this.facets = compact(this.facets);
this.disjunctiveFacets = compact(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the attribute facetted
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function(name) {
var predicate = {name: name};
return find(this.facets, predicate) ||
find(this.disjunctiveFacets, predicate) ||
find(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the facetted attribute to search for
* @return {array|object} facet values. For the hierarchical facets it is an object.
*/
function extractNormalizedFacetValues(results, attribute) {
var predicate = {name: attribute};
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find(results.facets, predicate);
if (!facet) return [];
return map(facet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isFacetRefined(attribute, k),
isExcluded: results._state.isExcludeRefined(attribute, k)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return map(disjunctiveFacet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find(results.hierarchicalFacets, predicate);
}
}
/**
* Sort nodes of a hierarchical facet results
* @private
* @param {HierarchicalFacet} node node to upon which we want to apply the sort
*/
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = map(node.data, partial(recSort, sortFn));
var sortedChildren = sortFn(children);
var newNode = merge({}, node, {data: sortedChildren});
return newNode;
}
SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc'];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name ascending
* (alphabetical order). The sort formula can overridden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('results', function(content){
* //get values ordered only by name ascending using the string predicate
* content.getFacetValues('city', {sortBy: ['name:asc']);
* //get values ordered only by count ascending using a function
* content.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.');
var options = defaults({}, opts, {sortBy: SearchResults.DEFAULT_SORT});
if (isArray(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (isArray(facetValues)) {
return orderBy(facetValues, order[0], order[1]);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partialRight(orderBy, order[0], order[1]), facetValues);
} else if (isFunction(options.sortBy)) {
if (isArray(facetValues)) {
return facetValues.sort(options.sortBy);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partial(vanillaSortFn, options.sortBy), facetValues);
}
throw new Error(
'options.sortBy is optional but if defined it must be ' +
'either an array of string (predicates) or a sorting function'
);
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the facetted attribute
* @return {object} The stats of the facet
*/
SearchResults.prototype.getFacetStats = function(attribute) {
if (this._state.isConjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.facets, attribute);
} else if (this._state.isDisjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute);
}
throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`');
};
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find(facetList, {name: facetName});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhausistivity for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
forEach(state.facetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
forEach(state.facetsExcludes, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
forEach(state.disjunctiveFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
forEach(state.hierarchicalFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
forEach(state.numericRefinements, function(operators, attributeName) {
forEach(operators, function(values, operator) {
forEach(values, function(value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
forEach(state.tagRefinements, function(name) {
res.push({type: 'tag', attributeName: '_tags', name: name});
});
return res;
};
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var count = get(facet, 'data[' + name + ']');
var exhaustive = get(facet, 'exhaustive');
return {
type: type,
attributeName: attributeName,
name: name,
count: count || 0,
exhaustive: exhaustive || false
};
}
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var splitted = name.split(facetDeclaration.separator);
var configuredName = splitted[splitted.length - 1];
for (var i = 0; facet !== undefined && i < splitted.length; ++i) {
facet = find(facet.data, {name: splitted[i]});
}
var count = get(facet, 'count');
var exhaustive = get(facet, 'exhaustive');
return {
type: 'hierarchical',
attributeName: attributeName,
name: configuredName,
count: count || 0,
exhaustive: exhaustive || false
};
}
module.exports = SearchResults;
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var reduce = __webpack_require__(50);
var find = __webpack_require__(46);
var startsWith = __webpack_require__(337);
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
module.exports = function formatSort(sortBy, defaults) {
return reduce(sortBy, function preparePredicate(out, sortInstruction) {
var sortInstructions = sortInstruction.split(':');
if (defaults && sortInstructions.length === 1) {
var similarDefault = find(defaults, function(predicate) {
return startsWith(predicate, sortInstruction[0]);
});
if (similarDefault) {
sortInstructions = similarDefault.split(':');
}
}
out[0].push(sortInstructions[0]);
out[1].push(sortInstructions[1]);
return out;
}, [[], []]);
};
/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Module containing the functions to serialize and deserialize
* {SearchParameters} in the query string format
* @module algoliasearchHelper.url
*/
var shortener = __webpack_require__(244);
var SearchParameters = __webpack_require__(76);
var qs = __webpack_require__(238);
var bind = __webpack_require__(324);
var forEach = __webpack_require__(33);
var pick = __webpack_require__(113);
var map = __webpack_require__(16);
var mapKeys = __webpack_require__(330);
var mapValues = __webpack_require__(331);
var isString = __webpack_require__(48);
var isPlainObject = __webpack_require__(105);
var isArray = __webpack_require__(1);
var invert = __webpack_require__(202);
var encode = __webpack_require__(75).encode;
function recursiveEncode(input) {
if (isPlainObject(input)) {
return mapValues(input, recursiveEncode);
}
if (isArray(input)) {
return map(input, recursiveEncode);
}
if (isString(input)) {
return encode(input);
}
return input;
}
var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR'];
var stateKeys = shortener.ENCODED_PARAMETERS;
function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) {
if (prefixRegexp !== null) {
a = a.replace(prefixRegexp, '');
b = b.replace(prefixRegexp, '');
}
a = invertedMapping[a] || a;
b = invertedMapping[b] || b;
if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) {
if (a === 'q') return -1;
if (b === 'q') return 1;
var isARefinements = refinementsParameters.indexOf(a) !== -1;
var isBRefinements = refinementsParameters.indexOf(b) !== -1;
if (isARefinements && !isBRefinements) {
return 1;
} else if (isBRefinements && !isARefinements) {
return -1;
}
}
return a.localeCompare(b);
}
/**
* Read a query string and return an object containing the state
* @param {string} queryString the query string that will be decoded
* @param {object} [options] accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
*/
exports.getStateFromQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var partialStateWithPrefix = qs.parse(queryString);
var prefixRegexp = new RegExp('^' + prefixForParameters);
var partialState = mapKeys(
partialStateWithPrefix,
function(v, k) {
var hasPrefix = prefixForParameters && prefixRegexp.test(k);
var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k;
var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey);
return decodedKey || unprefixedKey;
}
);
var partialStateWithParsedNumbers = SearchParameters._parseNumbers(partialState);
return pick(partialStateWithParsedNumbers, SearchParameters.PARAMETERS);
};
/**
* Retrieve an object of all the properties that are not understandable as helper
* parameters.
* @param {string} queryString the query string to read
* @param {object} [options] the options
* - prefixForParameters : prefix used for the helper configuration keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
exports.getUnrecognizedParametersInQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix;
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var foreignConfig = {};
var config = qs.parse(queryString);
if (prefixForParameters) {
var prefixRegexp = new RegExp('^' + prefixForParameters);
forEach(config, function(v, key) {
if (!prefixRegexp.test(key)) foreignConfig[key] = v;
});
} else {
forEach(config, function(v, key) {
if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v;
});
}
return foreignConfig;
};
/**
* Generate a query string for the state passed according to the options
* @param {SearchParameters} state state to serialize
* @param {object} [options] May contain the following parameters :
* - prefix : prefix in front of the keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* - moreAttributes : more values to be added in the query string. Those values
* won't be prefixed.
* - safe : get safe urls for use in emails, chat apps or any application auto linking urls.
* All parameters and values will be encoded in a way that it's safe to share them.
* Default to false for legacy reasons ()
* @return {string} the query string
*/
exports.getQueryStringFromState = function(state, options) {
var moreAttributes = options && options.moreAttributes;
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var safe = options && options.safe || false;
var invertedMapping = invert(mapping);
var stateForUrl = safe ? state : recursiveEncode(state);
var encodedState = mapKeys(
stateForUrl,
function(v, k) {
var shortK = shortener.encode(k);
return prefixForParameters + (mapping[shortK] || shortK);
}
);
var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters);
var sort = bind(sortQueryStringValues, null, prefixRegexp, invertedMapping);
if (moreAttributes) {
var stateQs = qs.stringify(encodedState, {encode: safe, sort: sort});
var moreQs = qs.stringify(moreAttributes, {encode: safe});
if (!stateQs) return moreQs;
return stateQs + '&' + moreQs;
}
return qs.stringify(encodedState, {encode: safe, sort: sort});
};
/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = '2.18.1';
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
var foreach = __webpack_require__(112);
module.exports = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
/***/ }),
/* 122 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(161),
hashDelete = __webpack_require__(162),
hashGet = __webpack_require__(163),
hashHas = __webpack_require__(164),
hashSet = __webpack_require__(165);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(58),
baseLodash = __webpack_require__(89);
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
module.exports = LodashWrapper;
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ }),
/* 128 */
/***/ (function(module, exports) {
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
module.exports = arrayIncludesWith;
/***/ }),
/* 129 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(40),
eq = __webpack_require__(17);
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignMergeValue;
/***/ }),
/* 131 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(57),
isFlattenable = __webpack_require__(311);
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
module.exports = baseFlatten;
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
var createBaseFor = __webpack_require__(296);
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
/***/ }),
/* 134 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && hasOwnProperty.call(object, key);
}
module.exports = baseHas;
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
equalArrays = __webpack_require__(71),
equalByTag = __webpack_require__(154),
equalObjects = __webpack_require__(155),
getTag = __webpack_require__(67),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(31),
isTypedArray = __webpack_require__(36);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
module.exports = baseIsEqualDeep;
/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(18),
isMasked = __webpack_require__(168),
isObject = __webpack_require__(5),
toSource = __webpack_require__(73);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isLength = __webpack_require__(47),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(59),
isArrayLike = __webpack_require__(13);
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
module.exports = baseMap;
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(60),
baseSet = __webpack_require__(275),
castPath = __webpack_require__(20);
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet(object, path);
if (predicate(value, path)) {
baseSet(result, castPath(path, object), value);
}
}
return result;
}
module.exports = basePickBy;
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(23),
metaMap = __webpack_require__(182);
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
module.exports = baseSetData;
/***/ }),
/* 142 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
/***/ }),
/* 143 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
module.exports = baseTimes;
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(23);
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
module.exports = castFunction;
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(53)(module)))
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(90);
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
module.exports = cloneTypedArray;
/***/ }),
/* 147 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
module.exports = composeArgs;
/***/ }),
/* 148 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
module.exports = composeArgsRight;
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(19),
isIterateeCall = __webpack_require__(215);
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(147),
composeArgsRight = __webpack_require__(148),
countHolders = __webpack_require__(294),
createCtor = __webpack_require__(65),
createRecurry = __webpack_require__(152),
getHolder = __webpack_require__(44),
reorder = __webpack_require__(317),
replaceHolders = __webpack_require__(32),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_ARY_FLAG = 128,
WRAP_FLIP_FLAG = 512;
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
module.exports = createHybrid;
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
var isLaziable = __webpack_require__(312),
setData = __webpack_require__(189),
setWrapToString = __webpack_require__(190);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
module.exports = createRecurry;
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10);
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
module.exports = defineProperty;
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(15),
Uint8Array = __webpack_require__(79),
eq = __webpack_require__(17),
equalArrays = __webpack_require__(71),
mapToArray = __webpack_require__(96),
setToArray = __webpack_require__(98);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {
var getAllKeys = __webpack_require__(92);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
var flatten = __webpack_require__(200),
overRest = __webpack_require__(186),
setToString = __webpack_require__(99);
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
module.exports = flatRest;
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
var metaMap = __webpack_require__(182),
noop = __webpack_require__(332);
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
module.exports = getData;
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(15);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(57),
getPrototype = __webpack_require__(94),
getSymbols = __webpack_require__(66),
stubArray = __webpack_require__(108);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
module.exports = getSymbolsIn;
/***/ }),
/* 160 */
/***/ (function(module, exports) {
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(29);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/ }),
/* 162 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(29);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(29);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(29);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(58),
getPrototype = __webpack_require__(94),
isPrototype = __webpack_require__(45);
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
module.exports = initCloneObject;
/***/ }),
/* 167 */
/***/ (function(module, exports) {
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(149);
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
module.exports = isMasked;
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(5);
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
module.exports = isStrictComparable;
/***/ }),
/* 170 */
/***/ (function(module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(26);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(26);
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(26);
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(26);
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(124),
ListCache = __webpack_require__(25),
Map = __webpack_require__(37);
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(27);
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
module.exports = mapCacheDelete;
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(27);
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(27);
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(27);
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
/***/ }),
/* 180 */
/***/ (function(module, exports) {
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
module.exports = matchesStrictComparable;
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
var memoize = __webpack_require__(206);
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
module.exports = memoizeCapped;
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
var WeakMap = __webpack_require__(80);
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(97);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(72);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(53)(module)))
/***/ }),
/* 185 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
/***/ }),
/* 186 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(56);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
module.exports = overRest;
/***/ }),
/* 187 */
/***/ (function(module, exports) {
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
/***/ }),
/* 188 */
/***/ (function(module, exports) {
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(141),
shortOut = __webpack_require__(191);
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
module.exports = setData;
/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {
var getWrapDetails = __webpack_require__(306),
insertWrapDetails = __webpack_require__(310),
setToString = __webpack_require__(99),
updateWrapDetails = __webpack_require__(321);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}
module.exports = setWrapToString;
/***/ }),
/* 191 */
/***/ (function(module, exports) {
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
module.exports = shortOut;
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(25);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
/***/ }),
/* 193 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
/***/ }),
/* 194 */
/***/ (function(module, exports) {
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
/***/ }),
/* 195 */
/***/ (function(module, exports) {
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(25),
Map = __webpack_require__(37),
MapCache = __webpack_require__(38);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {
var memoizeCapped = __webpack_require__(181);
/** Used to match property names within property paths. */
var reLeadingDot = /^\./,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (reLeadingDot.test(string)) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
module.exports = stringToPath;
/***/ }),
/* 198 */
/***/ (function(module, exports) {
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
module.exports = constant;
/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(131),
baseIteratee = __webpack_require__(12),
toInteger = __webpack_require__(51);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, baseIteratee(predicate, 3), index);
}
module.exports = findIndex;
/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {
var baseFlatten = __webpack_require__(132);
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
module.exports = flatten;
/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {
var baseHasIn = __webpack_require__(260),
hasPath = __webpack_require__(95);
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
module.exports = hasIn;
/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {
var constant = __webpack_require__(198),
createInverter = __webpack_require__(300),
identity = __webpack_require__(23);
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
result[value] = key;
}, constant(identity));
module.exports = invert;
/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObjectLike = __webpack_require__(6);
/** `Object#toString` result references. */
var numberTag = '[object Number]';
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
module.exports = isNumber;
/***/ }),
/* 204 */
/***/ (function(module, exports) {
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
module.exports = isUndefined;
/***/ }),
/* 205 */
/***/ (function(module, exports) {
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
module.exports = last;
/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(38);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
module.exports = memoize;
/***/ }),
/* 207 */
/***/ (function(module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(62),
castSlice = __webpack_require__(282),
charsEndIndex = __webpack_require__(283),
charsStartIndex = __webpack_require__(284),
stringToArray = __webpack_require__(319),
toString = __webpack_require__(70);
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrim, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
module.exports = trim;
/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _react = __webpack_require__(0);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectCurrentRefinements connector provides the logic to build a widget that will
* give the user the ability to remove all or some of the filters that were
* set.
* @name connectCurrentRefinements
* @kind connector
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {function} [clearsQuery=false] - Pass true to also clear the search query
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values.
* @providedPropType {function} query - the search query
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaCurrentRefinements',
propTypes: {
transformItems: _react.PropTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) {
var items = metadata.reduce(function (res, meta) {
return typeof meta.items !== 'undefined' ? res.concat(meta.items) : res;
}, []);
var query = props.clearsQuery && searchResults.results ? searchResults.results.query : undefined;
return {
items: props.transformItems ? props.transformItems(items) : items,
canRefine: items.length > 0,
query: query
};
},
refine: function refine(props, searchState, items) {
// `value` corresponds to our internal clear function computed in each connector metadata.
var refinementsToClear = items instanceof Array ? items.map(function (item) {
return item.value;
}) : [items];
searchState = props.clearsQuery && searchState.query ? _extends({}, searchState, { query: '' }) : searchState;
return refinementsToClear.reduce(function (res, clear) {
return clear(res);
}, searchState);
}
});
/***/ }),
/* 210 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _highlight = __webpack_require__(235);
var _highlight2 = _interopRequireDefault(_highlight);
var _highlightTags = __webpack_require__(212);
var _highlightTags2 = _interopRequireDefault(_highlightTags);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var highlight = function highlight(_ref) {
var attributeName = _ref.attributeName,
hit = _ref.hit,
highlightProperty = _ref.highlightProperty;
return (0, _highlight2.default)({
attributeName: attributeName,
hit: hit,
preTag: _highlightTags2.default.highlightPreTag,
postTag: _highlightTags2.default.highlightPostTag,
highlightProperty: highlightProperty
});
};
/**
* connectHighlight connector provides the logic to create an highlighter
* component that will retrieve, parse and render an highlighted attribute
* from an Algolia hit.
* @name connectHighlight
* @kind connector
* @category connector
* @providedPropType {function} highlight - the function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attribute: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute to look for and `hit` which is the hit from Algolia. It returns an array of object `{value: string, isHighlighted: boolean}`.
* @example
* const CustomHighlight = connectHighlight(({highlight, attributeName, hit, highlightProperty) => {
* const parsedHit = highlight({attributeName, hit, highlightProperty});
* return parsedHit.map(part => {
* if(part.isHighlighted) return <em>{part.value}</em>;
* return part.value:
* });
* });
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHighlighter',
propTypes: {},
getProvidedProps: function getProvidedProps() {
return { highlight: highlight };
}
});
/***/ }),
/* 211 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _SearchBox = __webpack_require__(344);
var _SearchBox2 = _interopRequireDefault(_SearchBox);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var itemsPropType = _react.PropTypes.arrayOf(_react.PropTypes.shape({
value: _react.PropTypes.any,
label: _react.PropTypes.string.isRequired,
items: function items() {
return itemsPropType.apply(undefined, arguments);
}
}));
var List = function (_Component) {
_inherits(List, _Component);
function List() {
_classCallCheck(this, List);
var _this = _possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this));
_this.defaultProps = {
isFromSearch: false
};
_this.onShowMoreClick = function () {
_this.setState(function (state) {
return {
extended: !state.extended
};
});
};
_this.getLimit = function () {
var _this$props = _this.props,
limitMin = _this$props.limitMin,
limitMax = _this$props.limitMax;
var extended = _this.state.extended;
return extended ? limitMax : limitMin;
};
_this.renderItem = function (item) {
var items = item.items && _react2.default.createElement(
'div',
_this.props.cx('itemItems'),
item.items.slice(0, _this.getLimit()).map(function (child) {
return _this.renderItem(child, item);
})
);
return _react2.default.createElement(
'div',
_extends({
key: item.key || item.label
}, _this.props.cx('item', item.isRefined && 'itemSelected', item.noRefinement && 'itemNoRefinement', items && 'itemParent', items && item.isRefined && 'itemSelectedParent')),
_this.props.renderItem(item),
items
);
};
_this.state = {
extended: false,
query: ''
};
return _this;
}
_createClass(List, [{
key: 'renderShowMore',
value: function renderShowMore() {
var _props = this.props,
showMore = _props.showMore,
translate = _props.translate,
cx = _props.cx;
var extended = this.state.extended;
var disabled = this.props.limitMin >= this.props.items.length;
if (!showMore) {
return null;
}
return _react2.default.createElement(
'button',
_extends({ disabled: disabled
}, cx('showMore', disabled && 'showMoreDisabled'), {
onClick: this.onShowMoreClick
}),
translate('showMore', extended)
);
}
}, {
key: 'renderSearchBox',
value: function renderSearchBox() {
var _this2 = this;
var _props2 = this.props,
cx = _props2.cx,
searchForItems = _props2.searchForItems,
isFromSearch = _props2.isFromSearch,
translate = _props2.translate,
items = _props2.items,
selectItem = _props2.selectItem;
var noResults = items.length === 0 && this.state.query !== '' ? _react2.default.createElement(
'div',
cx('noResults'),
translate('noResults')
) : null;
return _react2.default.createElement(
'div',
cx('SearchBox'),
_react2.default.createElement(_SearchBox2.default, {
currentRefinement: isFromSearch ? this.state.query : '',
refine: function refine(value) {
_this2.setState({ query: value });
searchForItems(value);
},
focusShortcuts: [],
translate: translate,
onSubmit: function onSubmit(e) {
e.preventDefault();
e.stopPropagation();
if (isFromSearch) {
selectItem(items[0]);
}
}
}),
noResults
);
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _props3 = this.props,
cx = _props3.cx,
items = _props3.items,
withSearchBox = _props3.withSearchBox,
canRefine = _props3.canRefine;
var searchBox = withSearchBox ? this.renderSearchBox() : null;
if (items.length === 0) {
return _react2.default.createElement(
'div',
cx('root', !canRefine && 'noRefinement'),
searchBox
);
}
// Always limit the number of items we show on screen, since the actual
// number of retrieved items might vary with the `maxValuesPerFacet` config
// option.
var limit = this.getLimit();
return _react2.default.createElement(
'div',
cx('root', !this.props.canRefine && 'noRefinement'),
searchBox,
_react2.default.createElement(
'div',
cx('items'),
items.slice(0, limit).map(function (item) {
return _this3.renderItem(item);
})
),
this.renderShowMore()
);
}
}]);
return List;
}(_react.Component);
List.propTypes = {
cx: _react.PropTypes.func.isRequired,
// Only required with showMore.
translate: _react.PropTypes.func,
items: itemsPropType,
renderItem: _react.PropTypes.func.isRequired,
selectItem: _react.PropTypes.func,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
limit: _react.PropTypes.number,
show: _react.PropTypes.func,
searchForItems: _react.PropTypes.func,
withSearchBox: _react.PropTypes.bool,
isFromSearch: _react.PropTypes.bool,
canRefine: _react.PropTypes.bool
};
exports.default = List;
/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var timestamp = Date.now().toString();
exports.default = {
highlightPreTag: "<ais-highlight-" + timestamp + ">",
highlightPostTag: "</ais-highlight-" + timestamp + ">"
};
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var AlgoliaSearchHelper = __webpack_require__(246);
var SearchParameters = __webpack_require__(76);
var SearchResults = __webpack_require__(117);
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(result) {
* console.log(result);
* });
* helper.toggleRefine('Movies & TV Shows')
* .toggleRefine('Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
function algoliasearchHelper(client, index, opts) {
return new AlgoliaSearchHelper(client, index, opts);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper.version = __webpack_require__(120);
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper.SearchParameters = SearchParameters;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper.SearchResults = SearchResults;
/**
* URL tools to generate query string and parse them from/into
* SearchParameters
* @member module:algoliasearchHelper.url
* @type {object} {@link url}
*
*/
algoliasearchHelper.url = __webpack_require__(119);
module.exports = algoliasearchHelper;
/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = __webpack_require__(401);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
return exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (typeof process !== 'undefined' && 'env' in process) {
return process.env.DEBUG;
}
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110)))
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(17),
isArrayLike = __webpack_require__(13),
isIndex = __webpack_require__(28),
isObject = __webpack_require__(5);
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
module.exports = isIterateeCall;
/***/ }),
/* 216 */
/***/ (function(module, exports, __webpack_require__) {
var isNumber = __webpack_require__(203);
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
module.exports = isNaN;
/***/ }),
/* 217 */
/***/ (function(module, exports, __webpack_require__) {
var toNumber = __webpack_require__(339);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
module.exports = toFinite;
/***/ }),
/* 218 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys2 = __webpack_require__(9);
var _keys3 = _interopRequireDefault(_keys2);
var _difference2 = __webpack_require__(326);
var _difference3 = _interopRequireDefault(_difference2);
var _isEmpty2 = __webpack_require__(7);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var namespace = 'configure';
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaConfigure',
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
var items = (0, _omit3.default)(props, 'children');
return searchParameters.setQueryParameters(items);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var items = (0, _omit3.default)(props, 'children');
var nonPresentKeys = this._props ? (0, _difference3.default)((0, _keys3.default)(this._props), (0, _keys3.default)(props)) : [];
this._props = props;
return _extends({}, nextSearchState, _defineProperty({}, namespace, _extends({}, (0, _omit3.default)(nextSearchState[namespace], nonPresentKeys), items)));
},
cleanUp: function cleanUp(props, searchState) {
var configureKeys = searchState[namespace] ? Object.keys(searchState[namespace]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!props[item]) {
acc[item] = searchState[namespace][item];
}
return acc;
}, {});
return (0, _isEmpty3.default)(configureState) ? (0, _omit3.default)(searchState, namespace) : _extends({}, searchState, _defineProperty({}, namespace, configureState));
}
});
/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getId = undefined;
var _isEmpty2 = __webpack_require__(7);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _algoliasearchHelper = __webpack_require__(213);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var getId = exports.getId = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function getCurrentRefinement(props, searchState) {
var id = getId(props);
if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') {
var subState = searchState[namespace];
if (subState[id] === '') {
return null;
}
return subState[id];
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return null;
}
function getValue(path, props, searchState) {
var id = props.id,
attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel;
var currentRefinement = getCurrentRefinement(props, searchState);
var nextRefinement = void 0;
if (currentRefinement === null) {
nextRefinement = path;
} else {
var tmpSearchParameters = new _algoliasearchHelper.SearchParameters({
hierarchicalFacets: [{
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}]
});
nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0];
}
return nextRefinement;
}
function transformValue(value, limit, props, searchState) {
return value.slice(0, limit).map(function (v) {
return {
label: v.name,
value: getValue(v.path, props, searchState),
count: v.count,
isRefined: v.isRefined,
items: v.data && transformValue(v.data, limit, props, searchState)
};
});
}
var sortBy = ['name:asc'];
/**
* connectHierarchicalMenu connector provides the logic to build a widget that will
* give the user the ability to explore a tree-like structure.
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
* @name connectHierarchicalMenu
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax.
* @propType {number} [limitMin=10] - The maximum number of items displayed.
* @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHierarchicalMenu',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
separator: _react.PropTypes.string,
rootPath: _react.PropTypes.string,
showParentLevel: _react.PropTypes.bool,
defaultRefinement: _react.PropTypes.string,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
transformItems: _react.PropTypes.func
},
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20,
separator: ' > ',
rootPath: null,
showParentLevel: true
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var id = getId(props);
var results = searchResults.results;
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState),
canRefine: false
};
}
var limit = showMore ? limitMax : limitMin;
var value = results.getFacetValues(id, { sortBy: sortBy });
var items = value.data ? transformValue(value.data, limit, props, searchState) : [];
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: getCurrentRefinement(props, searchState),
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId(props);
return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, id, nextRefinement || ''))));
},
cleanUp: function cleanUp(props, searchState) {
var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props));
if ((0, _isEmpty3.default)(cleanState[namespace])) {
return (0, _omit3.default)(cleanState, namespace);
}
return cleanState;
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var id = getId(props);
var limit = showMore ? limitMax : limitMin;
searchParameters = searchParameters.addHierarchicalFacet({
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}).setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
var currentRefinement = getCurrentRefinement(props, searchState);
if (currentRefinement !== null) {
searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var rootAttribute = props.attributes[0];
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState);
return {
id: id,
items: !currentRefinement ? [] : [{
label: rootAttribute + ': ' + currentRefinement,
attributeName: rootAttribute,
value: function value(nextState) {
return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, ''))));
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 220 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectHits connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* parameter to the [searchParameters](guide/Search_parameters.html) prop on `<InstantSearch/>`.
* @name connectHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var hits = searchResults.results ? searchResults.results.hits : [];
return { hits: hits };
},
/* Hits needs to be considered as a widget to trigger a search if no others widgets are used.
* To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState
* See createConnector.js
* */
getSearchParameters: function getSearchParameters(searchParameters) {
return searchParameters;
}
});
/***/ }),
/* 221 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'hitsPerPage';
}
function getCurrentRefinement(props, searchState) {
var id = getId();
if (typeof searchState[id] !== 'undefined') {
if (typeof searchState[id] === 'string') {
return parseInt(searchState[id], 10);
}
return searchState[id];
}
return props.defaultRefinement;
}
/**
* connectHitsPerPage connector provides the logic to create connected
* components that will allow a user to choose to display more or less results from Algolia.
* @name connectHitsPerPage
* @kind connector
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {{value: number, label: string}[]} items - List of hits per page options.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHitsPerPage',
propTypes: {
defaultRefinement: _react.PropTypes.number.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string,
value: _react.PropTypes.number.isRequired
})).isRequired,
transformItems: _react.PropTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState);
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false });
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextHitsPerPage) {
var id = getId();
return _extends({}, searchState, _defineProperty({}, id, nextHitsPerPage));
},
cleanUp: function cleanUp(props, searchState) {
return (0, _omit3.default)(searchState, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setHitsPerPage(getCurrentRefinement(props, searchState));
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 222 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function getId() {
return 'page';
}
/**
* InfiniteHits connector provides the logic to create connected
* components that will render an continuous list of results retrieved from
* Algolia. This connector provides a function to load more results.
* @name connectInfiniteHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {boolean} hasMore - indicates if there are more pages to load
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaInfiniteHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
if (!searchResults.results) {
this._allResults = [];
return {
hits: this._allResults,
hasMore: false
};
}
var _searchResults$result = searchResults.results,
hits = _searchResults$result.hits,
page = _searchResults$result.page,
nbPages = _searchResults$result.nbPages,
hitsPerPage = _searchResults$result.hitsPerPage;
if (page === 0) {
this._allResults = hits;
} else {
var previousPage = this._allResults.length / hitsPerPage - 1;
if (page > previousPage) {
this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hits));
} else if (page < previousPage) {
this._allResults = hits;
}
// If it is the same page we do not touch the page result list
}
var lastPageIndex = nbPages - 1;
var hasMore = page < lastPageIndex;
return {
hits: this._allResults,
hasMore: hasMore
};
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var id = getId();
var currentPage = searchState[id] ? searchState[id] : 0;
return searchParameters.setQueryParameters({
page: currentPage
});
},
refine: function refine(props, searchState) {
var id = getId();
var nextPage = searchState[id] ? Number(searchState[id]) + 1 : 1;
return _extends({}, searchState, _defineProperty({}, id, nextPage));
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
if (prevSearchState[id] === nextSearchState[id]) {
return _extends({}, nextSearchState, _defineProperty({}, id, 0));
}
return nextSearchState;
}
});
/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _orderBy2 = __webpack_require__(107);
var _orderBy3 = _interopRequireDefault(_orderBy2);
var _isEmpty2 = __webpack_require__(7);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId(props) {
return props.attributeName;
}
var namespace = 'menu';
function getCurrentRefinement(props, searchState) {
var id = getId(props);
if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') {
if (searchState[namespace][id] === '') {
return null;
}
return searchState[namespace][id];
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return null;
}
function getValue(name, props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState);
return name === currentRefinement ? '' : name;
}
var sortBy = ['count:desc', 'name:asc'];
/**
* connectMenu connector provides the logic to build a widget that will
* give the user tha ability to choose a single value for a specific facet.
* @name connectMenu
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of diplayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaMenu',
propTypes: {
attributeName: _react.PropTypes.string.isRequired,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
defaultRefinement: _react.PropTypes.string,
transformItems: _react.PropTypes.func,
withSearchBox: _react.PropTypes.bool,
searchForFacetValues: _react.PropTypes.bool },
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) {
var results = searchResults.results;
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: canRefine
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue(v.value, props, searchState),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) {
return {
label: v.name,
value: getValue(v.name, props, searchState),
count: v.count,
isRefined: v.isRefined
};
});
var sortedItems = withSearchBox && !isFromSearch ? (0, _orderBy3.default)(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items;
var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement(props, searchState),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId(props);
return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, id, nextRefinement ? nextRefinement : ''))));
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props));
if ((0, _isEmpty3.default)(cleanState[namespace])) {
return (0, _omit3.default)(cleanState, namespace);
}
return cleanState;
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
searchParameters = searchParameters.addDisjunctiveFacet(attributeName);
var currentRefinement = getCurrentRefinement(props, searchState);
if (currentRefinement !== null) {
searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState);
return {
id: id,
items: currentRefinement === null ? [] : [{
label: props.attributeName + ': ' + currentRefinement,
attributeName: props.attributeName,
value: function value(nextState) {
return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, ''))));
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEmpty2 = __webpack_require__(7);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _find3 = __webpack_require__(46);
var _find4 = _interopRequireDefault(_find3);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
return (item.start ? item.start : '') + ':' + (item.end ? item.end : '');
}
function parseItem(value) {
if (value.length === 0) {
return { start: null, end: null };
}
var _value$split = value.split(':'),
_value$split2 = _slicedToArray(_value$split, 2),
startStr = _value$split2[0],
endStr = _value$split2[1];
return {
start: startStr.length > 0 ? parseInt(startStr, 10) : null,
end: endStr.length > 0 ? parseInt(endStr, 10) : null
};
}
var namespace = 'multiRange';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState) {
var id = getId(props);
if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') {
return searchState[namespace][id];
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return '';
}
function isRefinementsRangeIncludesInsideItemRange(stats, start, end) {
return stats.min > start && stats.min < end || stats.max > start && stats.max < end;
}
function isItemRangeIncludedInsideRefinementsRange(stats, start, end) {
return start > stats.min && start < stats.max || end > stats.min && end < stats.max;
}
function itemHasRefinement(attributeName, results, value) {
var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null;
var range = value.split(':');
var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]);
var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]);
return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end)));
}
/**
* connectMultiRange connector provides the logic to build a widget that will
* give the user the ability to select a range value for a numeric attribute.
* Ranges are defined statically.
* @name connectMultiRange
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string.
* @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaMultiRange',
propTypes: {
id: _react.PropTypes.string,
attributeName: _react.PropTypes.string.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.node,
start: _react.PropTypes.number,
end: _react.PropTypes.number
})).isRequired,
transformItems: _react.PropTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName;
var currentRefinement = getCurrentRefinement(props, searchState);
var items = props.items.map(function (item) {
var value = stringifyItem(item);
return {
label: item.label,
value: value,
isRefined: value === currentRefinement,
noRefinement: searchResults && searchResults.results ? itemHasRefinement(getId(props), searchResults.results, value) : false
};
});
var stats = searchResults.results && searchResults.results.getFacetByName(attributeName) ? searchResults.results.getFacetStats(attributeName) : null;
var refinedItem = (0, _find4.default)(items, function (item) {
return item.isRefined === true;
});
if (!items.some(function (item) {
return item.value === '';
})) {
items.push({
value: '',
isRefined: (0, _isEmpty3.default)(refinedItem),
noRefinement: !stats,
label: 'All'
});
}
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement,
canRefine: items.length > 0 && items.some(function (item) {
return item.noRefinement === false;
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, getId(props, searchState), nextRefinement))));
},
cleanUp: function cleanUp(props, searchState) {
var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props));
if ((0, _isEmpty3.default)(cleanState[namespace])) {
return (0, _omit3.default)(cleanState, namespace);
}
return cleanState;
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName;
var _parseItem = parseItem(getCurrentRefinement(props, searchState)),
start = _parseItem.start,
end = _parseItem.end;
searchParameters = searchParameters.addDisjunctiveFacet(attributeName);
if (start) {
searchParameters = searchParameters.addNumericRefinement(attributeName, '>=', start);
}
if (end) {
searchParameters = searchParameters.addNumericRefinement(attributeName, '<=', end);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId(props);
var value = getCurrentRefinement(props, searchState);
var items = [];
if (value !== '') {
var _find2 = (0, _find4.default)(props.items, function (item) {
return stringifyItem(item) === value;
}),
label = _find2.label;
items.push({
label: props.attributeName + ': ' + label,
attributeName: props.attributeName,
currentRefinement: label,
value: function value(nextState) {
return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, ''))));
}
});
}
return { id: id, items: items };
}
});
/***/ }),
/* 225 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'page';
}
function getCurrentRefinement(props, searchState) {
var id = getId();
var page = searchState[id];
if (typeof page === 'undefined') {
page = 1;
} else if (typeof page === 'string') {
page = parseInt(page, 10);
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return page;
}
/**
* connectPagination connector provides the logic to build a widget that will
* let the user displays hits corresponding to a certain page.
* @name connectPagination
* @kind connector
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [pagesPadding=3] - How many page links to display around the current page.
* @propType {number} [maxPages=Infinity] - Maximum number of pages to display.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {number} nbPages - the total of existing pages
* @providedPropType {number} currentRefinement - the page refinement currently applied
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaPagination',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
if (!searchResults.results) {
return null;
}
var nbPages = searchResults.results.nbPages;
return {
nbPages: nbPages,
currentRefinement: getCurrentRefinement(props, searchState),
canRefine: nbPages > 1
};
},
refine: function refine(props, searchState, nextPage) {
var id = getId();
return _extends({}, searchState, _defineProperty({}, id, nextPage));
},
cleanUp: function cleanUp(props, searchState) {
return (0, _omit3.default)(searchState, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setPage(getCurrentRefinement(props, searchState) - 1);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
if (nextSearchState[id] && nextSearchState[id].isSamePage) {
return _extends({}, nextSearchState, _defineProperty({}, id, prevSearchState[id]));
} else if (prevSearchState[id] === nextSearchState[id]) {
return (0, _omit3.default)(nextSearchState, id);
}
return nextSearchState;
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 226 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectPoweredBy connector provides the logic to build a widget that
* will display a link to algolia.
* @name connectPoweredBy
* @kind connector
* @providedPropType {string} url - the url to redirect to algolia
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaPoweredBy',
propTypes: {},
getProvidedProps: function getProvidedProps() {
var url = 'https://www.algolia.com/?' + 'utm_source=instantsearch.js&' + 'utm_medium=website&' + ('utm_content=' + location.hostname + '&') + 'utm_campaign=poweredby';
return { url: url };
}
});
/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEmpty2 = __webpack_require__(7);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var namespace = 'refinementList';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState) {
var id = getId(props);
if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') {
var subState = searchState[namespace];
if (typeof subState[id] === 'string') {
// All items were unselected
if (subState[id] === '') {
return [];
}
// Only one item was in the searchState but we know it should be an array
return [subState[id]];
}
return subState[id];
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return [];
}
function getValue(name, props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState);
var isAnewValue = currentRefinement.indexOf(name) === -1;
var nextRefinement = isAnewValue ? currentRefinement.concat([name]) : // cannot use .push(), it mutates
currentRefinement.filter(function (selectedValue) {
return selectedValue !== name;
}); // cannot use .splice(), it mutates
return nextRefinement;
}
/**
* connectRefinementList connector provides the logic to build a widget that will
* give the user tha ability to choose multiple values for a specific facet.
* @name connectRefinementList
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of displayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var sortBy = ['isRefined', 'count:desc', 'name:asc'];
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaRefinementList',
propTypes: {
id: _react.PropTypes.string,
attributeName: _react.PropTypes.string.isRequired,
operator: _react.PropTypes.oneOf(['and', 'or']),
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
defaultRefinement: _react.PropTypes.arrayOf(_react.PropTypes.string),
withSearchBox: _react.PropTypes.bool,
searchForFacetValues: _react.PropTypes.bool, // @deprecated
transformItems: _react.PropTypes.func
},
defaultProps: {
operator: 'or',
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) {
var results = searchResults.results;
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState),
canRefine: canRefine,
isFromSearch: isFromSearch,
withSearchBox: withSearchBox
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue(v.value, props, searchState),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) {
return {
label: v.name,
value: getValue(v.name, props, searchState),
count: v.count,
isRefined: v.isRefined
};
});
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement(props, searchState),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId(props);
return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : ''))));
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props));
if ((0, _isEmpty3.default)(cleanState[namespace])) {
return (0, _omit3.default)(cleanState, namespace);
}
return cleanState;
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
operator = props.operator,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet';
var addRefinementKey = addKey + 'Refinement';
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
searchParameters = searchParameters[addKey](attributeName);
return getCurrentRefinement(props, searchState).reduce(function (res, val) {
return res[addRefinementKey](attributeName, val);
}, searchParameters);
},
getMetadata: function getMetadata(props, searchState) {
var id = getId(props);
return {
id: id,
items: getCurrentRefinement(props, searchState).length > 0 ? [{
attributeName: props.attributeName,
label: props.attributeName + ': ',
currentRefinement: getCurrentRefinement(props, searchState),
value: function value(nextState) {
return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, ''))));
},
items: getCurrentRefinement(props, searchState).map(function (item) {
return {
label: '' + item,
value: function value(nextState) {
var nextSelectedItems = getCurrentRefinement(props, nextState).filter(function (other) {
return other !== item;
});
return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, nextSelectedItems.length > 0 ? nextSelectedItems : ''))));
}
};
})
}] : []
};
}
});
/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectScrollTo connector provides the logic to build a widget that will
* let the page scroll to a certain point.
* @name connectScrollTo
* @kind connector
* @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget.
* @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaScrollTo',
propTypes: {
scrollOn: _react.PropTypes.string
},
defaultProps: {
scrollOn: 'page'
},
getProvidedProps: function getProvidedProps(props, searchState) {
var value = searchState[props.scrollOn];
return { value: value };
}
});
/***/ }),
/* 229 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _react = __webpack_require__(0);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'query';
}
function getCurrentRefinement(props, searchState) {
var id = getId();
if (typeof searchState[id] !== 'undefined') {
return searchState[id];
}
if (typeof props.defaultRefinement !== 'undefined') {
return props.defaultRefinement;
}
return '';
}
/**
* connectSearchBox connector provides the logic to build a widget that will
* let the user search for a query.
* @name connectSearchBox
* @kind connector
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the query to search for.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaSearchBox',
propTypes: {
defaultRefinement: _react.PropTypes.string
},
getProvidedProps: function getProvidedProps(props, searchState) {
return {
currentRefinement: getCurrentRefinement(props, searchState)
};
},
refine: function refine(props, searchState, nextQuery) {
var id = getId();
return _extends({}, searchState, _defineProperty({}, id, nextQuery));
},
cleanUp: function cleanUp(props, searchState) {
return (0, _omit3.default)(searchState, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement(props, searchState));
}
});
/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'sortBy';
}
function getCurrentRefinement(props, searchState) {
var id = getId();
if (searchState[id]) {
return searchState[id];
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return null;
}
/**
* connectSortBy connector provides the logic to build a widget that will
* displays a list of indexes allowing a user to change the hits are sorting.
* @name connectSortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind connector
* @propType {string} defaultRefinement - The default selected index.
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaSortBy',
propTypes: {
defaultRefinement: _react.PropTypes.string,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string,
value: _react.PropTypes.string.isRequired
})).isRequired,
transformItems: _react.PropTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState);
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false });
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId();
return _extends({}, searchState, _defineProperty({}, id, nextRefinement));
},
cleanUp: function cleanUp(props, searchState) {
return (0, _omit3.default)(searchState, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var selectedIndex = getCurrentRefinement(props, searchState);
return searchParameters.setIndex(selectedIndex);
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 231 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectStats connector provides the logic to build a widget that will
* displays algolia search statistics (hits number and processing time).
* @name connectStats
* @kind connector
* @providedPropType {number} nbHits - number of hits returned by Algolia.
* @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaStats',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
if (!searchResults.results) {
return null;
}
return {
nbHits: searchResults.results.nbHits,
processingTimeMS: searchResults.results.processingTimeMS
};
}
});
/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEmpty2 = __webpack_require__(7);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(0);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId(props) {
return props.attributeName;
}
var namespace = 'toggle';
function getCurrentRefinement(props, searchState) {
var id = getId(props);
if (searchState[namespace] && searchState[namespace][id]) {
return searchState[namespace][id];
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return false;
}
/**
* connectToggle connector provides the logic to build a widget that will
* provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization.
* @name connectToggle
* @kind connector
* @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attributeName`.
* @propType {boolean} [defaultChecked=false] - Default searchState of the widget. Should the toggle be checked by default?
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaToggle',
propTypes: {
label: _react.PropTypes.string,
filter: _react.PropTypes.func,
attributeName: _react.PropTypes.string,
value: _react.PropTypes.any,
defaultRefinement: _react.PropTypes.bool
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState);
return { currentRefinement: currentRefinement };
},
refine: function refine(props, searchState, nextChecked) {
return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, getId(props, searchState), nextChecked))));
},
cleanUp: function cleanUp(props, searchState) {
var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props));
if ((0, _isEmpty3.default)(cleanState[namespace])) {
return (0, _omit3.default)(cleanState, namespace);
}
return cleanState;
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
value = props.value,
filter = props.filter;
var checked = getCurrentRefinement(props, searchState);
if (checked) {
if (attributeName) {
searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value);
}
if (filter) {
searchParameters = filter(searchParameters);
}
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId(props);
var checked = getCurrentRefinement(props, searchState);
var items = [];
if (checked) {
items.push({
label: props.label,
currentRefinement: props.label,
attributeName: props.attributeName,
value: function value(nextState) {
return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, false))));
}
});
}
return { id: id, items: items };
}
});
/***/ }),
/* 233 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHighlight = __webpack_require__(210);
var _connectHighlight2 = _interopRequireDefault(_connectHighlight);
var _Highlight = __webpack_require__(378);
var _Highlight2 = _interopRequireDefault(_Highlight);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Renders any attribute from an hit into its highlighted form when relevant.
*
* Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide.
* @name Highlight
* @kind widget
* @propType {string} attributeName - the location of the highlighted attribute in the hit
* @propType {object} hit - the hit object containing the highlighted attribute
* @example
* import React from 'react';
*
* import {InstantSearch, connectHits, Highlight} from 'InstantSearch';
*
* const CustomHits = connectHits(hits => {
* return hits.map((hit) => <p><Highlight attributeName="description" hit={hit}/></p>);
* });
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CustomHits />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHighlight2.default)(_Highlight2.default);
/***/ }),
/* 234 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(54);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Link = function (_Component) {
_inherits(Link, _Component);
function Link() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Link);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) {
if ((0, _utils.isSpecialClick)(e)) {
return;
}
_this.props.onClick();
e.preventDefault();
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Link, [{
key: 'render',
value: function render() {
return _react2.default.createElement('a', _extends({}, (0, _omit3.default)(this.props, 'onClick'), {
onClick: this.onClick
}));
}
}]);
return Link;
}(_react.Component);
Link.propTypes = {
onClick: _react.PropTypes.func.isRequired
};
exports.default = Link;
/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _get2 = __webpack_require__(102);
var _get3 = _interopRequireDefault(_get2);
exports.default = parseAlgoliaHit;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Find an highlighted attribute given an `attributeName` and an `highlightProperty`, parses it,
* and provided an array of objects with the string value and a boolean if this
* value is highlighted.
*
* In order to use this feature, highlight must be activated in the configuration of
* the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and
* highligtPostTag in Algolia configuration.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightProperty - the property that contains the highlight structure in the results
* @param {string} attributeName - the highlighted attribute to look for
* @param {object} hit - the actual hit returned by Algolia.
* @return {object[]} - An array of {value: string, isDefined: boolean}.
*/
function parseAlgoliaHit(_ref) {
var _ref$preTag = _ref.preTag,
preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag,
_ref$postTag = _ref.postTag,
postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag,
highlightProperty = _ref.highlightProperty,
attributeName = _ref.attributeName,
hit = _ref.hit;
if (!hit) throw new Error('`hit`, the matching record, must be provided');
var highlightObject = (0, _get3.default)(hit[highlightProperty], attributeName);
var highlightedValue = !highlightObject ? '' : highlightObject.value;
return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightedValue });
}
/**
* Parses an highlighted attribute into an array of objects with the string value, and
* a boolean that indicated if this part is highlighted.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature
* @return {object[]} - An array of {value: string, isDefined: boolean}.
*/
function parseHighlightedAttribute(_ref2) {
var preTag = _ref2.preTag,
postTag = _ref2.postTag,
highlightedValue = _ref2.highlightedValue;
var splitByPreTag = highlightedValue.split(preTag);
var firstValue = splitByPreTag.shift();
var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }];
if (postTag === preTag) {
var isHighlighted = true;
splitByPreTag.forEach(function (split) {
elements.push({ value: split, isHighlighted: isHighlighted });
isHighlighted = !isHighlighted;
});
} else {
splitByPreTag.forEach(function (split) {
var splitByPostTag = split.split(postTag);
elements.push({
value: splitByPostTag[0],
isHighlighted: true
});
if (splitByPostTag[1] !== '') {
elements.push({
value: splitByPostTag[1],
isHighlighted: false
});
}
});
}
return elements;
}
/***/ }),
/* 236 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 237 */
/***/ (function(module, exports) {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var stringify = __webpack_require__(240);
var parse = __webpack_require__(239);
var formats = __webpack_require__(116);
module.exports = {
formats: formats,
parse: parse,
stringify: stringify
};
/***/ }),
/* 239 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(75);
var has = Object.prototype.hasOwnProperty;
var defaults = {
allowDots: false,
allowPrototypes: false,
arrayLimit: 20,
decoder: utils.decode,
delimiter: '&',
depth: 5,
parameterLimit: 1000,
plainObjects: false,
strictNullHandling: false
};
var parseValues = function parseValues(str, options) {
var obj = {};
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos));
val = options.decoder(part.slice(pos + 1));
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function parseObject(chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
var obj;
if (root === '[]') {
obj = [];
obj = obj.concat(parseObject(chain, val, options));
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index) &&
root !== cleanRoot &&
String(index) === cleanRoot &&
index >= 0 &&
(options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = parseObject(chain, val, options);
} else {
obj[cleanRoot] = parseObject(chain, val, options);
}
}
return obj;
};
var parseKeys = function parseKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey;
// The regex chunks
var parent = /^([^\[\]]*)/;
var child = /(\[[^\[\]]*\])/g;
// Get the parent
var segment = parent.exec(key);
// Stash the parent if it exists
var keys = [];
if (segment[1]) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, segment[1])) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].replace(/\[|\]/g, ''))) {
if (!options.allowPrototypes) {
continue;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
module.exports = function (str, opts) {
var options = opts || {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
/***/ }),
/* 240 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(75);
var formats = __webpack_require__(116);
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
return prefix + '[]';
},
indices: function indices(prefix, key) {
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) {
return prefix;
}
};
var toISO = Date.prototype.toISOString;
var defaults = {
delimiter: '&',
encode: true,
encoder: utils.encode,
serializeDate: function serializeDate(date) {
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter) {
var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (obj === null) {
if (strictNullHandling) {
return encoder ? encoder(prefix) : prefix;
}
obj = '';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
if (encoder) {
return [formatter(encoder(prefix)) + '=' + formatter(encoder(obj))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (Array.isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(stringify(
obj[key],
generateArrayPrefix(prefix, key),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter
));
} else {
values = values.concat(stringify(
obj[key],
prefix + (allowDots ? '.' + key : '[' + key + ']'),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter
));
}
}
return values;
};
module.exports = function (object, opts) {
var obj = object;
var options = opts || {};
var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
var encoder = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null;
var sort = typeof options.sort === 'function' ? options.sort : null;
var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
if (typeof options.format === 'undefined') {
options.format = formats.default;
} else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
throw new TypeError('Unknown format option provided.');
}
var formatter = formats.formatters[options.format];
var objKeys;
var filter;
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (Array.isArray(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
} else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (sort) {
objKeys.sort(sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
keys = keys.concat(stringify(
obj[key],
key,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter
));
}
return keys.join(delimiter);
};
/***/ }),
/* 241 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(115);
var events = __webpack_require__(109);
/**
* A DerivedHelper is a way to create sub requests to
* Algolia from a main helper.
* @class
* @classdesc The DerivedHelper provides an event based interface for search callbacks:
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
*/
function DerivedHelper(mainHelper, fn) {
this.main = mainHelper;
this.fn = fn;
this.lastResults = null;
}
util.inherits(DerivedHelper, events.EventEmitter);
/**
* Detach this helper from the main helper
* @return {undefined}
* @throws Error if the derived helper is already detached
*/
DerivedHelper.prototype.detach = function() {
this.removeAllListeners();
this.main.detachDerivedHelper(this);
};
DerivedHelper.prototype.getModifiedState = function(parameters) {
return this.fn(parameters);
};
module.exports = DerivedHelper;
/***/ }),
/* 242 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var isUndefined = __webpack_require__(204);
var isString = __webpack_require__(48);
var isFunction = __webpack_require__(18);
var isEmpty = __webpack_require__(7);
var defaults = __webpack_require__(100);
var reduce = __webpack_require__(50);
var filter = __webpack_require__(101);
var omit = __webpack_require__(4);
var lib = {
/**
* Adds a refinement to a RefinementList
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement, if the value is not a string it will be converted
* @return {RefinementList} a new and updated prefinement list
*/
addRefinement: function addRefinement(refinementList, attribute, value) {
if (lib.isRefined(refinementList, attribute, value)) {
return refinementList;
}
var valueAsString = '' + value;
var facetRefinement = !refinementList[attribute] ?
[valueAsString] :
refinementList[attribute].concat(valueAsString);
var mod = {};
mod[attribute] = facetRefinement;
return defaults({}, mod, refinementList);
},
/**
* Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (isUndefined(value)) {
return lib.clearRefinement(refinementList, attribute);
}
var valueAsString = '' + value;
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f && valueAsString === v;
});
},
/**
* Toggles the refinement value for an attribute.
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (isUndefined(value)) throw new Error('toggleRefinement should be used with a value');
if (lib.isRefined(refinementList, attribute, value)) {
return lib.removeRefinement(refinementList, attribute, value);
}
return lib.addRefinement(refinementList, attribute, value);
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
* behaviors can happen:
* - if no attribute is provided: clears the whole list
* - if an attribute is provided as a string: clears the list for the specific attribute
* - if an attribute is provided as a function: discards the elements for which the function returns true
* @param {RefinementList} refinementList the initial list
* @param {string} [attribute] the attribute or function to discard
* @param {string} [refinementType] optionnal parameter to give more context to the attribute function
* @return {RefinementList} a new and updated refinement list
*/
clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
if (isUndefined(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(refinementList, attribute);
} else if (isFunction(attribute)) {
return reduce(refinementList, function(memo, values, key) {
var facetList = filter(values, function(value) {
return !attribute(value, key, refinementType);
});
if (!isEmpty(facetList)) memo[key] = facetList;
return memo;
}, {});
}
},
/**
* Test if the refinement value is used for the attribute. If no refinement value
* is provided, test if the refinementList contains any refinement for the
* given attribute.
* @param {RefinementList} refinementList the list of refinement
* @param {string} attribute name of the attribute
* @param {string} [refinementValue] value of the filter/refinement
* @return {boolean}
*/
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var indexOf = __webpack_require__(69);
var containsRefinements = !!refinementList[attribute] &&
refinementList[attribute].length > 0;
if (isUndefined(refinementValue) || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return indexOf(refinementList[attribute], refinementValueAsString) !== -1;
}
};
module.exports = lib;
/***/ }),
/* 243 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(33);
var filter = __webpack_require__(101);
var map = __webpack_require__(16);
var isEmpty = __webpack_require__(7);
var indexOf = __webpack_require__(69);
function filterState(state, filters) {
var partialState = {};
var attributeFilters = filter(filters, function(f) { return f.indexOf('attribute:') !== -1; });
var attributes = map(attributeFilters, function(aF) { return aF.split(':')[1]; });
if (indexOf(attributes, '*') === -1) {
forEach(attributes, function(attr) {
if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) {
if (!partialState.facetsRefinements) partialState.facetsRefinements = {};
partialState.facetsRefinements[attr] = state.facetsRefinements[attr];
}
if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) {
if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {};
partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr];
}
if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) {
if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {};
partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr];
}
var numericRefinements = state.getNumericRefinements(attr);
if (!isEmpty(numericRefinements)) {
if (!partialState.numericRefinements) partialState.numericRefinements = {};
partialState.numericRefinements[attr] = state.numericRefinements[attr];
}
});
} else {
if (!isEmpty(state.numericRefinements)) {
partialState.numericRefinements = state.numericRefinements;
}
if (!isEmpty(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements;
if (!isEmpty(state.disjunctiveFacetsRefinements)) {
partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements;
}
if (!isEmpty(state.hierarchicalFacetsRefinements)) {
partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements;
}
}
var searchParameters = filter(
filters,
function(f) {
return f.indexOf('attribute:') === -1;
}
);
forEach(
searchParameters,
function(parameterKey) {
partialState[parameterKey] = state[parameterKey];
}
);
return partialState;
}
module.exports = filterState;
/***/ }),
/* 244 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var invert = __webpack_require__(202);
var keys = __webpack_require__(9);
var keys2Short = {
advancedSyntax: 'aS',
allowTyposOnNumericTokens: 'aTONT',
analyticsTags: 'aT',
analytics: 'a',
aroundLatLngViaIP: 'aLLVIP',
aroundLatLng: 'aLL',
aroundPrecision: 'aP',
aroundRadius: 'aR',
attributesToHighlight: 'aTH',
attributesToRetrieve: 'aTR',
attributesToSnippet: 'aTS',
disjunctiveFacetsRefinements: 'dFR',
disjunctiveFacets: 'dF',
distinct: 'd',
facetsExcludes: 'fE',
facetsRefinements: 'fR',
facets: 'f',
getRankingInfo: 'gRI',
hierarchicalFacetsRefinements: 'hFR',
hierarchicalFacets: 'hF',
highlightPostTag: 'hPoT',
highlightPreTag: 'hPrT',
hitsPerPage: 'hPP',
ignorePlurals: 'iP',
index: 'idx',
insideBoundingBox: 'iBB',
insidePolygon: 'iPg',
length: 'l',
maxValuesPerFacet: 'mVPF',
minimumAroundRadius: 'mAR',
minProximity: 'mP',
minWordSizefor1Typo: 'mWS1T',
minWordSizefor2Typos: 'mWS2T',
numericFilters: 'nF',
numericRefinements: 'nR',
offset: 'o',
optionalWords: 'oW',
page: 'p',
queryType: 'qT',
query: 'q',
removeWordsIfNoResults: 'rWINR',
replaceSynonymsInHighlight: 'rSIH',
restrictSearchableAttributes: 'rSA',
synonyms: 's',
tagFilters: 'tF',
tagRefinements: 'tR',
typoTolerance: 'tT',
optionalTagFilters: 'oTF',
optionalFacetFilters: 'oFF',
snippetEllipsisText: 'sET',
disableExactOnAttributes: 'dEOA',
enableExactOnSingleWordQuery: 'eEOSWQ'
};
var short2Keys = invert(keys2Short);
module.exports = {
/**
* All the keys of the state, encoded.
* @const
*/
ENCODED_PARAMETERS: keys(short2Keys),
/**
* Decode a shorten attribute
* @param {string} shortKey the shorten attribute
* @return {string} the decoded attribute, undefined otherwise
*/
decode: function(shortKey) {
return short2Keys[shortKey];
},
/**
* Encode an attribute into a short version
* @param {string} key the attribute
* @return {string} the shorten attribute
*/
encode: function(key) {
return keys2Short[key];
}
};
/***/ }),
/* 245 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = generateTrees;
var last = __webpack_require__(205);
var map = __webpack_require__(16);
var reduce = __webpack_require__(50);
var orderBy = __webpack_require__(107);
var trim = __webpack_require__(208);
var find = __webpack_require__(46);
var pickBy = __webpack_require__(335);
var prepareHierarchicalFacetSortBy = __webpack_require__(118);
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] &&
state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || '';
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet);
var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet));
var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, hierarchicalFacetRefinement);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length);
}
return reduce(results, generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null, // root level, no count
isRefined: true, // root level, always refined
path: null, // root level, no path
data: null
});
};
}
function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, currentRefinement) {
return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
parent = parent && find(parent.data, {isRefined: true});
level++;
}
}
// we found a refined parent, let's add current level data under it
if (parent) {
// filter values in case an object has multiple categories:
// {
// categories: {
// level0: ['beers', 'bières'],
// level1: ['beers > IPA', 'bières > Belges']
// }
// }
//
// If parent refinement is `beers`, then we do not want to have `bières > Belges`
// showing up
var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath,
currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel);
parent.data = orderBy(
map(
pickBy(hierarchicalFacetResult.data, onlyMatchingValuesFn),
formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement)
),
sortBy[0], sortBy[1]
);
}
return hierarchicalTree;
};
}
function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel) {
return function(facetCount, facetValue) {
// we want the facetValue is a child of hierarchicalRootPath
if (hierarchicalRootPath &&
(facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) {
return false;
}
// we always want root levels (only when there is no prefix path)
return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 ||
// if there is a rootPath, being root level mean 1 level under rootPath
hierarchicalRootPath &&
facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 ||
// if current refinement is a root level and current facetValue is a root level,
// keep the facetValue
facetValue.indexOf(hierarchicalSeparator) === -1 &&
currentRefinement.indexOf(hierarchicalSeparator) === -1 ||
// currentRefinement is a child of the facet value
currentRefinement.indexOf(facetValue) === 0 ||
// facetValue is a child of the current parent, add it
facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 &&
(hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0);
};
}
function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) {
return function format(facetCount, facetValue) {
return {
name: trim(last(facetValue.split(hierarchicalSeparator))),
path: facetValue,
count: facetCount,
isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
data: null
};
};
}
/***/ }),
/* 246 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var SearchParameters = __webpack_require__(76);
var SearchResults = __webpack_require__(117);
var DerivedHelper = __webpack_require__(241);
var requestBuilder = __webpack_require__(248);
var util = __webpack_require__(115);
var events = __webpack_require__(109);
var flatten = __webpack_require__(200);
var forEach = __webpack_require__(33);
var isEmpty = __webpack_require__(7);
var map = __webpack_require__(16);
var url = __webpack_require__(119);
var version = __webpack_require__(120);
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {SearchParameters} state the current parameters with the latest changes applied
* @property {SearchResults} lastResults the previous results received from Algolia. `null` before
* the first request
* @example
* helper.on('change', function(state, lastResults) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when the search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {SearchParameters} state the parameters used for this search
* @property {SearchResults} lastResults the results from the previous search. `null` if
* it is the first search.
* @example
* helper.on('search', function(state, lastResults) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {SearchResults} results the results received from Algolia
* @property {SearchParameters} state the parameters used to query Algolia. Those might
* be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(results, state) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {Error} error the error returned by the Algolia.
* @example
* helper.on('error', function(error) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line
else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version);
this.setClient(client);
var opts = options || {};
opts.index = index;
this.state = SearchParameters.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
this.derivedHelpers = [];
}
util.inherits(AlgoliaSearchHelper, events.EventEmitter);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occcurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper}
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper.prototype.search = function() {
this._search();
return this;
};
/**
* Gets the search query parameters that would be sent to the Algolia Client
* for the hits
* @return {object} Query Parameters
*/
AlgoliaSearchHelper.prototype.getQuery = function() {
var state = this.state;
return requestBuilder._getHitsSearchParams(state);
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [callback] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occured it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder._getQueries(tempState.index, tempState);
if (cb) {
return this.client.search(
queries,
function(err, content) {
if (err) cb(err, null, tempState);
else cb(err, new SearchResults(tempState, content.results), tempState);
}
);
}
return this.client.search(queries).then(function(content) {
return {
content: new SearchResults(tempState, content.results),
state: tempState,
_originalResponse: content
};
});
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {objet}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query insde the engine
*/
/**
* Search for facet values based on an query and the name of a facetted attribute. This
* triggers a search and will retrun a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} query the string query for the search
* @param {string} facet the name of the facetted attribute
* @return {promise<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query) {
var state = this.state;
var index = this.client.initIndex(this.state.index);
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, this.state);
return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) {
content.facetHits = forEach(content.facetHits, function(f) {
f.isRefined = isDisjunctive ?
state.isDisjunctiveFacetRefined(facet, f.value) :
state.isFacetRefined(facet, f.value);
});
return content;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function(q) {
this.state = this.state.setPage(0).setQuery(q);
this._change();
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
this.state = this.state.setPage(0).clearRefinements(name);
this._change();
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
this.state = this.state.setPage(0).clearTags();
this._change();
return this;
};
/**
* Adds a disjunctive filter to a facetted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value);
this._change();
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Adds a filter to a facetted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a facetted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).addExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function(tag) {
this.state = this.state.setPage(0).addTagRefinement(tag);
this._change();
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optionnals, triggering different behaviors:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Removes a disjunctive filter to a facetted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) {
this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet);
this._change();
return this;
};
/**
* Removes a filter to a facetted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a facetted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).removeExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function(tag) {
this.state = this.state.setPage(0).removeTagRefinement(tag);
this._change();
return this;
};
/**
* Adds or removes an exclusion filter to a facetted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a facetted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a facetted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).toggleFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function() {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
this.state = this.state.setPage(0).toggleTagRefinement(tag);
this._change();
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
return this.setPage(this.state.page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
return this.setPage(this.state.page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this.state = this.state.setPage(page);
this._change();
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function(name) {
this.state = this.state.setPage(0).setIndex(name);
this._change();
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
var newState = this.state.setPage(0).setQueryParameter(parameter, value);
if (this.state === newState) return this;
this.state = newState;
this._change();
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function(newState) {
this.state = new SearchParameters(newState);
this._change();
return this;
};
/**
* Get the current search state stored in the helper. This object is immutable.
* @param {string[]} [filters] optionnal filters to retrieve only a subset of the state
* @return {SearchParameters|object} if filters is specified a plain object is
* returned containing only the requested fields, otherwise return the unfiltered
* state
* @example
* // Get the complete state as stored in the helper
* helper.getState();
* @example
* // Get a part of the state with all the refinements on attributes and the query
* helper.getState(['query', 'attribute:category']);
*/
AlgoliaSearchHelper.prototype.getState = function(filters) {
if (filters === undefined) return this.state;
return this.state.filter(filters);
};
/**
* DEPRECATED Get part of the state as a query string. By default, the output keys will not
* be prefixed and will only take the applied refinements and the query.
* @deprecated
* @param {object} [options] May contain the following parameters :
*
* **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for
* the index, all the refinements with `attribute:*` or for some specific attributes with
* `attribute:theAttribute`
*
* **prefix** : prefix in front of the keys
*
* **moreAttributes** : more values to be added in the query string. Those values
* won't be prefixed.
* @return {string} the query string
*/
AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) {
var filters = options && options.filters || ['query', 'attribute:*'];
var partialState = this.getState(filters);
return url.getQueryStringFromState(partialState, options);
};
/**
* DEPRECATED Read a query string and return an object containing the state. Use
* url module.
* @deprecated
* @static
* @param {string} queryString the query string that will be decoded
* @param {object} options accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
* @see {@link url#getStateFromQueryString}
*/
AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString;
/**
* DEPRECATED Retrieve an object of all the properties that are not understandable as helper
* parameters. Use url module.
* @deprecated
* @static
* @param {string} queryString the query string to read
* @param {object} options the options
* - prefixForParameters : prefix used for the helper configuration keys
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString;
/**
* DEPRECATED Overrides part of the state with the properties stored in the provided query
* string.
* @deprecated
* @param {string} queryString the query string containing the informations to url the state
* @param {object} options optionnal parameters :
* - prefix : prefix used for the algolia parameters
* - triggerChange : if set to true the state update will trigger a change event
*/
AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) {
var triggerChange = options && options.triggerChange || false;
var configuration = url.getStateFromQueryString(queryString, options);
var updatedState = this.state.setQueryParameters(configuration);
if (triggerChange) this.setState(updatedState);
else this.overrideStateWithoutTriggeringChangeEvent(updatedState);
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters(newState);
return this;
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isRefined = function(facet, value) {
if (this.state.isConjunctiveFacet(facet)) {
return this.state.isFacetRefined(facet, value);
} else if (this.state.isDisjunctiveFacet(facet)) {
return this.state.isDisjunctiveFacetRefined(facet, value);
}
throw new Error(facet +
' is not properly defined in this helper configuration' +
'(use the facets or disjunctiveFacets keys to configure it)');
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
if (!isEmpty(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
}
// there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific facetted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for facetting
* @param {string} [value] optionnal value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) {
return this.state.isDisjunctiveFacetRefined(facet, value);
};
/**
* Check if the string is a currently filtering tag.
* @param {string} tag tag to check
* @return {boolean}
*/
AlgoliaSearchHelper.prototype.hasTag = function(tag) {
return this.state.isTagRefined(tag);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag}
*/
AlgoliaSearchHelper.prototype.isTagRefined = function() {
return this.hasTagRefinements.apply(this, arguments);
};
/**
* Get the name of the currently used index.
* @return {string}
* @example
* helper.setIndex('highestPrice_products').getIndex();
* // returns 'highestPrice_products'
*/
AlgoliaSearchHelper.prototype.getIndex = function() {
return this.state.index;
};
function getCurrentPage() {
return this.state.page;
}
/**
* Get the currently selected page
* @deprecated
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage;
/**
* Get the currently selected page
* @function
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getPage = getCurrentPage;
/**
* Get all the tags currently set to filters the results.
*
* @return {string[]} The list of tags currently set.
*/
AlgoliaSearchHelper.prototype.getTags = function() {
return this.state.tagRefinements;
};
/**
* Get a parameter of the search by its name. It is possible that a parameter is directly
* defined in the index dashboard, but it will be undefined using this method.
*
* The complete list of parameters is
* available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters have their own API)
* @param {string} parameterName the parameter name
* @return {any} the parameter value
* @example
* var hitsPerPage = helper.getQueryParameter('hitsPerPage');
*/
AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) {
return this.state.getQueryParameter(parameterName);
};
/**
* Get the list of refinements for a given attribute. This method works with
* conjunctive, disjunctive, excluding and numerical filters.
*
* See also SearchResults#getRefinements
*
* @param {string} facetName attribute name used for facetting
* @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and
* a type. Numeric also contains an operator.
* @example
* helper.addNumericRefinement('price', '>', 100);
* helper.getRefinements('price');
* // [
* // {
* // "value": [
* // 100
* // ],
* // "operator": ">",
* // "type": "numeric"
* // }
* // ]
* @example
* helper.addFacetRefinement('color', 'blue');
* helper.addFacetExclusion('color', 'red');
* helper.getRefinements('color');
* // [
* // {
* // "value": "blue",
* // "type": "conjunctive"
* // },
* // {
* // "value": "red",
* // "type": "exclude"
* // }
* // ]
* @example
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* // [
* // {
* // "value": "plastic",
* // "type": "disjunctive"
* // }
* // ]
*/
AlgoliaSearchHelper.prototype.getRefinements = function(facetName) {
var refinements = [];
if (this.state.isConjunctiveFacet(facetName)) {
var conjRefinements = this.state.getConjunctiveRefinements(facetName);
forEach(conjRefinements, function(r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
forEach(excludeRefinements, function(r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
forEach(disjRefinements, function(r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
forEach(numericRefinements, function(value, operator) {
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
};
// /////////// PRIVATE
/**
* Perform the underlying queries
* @private
* @return {undefined}
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper.prototype._search = function() {
var state = this.state;
var mainQueries = requestBuilder._getQueries(state.index, state);
var states = [{
state: state,
queriesCount: mainQueries.length,
helper: this
}];
this.emit('search', state, this.lastResults);
var derivedQueries = map(this.derivedHelpers, function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var queries = requestBuilder._getQueries(derivedState.index, derivedState);
states.push({
state: derivedState,
queriesCount: queries.length,
helper: derivedHelper
});
derivedHelper.emit('search', derivedState, derivedHelper.lastResults);
return queries;
});
var queries = mainQueries.concat(flatten(derivedQueries));
var queryId = this._queryId++;
this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId));
};
/**
* Transform the responses as sent by the server and transform them into a user
* usable objet that merge the results of all the batch requests. It will dispatch
* over the different helper + derived helpers (when there are some).
* @private
* @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>}
* state state used for to generate the request
* @param {number} queryId id of the current request
* @param {Error} err error if any, null otherwise
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) {
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._lastQueryIdReceived = queryId;
if (err) {
this.emit('error', err);
return;
}
var results = content.results;
forEach(states, function(s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults(state, specificResults);
helper.emit('result', formattedResponse, state);
});
};
AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query ||
facetFilters.length !== 0 ||
numericFilters.length !== 0 ||
tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean}
*/
AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) {
return this.state.disjunctiveRefinements[facet] &&
this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper.prototype._change = function() {
this.emit('change', this.state, this.lastResults);
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearCache = function() {
this.client.clearCache();
return this;
};
/**
* Updates the internal client instance. If the reference of the clients
* are equal then no update is actually done.
* @param {AlgoliaSearch} newClient an AlgoliaSearch client
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.setClient = function(newClient) {
if (this.client === newClient) return this;
if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version);
this.client = newClient;
return this;
};
/**
* Gets the instance of the currently used client.
* @return {AlgoliaSearch}
*/
AlgoliaSearchHelper.prototype.getClient = function() {
return this.client;
};
/**
* Creates an derived instance of the Helper. A derived helper
* is a way to request other indices synchronised with the lifecycle
* of the main Helper. This mechanism uses the multiqueries feature
* of Algolia to aggregate all the requests in a single network call.
*
* This method takes a function that is used to create a new SearchParameter
* that will be used to create requests to Algolia. Those new requests
* are created just before the `search` event. The signature of the function
* is `SearchParameters -> SearchParameters`.
*
* This method returns a new DerivedHelper which is an EventEmitter
* that fires the same `search`, `results` and `error` events. Those
* events, however, will receive data specific to this DerivedHelper
* and the SearchParameters that is returned by the call of the
* parameter function.
* @param {function} fn SearchParameters -> SearchParameters
* @return {DerivedHelper}
*/
AlgoliaSearchHelper.prototype.derive = function(fn) {
var derivedHelper = new DerivedHelper(this, fn);
this.derivedHelpers.push(derivedHelper);
return derivedHelper;
};
/**
* This method detaches a derived Helper from the main one. Prefer using the one from the
* derived helper itself, to remove the event listeners too.
* @private
* @return {undefined}
* @throws Error
*/
AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) {
var pos = this.derivedHelpers.indexOf(derivedHelper);
if (pos === -1) throw new Error('Derived helper already detached');
this.derivedHelpers.splice(pos, 1);
};
/**
* @typedef AlgoliaSearchHelper.NumericRefinement
* @type {object}
* @property {number[]} value the numbers that are used for filtering this attribute with
* the operator specified.
* @property {string} operator the facetting data: value, number of entries
* @property {string} type will be 'numeric'
*/
/**
* @typedef AlgoliaSearchHelper.FacetRefinement
* @type {object}
* @property {string} value the string use to filter the attribute
* @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude'
*/
/*
* This function tests if the _ua parameter of the client
* already contains the JS Helper UA
*/
function doesClientAgentContainsHelper(client) {
// this relies on JS Client internal variable, this might break if implementation changes
var currentAgent = client._ua;
return !currentAgent ? false :
currentAgent.indexOf('JS Helper') !== -1;
}
module.exports = AlgoliaSearchHelper;
/***/ }),
/* 247 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var map = __webpack_require__(16);
var isArray = __webpack_require__(1);
var isNumber = __webpack_require__(203);
var isString = __webpack_require__(48);
function valToNumber(v) {
if (isNumber(v)) {
return v;
} else if (isString(v)) {
return parseFloat(v);
} else if (isArray(v)) {
return map(v, valToNumber);
}
throw new Error('The value should be a number, a parseable string or an array of those.');
}
module.exports = valToNumber;
/***/ }),
/* 248 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(33);
var map = __webpack_require__(16);
var reduce = __webpack_require__(50);
var merge = __webpack_require__(106);
var isArray = __webpack_require__(1);
var requestBuilder = {
/**
* Get all the queries to send to the client, those queries can used directly
* with the Algolia client.
* @private
* @return {object[]} The queries
*/
_getQueries: function getQueries(index, state) {
var queries = [];
// One query for the hits
queries.push({
indexName: index,
params: requestBuilder._getHitsSearchParams(state)
});
// One for each disjunctive facets
forEach(state.getRefinedDisjunctiveFacets(), function(refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
// maybe more to get the root level of hierarchical facets when activated
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are deeper than level 0 (starting from `beer > IPA`)
// we want to get the root values
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true)
});
}
});
return queries;
},
/**
* Build search parameters used to fetch hits
* @private
* @return {object.<string, any>}
*/
_getHitsSearchParams: function(state) {
var facets = state.facets
.concat(state.disjunctiveFacets)
.concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state));
var facetFilters = requestBuilder._getFacetFilters(state);
var numericFilters = requestBuilder._getNumericFilters(state);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
facets: facets,
tagFilters: tagFilters
};
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @private
* @param {string} facet the associated facet name
* @param {boolean} hierarchicalRootLevel ?? FIXME
* @return {object}
*/
_getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder._getNumericFilters(state, facet);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
tagFilters: tagFilters
};
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) {
additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute(
state,
hierarchicalFacet,
hierarchicalRootLevel
);
} else {
additionalParams.facets = facet;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Return the numeric filters in an algolia request fashion
* @private
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
_getNumericFilters: function(state, facetName) {
if (state.numericFilters) {
return state.numericFilters;
}
var numericFilters = [];
forEach(state.numericRefinements, function(operators, attribute) {
forEach(operators, function(values, operator) {
if (facetName !== attribute) {
forEach(values, function(value) {
if (isArray(value)) {
var vs = map(value, function(v) {
return attribute + operator + v;
});
numericFilters.push(vs);
} else {
numericFilters.push(attribute + operator + value);
}
});
}
});
});
return numericFilters;
},
/**
* Return the tags filters depending
* @private
* @return {string}
*/
_getTagFilters: function(state) {
if (state.tagFilters) {
return state.tagFilters;
}
return state.tagRefinements.join(',');
},
/**
* Build facetFilters parameter based on current refinements. The array returned
* contains strings representing the facet filters in the algolia format.
* @private
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.<string>}
*/
_getFacetFilters: function(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
forEach(state.facetsRefinements, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
forEach(state.facetsExcludes, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
forEach(state.disjunctiveFacetsRefinements, function(facetValues, facetName) {
if (facetName === facet || !facetValues || facetValues.length === 0) return;
var orFilters = [];
forEach(facetValues, function(facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
forEach(state.hierarchicalFacetsRefinements, function(facetValues, facetName) {
var facetValue = facetValues[0];
if (facetValue === undefined) {
return;
}
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex;
// we ask for parent facet values only when the `facet` is the current hierarchical facet
if (facet === facetName) {
// if we are at the root level already, no need to ask for facet values, we get them from
// the hits query
if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) ||
(rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) {
return;
}
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) {
facetFilters.push([attributeToRefine + ':' + facetValue]);
}
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function(state) {
var out = [];
return reduce(
state.hierarchicalFacets,
// ask for as much levels as there's hierarchical refinements
function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];
// if no refinement, ask for root level
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) {
attributeIndex = rootPath.split(separator).length;
}
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || '';
// if refinement is 'beers > IPA > Flying dog',
// then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values)
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
},
getSearchForFacetQuery: function(facetName, query, state) {
var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ?
state.clearRefinements(facetName) :
state;
var queries = merge(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), {
facetQuery: query,
facetName: facetName
});
return queries;
}
};
module.exports = requestBuilder;
/***/ }),
/* 249 */
/***/ (function(module, exports) {
module.exports = function deprecate(fn, message) {
var warned = false;
function deprecated() {
if (!warned) {
/* eslint no-console:0 */
console.log(message);
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
/***/ }),
/* 250 */
/***/ (function(module, exports) {
module.exports = function deprecatedMessage(previousUsage, newUsage) {
var githubAnchorLink = previousUsage.toLowerCase()
.replace('.', '')
.replace('()', '');
return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
'`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink;
};
/***/ }),
/* 251 */
/***/ (function(module, exports) {
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
module.exports = addMapEntry;
/***/ }),
/* 252 */
/***/ (function(module, exports) {
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
module.exports = addSetEntry;
/***/ }),
/* 253 */
/***/ (function(module, exports) {
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
module.exports = asciiToArray;
/***/ }),
/* 254 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
keys = __webpack_require__(9);
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
module.exports = baseAssign;
/***/ }),
/* 255 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
keysIn = __webpack_require__(49);
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
module.exports = baseAssignIn;
/***/ }),
/* 256 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
module.exports = baseClamp;
/***/ }),
/* 257 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
arrayEach = __webpack_require__(81),
assignValue = __webpack_require__(86),
baseAssign = __webpack_require__(254),
baseAssignIn = __webpack_require__(255),
cloneBuffer = __webpack_require__(145),
copyArray = __webpack_require__(64),
copySymbols = __webpack_require__(292),
copySymbolsIn = __webpack_require__(293),
getAllKeys = __webpack_require__(92),
getAllKeysIn = __webpack_require__(93),
getTag = __webpack_require__(67),
initCloneArray = __webpack_require__(308),
initCloneByTag = __webpack_require__(309),
initCloneObject = __webpack_require__(166),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(31),
isObject = __webpack_require__(5),
keys = __webpack_require__(9);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
module.exports = baseClone;
/***/ }),
/* 258 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(55),
arrayIncludes = __webpack_require__(83),
arrayIncludesWith = __webpack_require__(128),
arrayMap = __webpack_require__(11),
baseUnary = __webpack_require__(43),
cacheHas = __webpack_require__(63);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
module.exports = baseDifference;
/***/ }),
/* 259 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(59);
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
module.exports = baseFilter;
/***/ }),
/* 260 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
module.exports = baseHasIn;
/***/ }),
/* 261 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(55),
arrayIncludes = __webpack_require__(83),
arrayIncludesWith = __webpack_require__(128),
arrayMap = __webpack_require__(11),
baseUnary = __webpack_require__(43),
cacheHas = __webpack_require__(63);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? arrayIncludesWith : arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = arrayMap(array, baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
module.exports = baseIntersection;
/***/ }),
/* 262 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(41);
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
module.exports = baseInverter;
/***/ }),
/* 263 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
baseIsEqual = __webpack_require__(61);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
module.exports = baseIsMatch;
/***/ }),
/* 264 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
module.exports = baseIsNaN;
/***/ }),
/* 265 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(5),
isPrototype = __webpack_require__(45),
nativeKeysIn = __webpack_require__(314);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = baseKeysIn;
/***/ }),
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsMatch = __webpack_require__(263),
getMatchData = __webpack_require__(305),
matchesStrictComparable = __webpack_require__(180);
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
module.exports = baseMatches;
/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(61),
get = __webpack_require__(102),
hasIn = __webpack_require__(201),
isKey = __webpack_require__(68),
isStrictComparable = __webpack_require__(169),
matchesStrictComparable = __webpack_require__(180),
toKey = __webpack_require__(22);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
module.exports = baseMatchesProperty;
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
assignMergeValue = __webpack_require__(130),
baseFor = __webpack_require__(133),
baseMergeDeep = __webpack_require__(269),
isObject = __webpack_require__(5),
keysIn = __webpack_require__(49);
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
if (isObject(srcValue)) {
stack || (stack = new Stack);
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(object[key], srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
module.exports = baseMerge;
/***/ }),
/* 269 */
/***/ (function(module, exports, __webpack_require__) {
var assignMergeValue = __webpack_require__(130),
cloneBuffer = __webpack_require__(145),
cloneTypedArray = __webpack_require__(146),
copyArray = __webpack_require__(64),
initCloneObject = __webpack_require__(166),
isArguments = __webpack_require__(30),
isArray = __webpack_require__(1),
isArrayLikeObject = __webpack_require__(103),
isBuffer = __webpack_require__(31),
isFunction = __webpack_require__(18),
isObject = __webpack_require__(5),
isPlainObject = __webpack_require__(105),
isTypedArray = __webpack_require__(36),
toPlainObject = __webpack_require__(340);
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = object[key],
srcValue = source[key],
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
module.exports = baseMergeDeep;
/***/ }),
/* 270 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseIteratee = __webpack_require__(12),
baseMap = __webpack_require__(139),
baseSortBy = __webpack_require__(277),
baseUnary = __webpack_require__(43),
compareMultiple = __webpack_require__(291),
identity = __webpack_require__(23);
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
var index = -1;
iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
module.exports = baseOrderBy;
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
var basePickBy = __webpack_require__(140),
hasIn = __webpack_require__(201);
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
}
module.exports = basePick;
/***/ }),
/* 272 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
/***/ }),
/* 273 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(60);
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
module.exports = basePropertyDeep;
/***/ }),
/* 274 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
module.exports = baseReduce;
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(86),
castPath = __webpack_require__(20),
isIndex = __webpack_require__(28),
isObject = __webpack_require__(5),
toKey = __webpack_require__(22);
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
module.exports = baseSet;
/***/ }),
/* 276 */
/***/ (function(module, exports, __webpack_require__) {
var constant = __webpack_require__(198),
defineProperty = __webpack_require__(153),
identity = __webpack_require__(23);
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
module.exports = baseSetToString;
/***/ }),
/* 277 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
module.exports = baseSortBy;
/***/ }),
/* 278 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
module.exports = baseSum;
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(20),
last = __webpack_require__(205),
parent = __webpack_require__(315),
toKey = __webpack_require__(22);
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
module.exports = baseUnset;
/***/ }),
/* 280 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11);
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
module.exports = baseValues;
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLikeObject = __webpack_require__(103);
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
module.exports = castArrayLikeObject;
/***/ }),
/* 282 */
/***/ (function(module, exports, __webpack_require__) {
var baseSlice = __webpack_require__(142);
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
module.exports = castSlice;
/***/ }),
/* 283 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(42);
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsEndIndex;
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(42);
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsStartIndex;
/***/ }),
/* 285 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(90);
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
module.exports = cloneDataView;
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
var addMapEntry = __webpack_require__(251),
arrayReduce = __webpack_require__(85),
mapToArray = __webpack_require__(96);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `map`.
*
* @private
* @param {Object} map The map to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned map.
*/
function cloneMap(map, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map);
return arrayReduce(array, addMapEntry, new map.constructor);
}
module.exports = cloneMap;
/***/ }),
/* 287 */
/***/ (function(module, exports) {
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
module.exports = cloneRegExp;
/***/ }),
/* 288 */
/***/ (function(module, exports, __webpack_require__) {
var addSetEntry = __webpack_require__(252),
arrayReduce = __webpack_require__(85),
setToArray = __webpack_require__(98);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `set`.
*
* @private
* @param {Object} set The set to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned set.
*/
function cloneSet(set, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set);
return arrayReduce(array, addSetEntry, new set.constructor);
}
module.exports = cloneSet;
/***/ }),
/* 289 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(15);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
module.exports = cloneSymbol;
/***/ }),
/* 290 */
/***/ (function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(24);
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
module.exports = compareAscending;
/***/ }),
/* 291 */
/***/ (function(module, exports, __webpack_require__) {
var compareAscending = __webpack_require__(290);
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
module.exports = compareMultiple;
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
getSymbols = __webpack_require__(66);
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
module.exports = copySymbols;
/***/ }),
/* 293 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
getSymbolsIn = __webpack_require__(159);
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
module.exports = copySymbolsIn;
/***/ }),
/* 294 */
/***/ (function(module, exports) {
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
module.exports = countHolders;
/***/ }),
/* 295 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(13);
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
module.exports = createBaseEach;
/***/ }),
/* 296 */
/***/ (function(module, exports) {
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
/***/ }),
/* 297 */
/***/ (function(module, exports, __webpack_require__) {
var createCtor = __webpack_require__(65),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
module.exports = createBind;
/***/ }),
/* 298 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(56),
createCtor = __webpack_require__(65),
createHybrid = __webpack_require__(151),
createRecurry = __webpack_require__(152),
getHolder = __webpack_require__(44),
replaceHolders = __webpack_require__(32),
root = __webpack_require__(3);
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
module.exports = createCurry;
/***/ }),
/* 299 */
/***/ (function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(12),
isArrayLike = __webpack_require__(13),
keys = __webpack_require__(9);
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = baseIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
module.exports = createFind;
/***/ }),
/* 300 */
/***/ (function(module, exports, __webpack_require__) {
var baseInverter = __webpack_require__(262);
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
module.exports = createInverter;
/***/ }),
/* 301 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(56),
createCtor = __webpack_require__(65),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
module.exports = createPartial;
/***/ }),
/* 302 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(17);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
module.exports = customDefaultsAssignIn;
/***/ }),
/* 303 */
/***/ (function(module, exports, __webpack_require__) {
var isPlainObject = __webpack_require__(105);
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
module.exports = customOmitClone;
/***/ }),
/* 304 */
/***/ (function(module, exports, __webpack_require__) {
var realNames = __webpack_require__(316);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
module.exports = getFuncName;
/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {
var isStrictComparable = __webpack_require__(169),
keys = __webpack_require__(9);
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
module.exports = getMatchData;
/***/ }),
/* 306 */
/***/ (function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
module.exports = getWrapDetails;
/***/ }),
/* 307 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
module.exports = hasUnicode;
/***/ }),
/* 308 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
module.exports = initCloneArray;
/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(90),
cloneDataView = __webpack_require__(285),
cloneMap = __webpack_require__(286),
cloneRegExp = __webpack_require__(287),
cloneSet = __webpack_require__(288),
cloneSymbol = __webpack_require__(289),
cloneTypedArray = __webpack_require__(146);
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, cloneFunc, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return cloneMap(object, isDeep, cloneFunc);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return cloneSet(object, isDeep, cloneFunc);
case symbolTag:
return cloneSymbol(object);
}
}
module.exports = initCloneByTag;
/***/ }),
/* 310 */
/***/ (function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
module.exports = insertWrapDetails;
/***/ }),
/* 311 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(15),
isArguments = __webpack_require__(30),
isArray = __webpack_require__(1);
/** Built-in value references. */
var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
module.exports = isFlattenable;
/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(78),
getData = __webpack_require__(157),
getFuncName = __webpack_require__(304),
lodash = __webpack_require__(342);
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
module.exports = isLaziable;
/***/ }),
/* 313 */
/***/ (function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(147),
composeArgsRight = __webpack_require__(148),
replaceHolders = __webpack_require__(32);
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
module.exports = mergeData;
/***/ }),
/* 314 */
/***/ (function(module, exports) {
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
module.exports = nativeKeysIn;
/***/ }),
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(60),
baseSlice = __webpack_require__(142);
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
module.exports = parent;
/***/ }),
/* 316 */
/***/ (function(module, exports) {
/** Used to lookup unminified function names. */
var realNames = {};
module.exports = realNames;
/***/ }),
/* 317 */
/***/ (function(module, exports, __webpack_require__) {
var copyArray = __webpack_require__(64),
isIndex = __webpack_require__(28);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
module.exports = reorder;
/***/ }),
/* 318 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
module.exports = strictIndexOf;
/***/ }),
/* 319 */
/***/ (function(module, exports, __webpack_require__) {
var asciiToArray = __webpack_require__(253),
hasUnicode = __webpack_require__(307),
unicodeToArray = __webpack_require__(320);
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
module.exports = stringToArray;
/***/ }),
/* 320 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
module.exports = unicodeToArray;
/***/ }),
/* 321 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(81),
arrayIncludes = __webpack_require__(83);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
module.exports = updateWrapDetails;
/***/ }),
/* 322 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(78),
LodashWrapper = __webpack_require__(125),
copyArray = __webpack_require__(64);
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
module.exports = wrapperClone;
/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
createAssigner = __webpack_require__(150),
keysIn = __webpack_require__(49);
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
module.exports = assignInWith;
/***/ }),
/* 324 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(19),
createWrap = __webpack_require__(91),
getHolder = __webpack_require__(44),
replaceHolders = __webpack_require__(32);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
// Assign default placeholders.
bind.placeholder = {};
module.exports = bind;
/***/ }),
/* 325 */
/***/ (function(module, exports) {
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = compact;
/***/ }),
/* 326 */
/***/ (function(module, exports, __webpack_require__) {
var baseDifference = __webpack_require__(258),
baseFlatten = __webpack_require__(132),
baseRest = __webpack_require__(19),
isArrayLikeObject = __webpack_require__(103);
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
: [];
});
module.exports = difference;
/***/ }),
/* 327 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(41),
castFunction = __webpack_require__(144);
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && baseForOwn(object, castFunction(iteratee));
}
module.exports = forOwn;
/***/ }),
/* 328 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(42),
isArrayLike = __webpack_require__(13),
isString = __webpack_require__(48),
toInteger = __webpack_require__(51),
values = __webpack_require__(341);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
module.exports = includes;
/***/ }),
/* 329 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseIntersection = __webpack_require__(261),
baseRest = __webpack_require__(19),
castArrayLikeObject = __webpack_require__(281);
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped)
: [];
});
module.exports = intersection;
/***/ }),
/* 330 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(40),
baseForOwn = __webpack_require__(41),
baseIteratee = __webpack_require__(12);
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
module.exports = mapKeys;
/***/ }),
/* 331 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(40),
baseForOwn = __webpack_require__(41),
baseIteratee = __webpack_require__(12);
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
module.exports = mapValues;
/***/ }),
/* 332 */
/***/ (function(module, exports) {
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
module.exports = noop;
/***/ }),
/* 333 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(19),
createWrap = __webpack_require__(91),
getHolder = __webpack_require__(44),
replaceHolders = __webpack_require__(32);
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partial.placeholder = {};
module.exports = partial;
/***/ }),
/* 334 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(19),
createWrap = __webpack_require__(91),
getHolder = __webpack_require__(44),
replaceHolders = __webpack_require__(32);
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partialRight.placeholder = {};
module.exports = partialRight;
/***/ }),
/* 335 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(11),
baseIteratee = __webpack_require__(12),
basePickBy = __webpack_require__(140),
getAllKeysIn = __webpack_require__(93);
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = baseIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
module.exports = pickBy;
/***/ }),
/* 336 */
/***/ (function(module, exports, __webpack_require__) {
var baseProperty = __webpack_require__(272),
basePropertyDeep = __webpack_require__(273),
isKey = __webpack_require__(68),
toKey = __webpack_require__(22);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
module.exports = property;
/***/ }),
/* 337 */
/***/ (function(module, exports, __webpack_require__) {
var baseClamp = __webpack_require__(256),
baseToString = __webpack_require__(62),
toInteger = __webpack_require__(51),
toString = __webpack_require__(70);
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
module.exports = startsWith;
/***/ }),
/* 338 */
/***/ (function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(12),
baseSum = __webpack_require__(278);
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, baseIteratee(iteratee, 2))
: 0;
}
module.exports = sumBy;
/***/ }),
/* 339 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(5),
isSymbol = __webpack_require__(24);
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = toNumber;
/***/ }),
/* 340 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(21),
keysIn = __webpack_require__(49);
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
module.exports = toPlainObject;
/***/ }),
/* 341 */
/***/ (function(module, exports, __webpack_require__) {
var baseValues = __webpack_require__(280),
keys = __webpack_require__(9);
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
module.exports = values;
/***/ }),
/* 342 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(78),
LodashWrapper = __webpack_require__(125),
baseLodash = __webpack_require__(89),
isArray = __webpack_require__(1),
isObjectLike = __webpack_require__(6),
wrapperClone = __webpack_require__(322);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
module.exports = lodash;
/***/ }),
/* 343 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Highlighter;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Highlighter(_ref) {
var hit = _ref.hit,
attributeName = _ref.attributeName,
highlight = _ref.highlight,
highlightProperty = _ref.highlightProperty;
var parsedHighlightedValue = highlight({ hit: hit, attributeName: attributeName, highlightProperty: highlightProperty });
var reactHighlighted = parsedHighlightedValue.map(function (v, i) {
var key = "split-" + i + "-" + v.value;
if (!v.isHighlighted) {
return _react2.default.createElement(
"span",
{ key: key, className: "ais-Highlight__nonHighlighted" },
v.value
);
}
return _react2.default.createElement(
"em",
{ key: key, className: "ais-Highlight__highlighted" },
v.value
);
});
return _react2.default.createElement(
"span",
{ className: "ais-Highlight" },
reactHighlighted
);
}
Highlighter.propTypes = {
hit: _react2.default.PropTypes.object.isRequired,
attributeName: _react2.default.PropTypes.string.isRequired,
highlight: _react2.default.PropTypes.func.isRequired,
highlightProperty: _react2.default.PropTypes.string.isRequired
};
/***/ }),
/* 344 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('SearchBox');
var SearchBox = function (_Component) {
_inherits(SearchBox, _Component);
function SearchBox(props) {
_classCallCheck(this, SearchBox);
var _this = _possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this));
_this.getQuery = function () {
return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query;
};
_this.setQuery = function (val) {
var _this$props = _this.props,
refine = _this$props.refine,
searchAsYouType = _this$props.searchAsYouType;
if (searchAsYouType) {
refine(val);
} else {
_this.setState({
query: val
});
}
};
_this.onInputMount = function (input) {
_this.input = input;
if (_this.props.__inputRef) {
_this.props.__inputRef(input);
}
};
_this.onKeyDown = function (e) {
if (!_this.props.focusShortcuts) {
return;
}
var shortcuts = _this.props.focusShortcuts.map(function (key) {
return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key;
});
var elt = e.target || e.srcElement;
var tagName = elt.tagName;
if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') {
// already in an input
return;
}
var which = e.which || e.keyCode;
if (shortcuts.indexOf(which) === -1) {
// not the right shortcut
return;
}
_this.input.focus();
e.stopPropagation();
e.preventDefault();
};
_this.onSubmit = function (e) {
e.preventDefault();
e.stopPropagation();
var _this$props2 = _this.props,
refine = _this$props2.refine,
searchAsYouType = _this$props2.searchAsYouType;
if (!searchAsYouType) {
refine(_this.getQuery());
}
return false;
};
_this.onChange = function (e) {
_this.setQuery(e.target.value);
};
_this.onReset = function () {
_this.setQuery('');
_this.input.focus();
};
_this.state = {
query: props.searchAsYouType ? null : props.currentRefinement
};
return _this;
}
_createClass(SearchBox, [{
key: 'componentDidMount',
value: function componentDidMount() {
document.addEventListener('keydown', this.onKeyDown);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
document.removeEventListener('keydown', this.onKeyDown);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
// Reset query when the searchParameters query has changed.
// This is kind of an anti-pattern (props in state), but it works here
// since we know for sure that searchParameters having changed means a
// new search has been triggered.
if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) {
this.setState({
query: nextProps.currentRefinement
});
}
}
// From https://github.com/algolia/autocomplete.js/pull/86
}, {
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
autoFocus = _props.autoFocus;
var query = this.getQuery();
/* eslint-disable max-len */
return _react2.default.createElement(
'form',
_extends({
noValidate: true,
onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit,
onReset: this.onReset
}, cx('root')),
_react2.default.createElement(
'svg',
{ xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } },
_react2.default.createElement(
'symbol',
{ xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-search-13', viewBox: '0 0 40 40' },
_react2.default.createElement('path', { d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z',
fillRule: 'evenodd' })
),
_react2.default.createElement(
'symbol',
{ xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-clear-3', viewBox: '0 0 20 20' },
_react2.default.createElement('path', { d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z', fillRule: 'evenodd' })
)
),
_react2.default.createElement(
'div',
_extends({
role: 'search'
}, cx('wrapper')),
_react2.default.createElement('input', _extends({
ref: this.onInputMount,
type: 'search',
placeholder: translate('placeholder'),
autoFocus: autoFocus,
autoComplete: 'off',
required: true,
value: query,
onChange: this.onChange
}, cx('input'))),
_react2.default.createElement(
'button',
_extends({ type: 'submit', title: translate('submitTitle') }, cx('submit')),
_react2.default.createElement(
'svg',
{ role: 'img' },
_react2.default.createElement('use', { xlinkHref: '#sbx-icon-search-13' })
)
),
_react2.default.createElement(
'button',
_extends({ type: 'reset', title: translate('resetTitle') }, cx('reset'), { onClick: this.onReset }),
_react2.default.createElement(
'svg',
{ role: 'img' },
_react2.default.createElement('use', { xlinkHref: '#sbx-icon-clear-3' })
)
)
)
);
/* eslint-enable */
}
}]);
return SearchBox;
}(_react.Component);
SearchBox.propTypes = {
currentRefinement: _react.PropTypes.string,
refine: _react.PropTypes.func.isRequired,
translate: _react.PropTypes.func.isRequired,
focusShortcuts: _react.PropTypes.arrayOf(_react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number])),
autoFocus: _react.PropTypes.bool,
searchAsYouType: _react.PropTypes.bool,
onSubmit: _react.PropTypes.func,
// For testing purposes
__inputRef: _react.PropTypes.func
};
SearchBox.defaultProps = {
currentRefinement: '',
focusShortcuts: ['s', '/'],
autoFocus: false,
searchAsYouType: true
};
exports.default = (0, _translatable2.default)({
submit: null,
reset: null,
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(SearchBox);
/***/ }),
/* 345 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _has2 = __webpack_require__(74);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Select = function (_Component) {
_inherits(Select, _Component);
function Select() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Select);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) {
_this.props.onSelect(e.target.value);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Select, [{
key: 'render',
value: function render() {
var _props = this.props,
cx = _props.cx,
items = _props.items,
selectedItem = _props.selectedItem;
return _react2.default.createElement(
'select',
_extends({}, cx('root'), {
value: selectedItem,
onChange: this.onChange
}),
items.map(function (item) {
return _react2.default.createElement(
'option',
{
key: (0, _has3.default)(item, 'key') ? item.key : item.value,
disabled: item.disabled,
value: item.value
},
(0, _has3.default)(item, 'label') ? item.label : item.value
);
})
);
}
}]);
return Select;
}(_react.Component);
Select.propTypes = {
cx: _react.PropTypes.func.isRequired,
onSelect: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
value: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]).isRequired,
key: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]),
label: _react.PropTypes.string,
disabled: _react.PropTypes.bool
})).isRequired,
selectedItem: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]).isRequired
};
exports.default = Select;
/***/ }),
/* 346 */
/***/ (function(module, exports, __webpack_require__) {
var buildSearchMethod = __webpack_require__(347);
var deprecate = __webpack_require__(249);
var deprecatedMessage = __webpack_require__(250);
module.exports = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the full text query
* @param {object} [args] (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param {function} [callback] the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the similar query
* @param {object} [args] (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery');
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = __webpack_require__(349);
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse',
body: {params: params},
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse',
body: {cursor: cursor},
hostType: 'read',
callback: callback
});
};
/*
* Search for facet values
* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
*
* @param {string} params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} params.facetQuery Query for the facet search
* @param {string} [params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
* @param callback (optional)
*/
IndexCore.prototype.searchForFacetValues = function(params, callback) {
var clone = __webpack_require__(77);
var omit = __webpack_require__(411);
var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])';
if (params.facetName === undefined || params.facetQuery === undefined) {
throw new Error(usage);
}
var facetName = params.facetName;
var filteredParams = omit(clone(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = this.as._getSearchParams(filteredParams, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' +
encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
hostType: 'read',
body: {params: searchParameters},
callback: callback
});
};
IndexCore.prototype.searchFacet = deprecate(function(params, callback) {
return this.searchForFacetValues(params, callback);
}, deprecatedMessage(
'index.searchFacet(params[, callback])',
'index.searchForFacetValues(params[, callback])'
));
IndexCore.prototype._search = function(params, url, callback, additionalUA) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback,
additionalUA: additionalUA
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occured
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = __webpack_require__(35);
var map = __webpack_require__(121);
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
/***/ }),
/* 347 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = buildSearchMethod;
var errors = __webpack_require__(111);
/**
* Creates a search method to be used in clients
* @param {string} queryParam the name of the attribute used for the query
* @param {string} url the url
* @return {function} the search method
*/
function buildSearchMethod(queryParam, url) {
/**
* The search method. Prepares the data and send the query to Algolia.
* @param {string} query the string used for query search
* @param {object} args additional parameters to send with the search
* @param {function} [callback] the callback to be called with the client gets the answer
* @return {undefined|Promise} If the callback is not provided then this methods returns a Promise
*/
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
// Normalizing the function signature
if (arguments.length === 0 || typeof query === 'function') {
// Usage : .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// Usage : .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// At this point we have 3 arguments with values
// Usage : .search(args) // careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
var additionalUA;
if (args !== undefined) {
if (args.additionalUA) {
additionalUA = args.additionalUA;
delete args.additionalUA;
}
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback, additionalUA);
};
}
/***/ }),
/* 348 */
/***/ (function(module, exports) {
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
module.exports = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
/***/ }),
/* 349 */
/***/ (function(module, exports, __webpack_require__) {
var foreach = __webpack_require__(112);
module.exports = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
/***/ }),
/* 350 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.default = createInstantSearch;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _InstantSearch = __webpack_require__(396);
var _InstantSearch2 = _interopRequireDefault(_InstantSearch);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _name$author$descript = {
name: 'react-instantsearch',
author: {
name: 'Algolia, Inc.',
url: 'https://www.algolia.com'
},
description: '\u26A1 Lightning-fast search for React and React Native apps',
version: '3.2.1',
scripts: {
build: './scripts/build.sh',
'build-and-publish': './scripts/build-and-publish.sh'
},
homepage: 'https://community.algolia.com/instantsearch.js/react/',
repository: {
type: 'git',
url: 'https://github.com/algolia/instantsearch.js/'
},
dependencies: {
algoliasearch: '^3.21.1',
'algoliasearch-helper': '^2.18.1',
classnames: '^2.2.5',
lodash: '^4.17.4'
},
license: 'MIT',
devDependencies: {
enzyme: '^2.7.1',
react: '^15.4.2',
'react-dom': '^15.4.2',
'react-native': '^0.41.2',
'react-test-renderer': '^15.4.2'
}
};
var version = _name$author$descript.version;
/**
* Creates a specialized root InstantSearch component. It accepts
* an algolia client and a specification of the root Element.
* @param {function} defaultAlgoliaClient - a function that builds an Algolia client
* @param {object} root - the defininition of the root of an InstantSearch sub tree.
* @returns {object} an InstantSearch root
*/
function createInstantSearch(defaultAlgoliaClient, root) {
var _class, _temp;
return _temp = _class = function (_Component) {
_inherits(CreateInstantSearch, _Component);
function CreateInstantSearch(props) {
_classCallCheck(this, CreateInstantSearch);
var _this = _possibleConstructorReturn(this, (CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call(this));
_this.client = props.algoliaClient || defaultAlgoliaClient(props.appId, props.apiKey);
_this.client.addAlgoliaAgent('react-instantsearch ' + version);
return _this;
}
_createClass(CreateInstantSearch, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var props = this.props;
if (nextProps.algoliaClient) {
this.client = nextProps.algoliaClient;
} else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) {
this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey);
}
this.client.addAlgoliaAgent('react-instantsearch ' + version);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(_InstantSearch2.default, {
createURL: this.props.createURL,
indexName: this.props.indexName,
searchParameters: this.props.searchParameters,
searchState: this.props.searchState,
onSearchStateChange: this.props.onSearchStateChange,
root: root,
algoliaClient: this.client,
children: this.props.children
});
}
}]);
return CreateInstantSearch;
}(_react.Component), _class.propTypes = {
algoliaClient: _react.PropTypes.object,
appId: _react.PropTypes.string,
apiKey: _react.PropTypes.string,
children: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.arrayOf(_react2.default.PropTypes.node), _react2.default.PropTypes.node]),
indexName: _react.PropTypes.string.isRequired,
searchParameters: _react.PropTypes.object,
createURL: _react.PropTypes.func,
searchState: _react.PropTypes.object,
onSearchStateChange: _react.PropTypes.func
}, _temp;
}
/***/ }),
/* 351 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectCurrentRefinements = __webpack_require__(209);
var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements);
var _ClearAll = __webpack_require__(374);
var _ClearAll2 = _interopRequireDefault(_ClearAll);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The ClearAll widget displays a button that lets the user clean every refinement applied
* to the search.
* @name ClearAll
* @kind widget
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {boolean} [clearsQuery=false] - Pass true to also clear the search query
* @themeKey ais-ClearAll__root - the widget button
* @translationKey reset - the clear all button value
* @example
* import React from 'react';
*
* import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <ClearAll />
* <RefinementList
attributeName="colors"
defaultRefinement={['Black']}
/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectCurrentRefinements2.default)(_ClearAll2.default);
/***/ }),
/* 352 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectConfigure = __webpack_require__(218);
var _connectConfigure2 = _interopRequireDefault(_connectConfigure);
var _Configure = __webpack_require__(375);
var _Configure2 = _interopRequireDefault(_Configure);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Configure is a widget that lets you provide raw search parameters
* to the Algolia API.
*
* Any of the props added to this widget will be forwarded to Algolia. For more information
* on the different parameters that can be set, have a look at the
* [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters).
*
* This widget can be used either with react-dom and react-native. It will not render anything
* on screen, only configure some parameters.
*
* Read more in the [Search parameters](guide/Search_parameters.html) guide.
* @name Configure
* @kind widget
* @example
* import React from 'react';
*
* import {Configure} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Configure distinct={1} />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectConfigure2.default)(_Configure2.default);
/***/ }),
/* 353 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectCurrentRefinements = __webpack_require__(209);
var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements);
var _CurrentRefinements = __webpack_require__(376);
var _CurrentRefinements2 = _interopRequireDefault(_CurrentRefinements);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The CurrentRefinements widget displays the list of currently applied filters.
*
* It allows the user to selectively remove them.
* @name CurrentRefinements
* @kind widget
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-CurrentRefinements__root - the root div of the widget
* @themeKey ais-CurrentRefinements__items - the container of the filters
* @themeKey ais-CurrentRefinements__item - a single filter
* @themeKey ais-CurrentRefinements__itemLabel - the label of a filter
* @themeKey ais-CurrentRefinements__itemClear - the trigger to remove the filter
* @themeKey ais-CurrentRefinements__noRefinement - present when there is no refinement
* @translationKey clearFilter - the remove filter button label
* @example
* import React from 'react';
*
* import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CurrentRefinements />
* <RefinementList
attributeName="colors"
defaultRefinement={['Black']}
/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectCurrentRefinements2.default)(_CurrentRefinements2.default);
/***/ }),
/* 354 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHierarchicalMenu = __webpack_require__(219);
var _connectHierarchicalMenu2 = _interopRequireDefault(_connectHierarchicalMenu);
var _HierarchicalMenu = __webpack_require__(377);
var _HierarchicalMenu2 = _interopRequireDefault(_HierarchicalMenu);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The hierarchical menu lets the user browse attributes using a tree-like structure.
*
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
*
* @name HierarchicalMenu
* @kind widget
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax.
* @propType {number} [limitMin=10] - The maximum number of items displayed.
* @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-HierarchicalMenu__root - Container of the widget
* @themeKey ais-HierarchicalMenu__items - Container of the items
* @themeKey ais-HierarchicalMenu__item - Id for a single list item
* @themeKey ais-HierarchicalMenu__itemSelected - Id for the selected items in the list
* @themeKey ais-HierarchicalMenu__itemParent - Id for the elements that have a sub list displayed
* @themeKey HierarchicalMenu__itemSelectedParent - Id for parents that have currently a child selected
* @themeKey ais-HierarchicalMenu__itemLink - the link containing the label and the count
* @themeKey ais-HierarchicalMenu__itemLabel - the label of the entry
* @themeKey ais-HierarchicalMenu__itemCount - the count of the entry
* @themeKey ais-HierarchicalMenu__itemItems - id representing a children
* @themeKey ais-HierarchicalMenu__showMore - container for the show more button
* @themeKey ais-HierarchicalMenu__noRefinement - present when there is no refinement
* @translationKey showMore - Label value of the button which toggles the number of items
* @example
* import React from 'react';
* import {
* InstantSearch,
* HierarchicalMenu,
* } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <HierarchicalMenu
* id="categories"
* key="categories"
* attributes={[
* 'category',
* 'sub_category',
* 'sub_sub_category',
* ]}
* />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHierarchicalMenu2.default)(_HierarchicalMenu2.default);
/***/ }),
/* 355 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHits = __webpack_require__(220);
var _connectHits2 = _interopRequireDefault(_connectHits);
var _Hits = __webpack_require__(379);
var _Hits2 = _interopRequireDefault(_Hits);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Displays a list of hits.
*
* To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html).
*
* @name Hits
* @kind widget
* @propType {Component} [hitComponent] - Component used for rendering each hit from
* the results. If it is not provided the rendering defaults to displaying the
* hit in its JSON form. The component will be called with a `hit` prop.
* @themeKey ais-Hits__root - the root of the component
* @example
* import React from 'react';
* import {
* InstantSearch,
* Hits,
* } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Hits />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHits2.default)(_Hits2.default);
/***/ }),
/* 356 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHitsPerPage = __webpack_require__(221);
var _connectHitsPerPage2 = _interopRequireDefault(_connectHitsPerPage);
var _HitsPerPage = __webpack_require__(380);
var _HitsPerPage2 = _interopRequireDefault(_HitsPerPage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The HitsPerPage widget displays a dropdown menu to let the user change the number
* of displayed hits.
*
* @name HitsPerPage
* @kind widget
* @propType {{value: number, label: string}[]} items - List of available options.
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-HitsPerPage__root - the root of the component.
* @example
* import React from 'react';
* import {
* InstantSearch,
* HitsPerPage,
* } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <HitsPerPage defaultRefinement={20}/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHitsPerPage2.default)(_HitsPerPage2.default);
/***/ }),
/* 357 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectInfiniteHits = __webpack_require__(222);
var _connectInfiniteHits2 = _interopRequireDefault(_connectInfiniteHits);
var _InfiniteHits = __webpack_require__(381);
var _InfiniteHits2 = _interopRequireDefault(_InfiniteHits);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Displays an infinite list of hits along with a **load more** button.
*
* To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html).
*
* @name InfiniteHits
* @kind widget
* @propType {Component} hitComponent - Component used for rendering each hit from
* the results. If it is not provided the rendering defaults to displaying the
* hit in its JSON form. The component will be called with a `hit` prop.
* @themeKey root - the root of the component
* @example
* import React from 'react';
* import {
* InstantSearch,
* Hits,
* } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <InfiniteHits />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectInfiniteHits2.default)(_InfiniteHits2.default);
/***/ }),
/* 358 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectMenu = __webpack_require__(223);
var _connectMenu2 = _interopRequireDefault(_connectMenu);
var _Menu = __webpack_require__(383);
var _Menu2 = _interopRequireDefault(_Menu);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Menu component displays a menu that lets the user choose a single value for a specific attribute.
* @name Menu
* @kind widget
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of diplayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values
* @themeKey ais-Menu__root - the root of the component
* @themeKey ais-Menu__items - the container of all items in the menu
* @themeKey ais-Menu__item - a single item
* @themeKey ais-Menu__itemLinkSelected - the selected menu item
* @themeKey ais-Menu__itemLink - the item link
* @themeKey ais-Menu__itemLabelSelected - the selected item label
* @themeKey ais-Menu__itemLabel - the item label
* @themeKey ais-Menu__itemCount - the item count
* @themeKey ais-Menu__itemCountSelected - the selected item count
* @themeKey ais-Menu__noRefinement - present when there is no refinement
* @themeKey ais-Menu__showMore - the button that let the user toggle more results
* @themeKey ais-Menu__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded
* @translationkey noResults - The label of the no results text when no search for facet values results are found.
* @example
* import React from 'react';
*
* import {Menu, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Menu
* attributeName="category"
* />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectMenu2.default)(_Menu2.default);
/***/ }),
/* 359 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectMultiRange = __webpack_require__(224);
var _connectMultiRange2 = _interopRequireDefault(_connectMultiRange);
var _MultiRange = __webpack_require__(384);
var _MultiRange2 = _interopRequireDefault(_MultiRange);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* MultiRange is a widget used for selecting the range value of a numeric attribute.
* @name MultiRange
* @kind widget
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the format "min:max".
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-MultiRange__root - The root component of the widget
* @themeKey ais-MultiRange__items - The container of the items
* @themeKey ais-MultiRange__item - A single item
* @themeKey ais-MultiRange__itemSelected - The selected item
* @themeKey ais-MultiRange__itemLabel - The label of an item
* @themeKey ais-MultiRange__itemLabelSelected - The selected label item
* @themeKey ais-MultiRange__itemRadio - The radio of an item
* @themeKey ais-MultiRange__itemRadioSelected - The selected radio item
* @themeKey ais-MultiRange__noRefinement - present when there is no refinement for all ranges
* @themeKey ais-MultiRange__itemNoRefinement - present when there is no refinement for one range
* @themeKey ais-MultiRange__itemAll - indicate the range that will contain all the results
* @translationkey all - The label of the largest range added automatically by react instantsearch
* @example
* import React from 'react';
*
* import {InstantSearch, MultiRange} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <MultiRange attributeName="price"
* items={[
* {end: 10, label: '<$10'},
* {start: 10, end: 100, label: '$10-$100'},
* {start: 100, end: 500, label: '$100-$500'},
* {start: 500, label: '>$500'},
* ]}
* />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectMultiRange2.default)(_MultiRange2.default);
/***/ }),
/* 360 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectPagination = __webpack_require__(225);
var _connectPagination2 = _interopRequireDefault(_connectPagination);
var _Pagination = __webpack_require__(385);
var _Pagination2 = _interopRequireDefault(_Pagination);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Pagination widget displays a simple pagination system allowing the user to
* change the current page.
* @name Pagination
* @kind widget
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [pagesPadding=3] - How many page links to display around the current page.
* @propType {number} [maxPages=Infinity] - Maximum number of pages to display.
* @themeKey ais-Pagination__root - The root component of the widget
* @themeKey ais-Pagination__itemFirst - The first page link item
* @themeKey ais-Pagination__itemPrevious - The previous page link item
* @themeKey ais-Pagination__itemPage - The page link item
* @themeKey ais-Pagination__itemNext - The next page link item
* @themeKey ais-Pagination__itemLast - The last page link item
* @themeKey ais-Pagination__itemDisabled - a disabled item
* @themeKey ais-Pagination__itemSelected - a selected item
* @themeKey ais-Pagination__itemLink - The link of an item
* @themeKey ais-Pagination__noRefinement - present when there is no refinement
* @translationKey previous - Label value for the previous page link
* @translationKey next - Label value for the next page link
* @translationKey first - Label value for the first page link
* @translationKey last - Label value for the last page link
* @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string
* @translationKey ariaPrevious - Accessibility label value for the previous page link
* @translationKey ariaNext - Accessibility label value for the next page link
* @translationKey ariaFirst - Accessibility label value for the first page link
* @translationKey ariaLast - Accessibility label value for the last page link
* @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string
* @example
* import React from 'react';
*
* import {Pagination, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Pagination/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectPagination2.default)(_Pagination2.default);
/***/ }),
/* 361 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Panel = __webpack_require__(386);
var _Panel2 = _interopRequireDefault(_Panel);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Panel widget wraps other widgets in a consistent panel design.
*
* It also reacts, indicates and set CSS classes when widgets are no more
* relevant for refining. E.g. when a RefinementList becomes empty because of
* the current search results.
* @name Panel
* @kind widget
* @propType {string} title - The panel title
* @themeKey ais-Panel__root - Container of the widget
* @themeKey ais-Panel__title - The panel title
* @themeKey ais-Panel__noRefinement - Present if the panel content is empty
* @example
* import React from 'react';
*
* import {Panel, RefinementList, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Panel title="category">
* <RefinementList attributeName="category" />
* </Panel>
* </InstantSearch>
* );
* }
*/
exports.default = _Panel2.default;
/***/ }),
/* 362 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectPoweredBy = __webpack_require__(226);
var _connectPoweredBy2 = _interopRequireDefault(_connectPoweredBy);
var _PoweredBy = __webpack_require__(387);
var _PoweredBy2 = _interopRequireDefault(_PoweredBy);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* PoweredBy displays an Algolia logo.
*
* Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing).
* @name PoweredBy
* @kind widget
* @themeKey ais-PoweredBy__root - The root component of the widget
* @themeKey ais-PoweredBy__searchBy - The powered by label
* @themeKey ais-PoweredBy__algoliaLink - The algolia logo link
* @translationKey searchBy - Label value for the powered by
* @example
* import React from 'react';
*
* import {PoweredBy, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <PoweredBy />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectPoweredBy2.default)(_PoweredBy2.default);
/***/ }),
/* 363 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectRange = __webpack_require__(114);
var _connectRange2 = _interopRequireDefault(_connectRange);
var _RangeInput = __webpack_require__(388);
var _RangeInput2 = _interopRequireDefault(_RangeInput);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* RangeInput allows a user to select a numeric range using a minimum and maximum input.
* @name RangeInput
* @kind widget
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @themeKey ais-RangeInput__root - The root component of the widget
* @themeKey ais-RangeInput__labelMin - The label for the min input
* @themeKey ais-RangeInput__inputMin - The min input
* @themeKey ais-RangeInput__separator - The separator between input
* @themeKey ais-RangeInput__labelMax - The label for the max input
* @themeKey ais-RangeInput__inputMax - The max input
* @themeKey ais-RangeInput__submit - The submit button
* @themeKey ais-RangeInput__noRefinement - present when there is no refinement
* @translationKey submit - Label value for the submit button
* @translationKey separator - Label value for the input separator
* @example
* import React from 'react';
*
* import {RangeInput, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <RangeInput attributeName="price"/>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectRange2.default)(_RangeInput2.default);
/***/ }),
/* 364 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectRange = __webpack_require__(114);
var _connectRange2 = _interopRequireDefault(_connectRange);
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Since a lot of sliders already exist, we did not include one by default.
* However you can easily connect React InstantSearch to an existing one
* using the [connectRange connector](/connectors/connectRange.html).
*
* @name RangeSlider
* @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values.
* @kind widget
* @example
*
* // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the
* // range connector
*
* import React, {PropTypes} from 'react';
* import {connectRange} from 'react-instantsearch/connectors';
* import Rheostat from 'rheostat';
*
* const Range = React.createClass({
propTypes: {
min: React.PropTypes.number,
max: React.PropTypes.number,
currentRefinement: React.PropTypes.object,
refine: React.PropTypes.func.isRequired,
canRefine: React.PropTypes.bool.isRequired,
},
getInitialState() {
return {currentValues: {min: this.props.min, max: this.props.max}};
},
componentWillReceiveProps(sliderState) {
if (sliderState.canRefine) {
this.setState({currentValues: {min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max}});
}
},
onValuesUpdated(sliderState) {
this.setState({currentValues: {min: sliderState.values[0], max: sliderState.values[1]}});
},
onChange(sliderState) {
if (this.props.currentRefinement.min !== sliderState.values[0] ||
this.props.currentRefinement.max !== sliderState.values[1]) {
this.props.refine({min: sliderState.values[0], max: sliderState.values[1]});
}
},
render() {
const {min, max, currentRefinement} = this.props;
const {currentValues} = this.state;
return min !== max ?
<div>
<Rheostat
min={min}
max={max}
values={[currentRefinement.min, currentRefinement.max]}
onChange={this.onChange}
onValuesUpdated={this.onValuesUpdated}
/>
<div style={{display: 'flex', justifyContent: 'space-between'}}>
<div>{currentValues.min}</div>
<div>{currentValues.max}</div>
</div>
</div> : null;
},
});
const ConnectedRange = connectRange(Range);
*/
exports.default = (0, _connectRange2.default)(function () {
return _react2.default.createElement(
'div',
null,
'We do not provide any Slider, see the documentation to learn how to connect one easily:',
_react2.default.createElement(
'a',
{ target: '_blank', href: 'https://community.algolia.com/instantsearch.js/react/widgets/RangeSlider.html' },
'https://community.algolia.com/instantsearch.js/react/widgets/RangeSlider.html'
)
);
});
/***/ }),
/* 365 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectRefinementList = __webpack_require__(227);
var _connectRefinementList2 = _interopRequireDefault(_connectRefinementList);
var _RefinementList = __webpack_require__(389);
var _RefinementList2 = _interopRequireDefault(_RefinementList);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The RefinementList component displays a list that let the end user choose multiple values for a specific facet.
* @name RefinementList
* @kind widget
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of displayed items
* @propType {number} [limitMax=20] - the maximum number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} [defaultRefinement] - the values of the items selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-RefinementList__root - the root of the component
* @themeKey ais-RefinementList__items - the container of all items in the list
* @themeKey ais-RefinementList__itemSelected - the selected list item
* @themeKey ais-RefinementList__itemCheckbox - the item checkbox
* @themeKey ais-RefinementList__itemCheckboxSelected - the selected item checkbox
* @themeKey ais-RefinementList__itemLabel - the item label
* @themeKey ais-RefinementList__itemLabelSelected - the selected item label
* @themeKey RefinementList__itemCount - the item count
* @themeKey RefinementList__itemCountSelected - the selected item count
* @themeKey ais-RefinementList__showMore - the button that let the user toggle more results
* @themeKey ais-RefinementList__noRefinement - present when there is no refinement
* @themeKey ais-RefinementList__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded
* @translationkey noResults - The label of the no results text when no search for facet values results are found.
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @example
* import React from 'react';
*
* import {RefinementList, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <RefinementList attributeName="colors" />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectRefinementList2.default)(_RefinementList2.default);
/***/ }),
/* 366 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectScrollTo = __webpack_require__(228);
var _connectScrollTo2 = _interopRequireDefault(_connectScrollTo);
var _ScrollTo = __webpack_require__(390);
var _ScrollTo2 = _interopRequireDefault(_ScrollTo);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The ScrollTo component will made the page scroll to the component wrapped by it when one of the
* [search state](guide/Search_state.html) prop is updated. By default when the page number changes,
* the scroll goes to the wrapped component.
*
* @name ScrollTo
* @kind widget
* @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes.
* @example
* import React from 'react';
*
* import {ScrollTo, Hits, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <ScrollTo>
* <Hits />
* </ScrollTo>
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectScrollTo2.default)(_ScrollTo2.default);
/***/ }),
/* 367 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectSearchBox = __webpack_require__(229);
var _connectSearchBox2 = _interopRequireDefault(_connectSearchBox);
var _SearchBox = __webpack_require__(344);
var _SearchBox2 = _interopRequireDefault(_SearchBox);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The SearchBox component displays a search box that lets the user search for a specific query.
* @name SearchBox
* @kind widget
* @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes.
* @propType {boolean} [autoFocus=false] - Should the search box be focused on render?
* @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused.
* @themeKey ais-SearchBox__root - the root of the component
* @themeKey ais-SearchBox__wrapper - the search box wrapper
* @themeKey ais-SearchBox__input - the search box input
* @themeKey ais-SearchBox__submit - the submit button
* @themeKey ais-SearchBox__reset - the reset button
* @translationkey submit - The submit button label
* @translationkey reset - The reset button label
* @translationkey submitTitle - The submit button title
* @translationkey resetTitle - The reset button title
* @translationkey placeholder - The label of the input placeholder
* @example
* import React from 'react';
*
* import {SearchBox, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SearchBox />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectSearchBox2.default)(_SearchBox2.default);
/***/ }),
/* 368 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectHighlight = __webpack_require__(210);
var _connectHighlight2 = _interopRequireDefault(_connectHighlight);
var _Snippet = __webpack_require__(391);
var _Snippet2 = _interopRequireDefault(_Snippet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Renders any attribute from an hit into its highlighted snippet form when relevant.
*
* Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide.
* @name Snippet
* @kind widget
* @propType {string} attributeName - the location of the highlighted snippet attribute in the hit
* @propType {object} hit - the hit object containing the highlighted snippet attribute
* @example
* import React from 'react';
*
* import {InstantSearch, connectHits, Snippet} from 'InstantSearch';
*
* const CustomHits = connectHits(hits => {
* return hits.map((hit) => <p><Snippet attributeName="description" hit={hit}/></p>);
* });
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CustomHits />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectHighlight2.default)(_Snippet2.default);
/***/ }),
/* 369 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectSortBy = __webpack_require__(230);
var _connectSortBy2 = _interopRequireDefault(_connectSortBy);
var _SortBy = __webpack_require__(392);
var _SortBy2 = _interopRequireDefault(_SortBy);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The SortBy component displays a list of indexes allowing a user to change the hits are sorting.
* @name SortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind widget
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {string} defaultRefinement - The default selected index.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-SortBy__root - the root of the component
* @example
* import React from 'react';
*
* import {SortBy, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SortBy
* items={[
* {value: 'ikea', label: 'Featured'},
* {value: 'ikea_price_asc', label: 'Price asc.'},
* {value: 'ikea_price_desc', label: 'Price desc.'},
* ]}
* defaultRefinement="ikea"
* />
* </InstantSearch>
* );
* } */
exports.default = (0, _connectSortBy2.default)(_SortBy2.default);
/***/ }),
/* 370 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectRange = __webpack_require__(114);
var _connectRange2 = _interopRequireDefault(_connectRange);
var _StarRating = __webpack_require__(393);
var _StarRating2 = _interopRequireDefault(_StarRating);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* StarRating lets the user refine search results by clicking on stars.
*
* The stars are based on the selected `attributeName`.
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @name StarRating
* @kind widget
* @propType {string} attributeName - the name of the attribute in the record
* @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating.
* @themeKey ais-StarRating__root - The root component of the widget
* @themeKey ais-StarRating__ratingLink - The item link
* @themeKey ais-StarRating__ratingLinkSelected - The selected link item
* @themeKey ais-StarRating__ratingLinkDisabled - The disabled link item
* @themeKey ais-StarRating__ratingIcon - The rating icon
* @themeKey ais-StarRating__ratingIconSelected - The selected rating icon
* @themeKey ais-StarRating__ratingIconDisabled - The disabled rating icon
* @themeKey ais-StarRating__ratingIconEmpty - The rating empty icon
* @themeKey ais-StarRating__ratingIconEmptySelected - The selected rating empty icon
* @themeKey ais-StarRating__ratingIconEmptyDisabled - The disabled rating empty icon
* @themeKey ais-StarRating__ratingLabel - The link label
* @themeKey ais-StarRating__ratingLabelSelected - The selected link label
* @themeKey ais-StarRating__ratingLabelDisabled - The disabled link label
* @themeKey ais-StarRating__ratingCount - The link count
* @themeKey ais-StarRating__ratingCountSelected - The selected link count
* @themeKey ais-StarRating__ratingCountDisabled - The disabled link count
* @themeKey ais-StarRating__noRefinement - present when there is no refinement
* @translationKey ratingLabel - Label value for the rating link
* @example
* import React from 'react';
*
* import {StarRating, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <StarRating attributeName="rating" />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectRange2.default)(_StarRating2.default);
/***/ }),
/* 371 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectStats = __webpack_require__(231);
var _connectStats2 = _interopRequireDefault(_connectStats);
var _Stats = __webpack_require__(394);
var _Stats2 = _interopRequireDefault(_Stats);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server).
* @name Stats
* @kind widget
* @themeKey ais-Stats__root - the root of the component
* @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time.
* @example
* import React from 'react';
*
* import {Stats, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Stats />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectStats2.default)(_Stats2.default);
/***/ }),
/* 372 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectToggle = __webpack_require__(232);
var _connectToggle2 = _interopRequireDefault(_connectToggle);
var _Toggle = __webpack_require__(395);
var _Toggle2 = _interopRequireDefault(_Toggle);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Toggle provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization.
* @name Toggle
* @kind widget
* @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attributeName` when checked.
* @propType {boolean} [defaultChecked=false] - Default state of the widget. Should the toggle be checked by default?
* @themeKey ais-Toggle__root - the root of the component
* @themeKey ais-Toggle__checkbox - the toggle checkbox
* @themeKey ais-Toggle__label - the toggle label
* @example
* import React from 'react';
*
* import {Toggle, InstantSearch} from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Toggle attributeName="materials"
* label="Made with solid pine"
* value={'Solid pine'}
* />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _connectToggle2.default)(_Toggle2.default);
/***/ }),
/* 373 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var AlgoliaSearch = __webpack_require__(403);
var createAlgoliasearch = __webpack_require__(407);
module.exports = createAlgoliasearch(AlgoliaSearch);
/***/ }),
/* 374 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('ClearAll');
var ClearAll = function (_Component) {
_inherits(ClearAll, _Component);
function ClearAll() {
_classCallCheck(this, ClearAll);
return _possibleConstructorReturn(this, (ClearAll.__proto__ || Object.getPrototypeOf(ClearAll)).apply(this, arguments));
}
_createClass(ClearAll, [{
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
items = _props.items,
refine = _props.refine,
query = _props.query;
var isDisabled = items.length === 0 && (!query || query === '');
if (isDisabled) {
return _react2.default.createElement(
'button',
_extends({}, cx('root'), { disabled: true }),
translate('reset')
);
}
return _react2.default.createElement(
'button',
_extends({}, cx('root'), {
onClick: refine.bind(null, items)
}),
translate('reset')
);
}
}]);
return ClearAll;
}(_react.Component);
ClearAll.propTypes = {
translate: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.object).isRequired,
refine: _react.PropTypes.func.isRequired,
query: _react.PropTypes.string
};
exports.default = (0, _translatable2.default)({
reset: 'Clear all filters'
})(ClearAll);
/***/ }),
/* 375 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {
return null;
};
/***/ }),
/* 376 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('CurrentRefinements');
var CurrentRefinements = function (_Component) {
_inherits(CurrentRefinements, _Component);
function CurrentRefinements() {
_classCallCheck(this, CurrentRefinements);
return _possibleConstructorReturn(this, (CurrentRefinements.__proto__ || Object.getPrototypeOf(CurrentRefinements)).apply(this, arguments));
}
_createClass(CurrentRefinements, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
items = _props.items,
refine = _props.refine,
canRefine = _props.canRefine;
return _react2.default.createElement(
'div',
cx('root', !canRefine && 'noRefinement'),
_react2.default.createElement(
'div',
cx('items'),
items.map(function (item) {
return _react2.default.createElement(
'div',
_extends({
key: item.label
}, cx('item', item.items && 'itemParent')),
_react2.default.createElement(
'span',
cx('itemLabel'),
item.label
),
item.items ? item.items.map(function (nestedItem) {
return _react2.default.createElement(
'div',
_extends({
key: nestedItem.label
}, cx('item')),
_react2.default.createElement(
'span',
cx('itemLabel'),
nestedItem.label
),
_react2.default.createElement(
'button',
_extends({}, cx('itemClear'), {
onClick: refine.bind(null, nestedItem.value)
}),
translate('clearFilter', nestedItem)
)
);
}) : _react2.default.createElement(
'button',
_extends({}, cx('itemClear'), {
onClick: refine.bind(null, item.value)
}),
translate('clearFilter', item)
)
);
})
)
);
}
}]);
return CurrentRefinements;
}(_react.Component);
CurrentRefinements.propTypes = {
translate: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string
})).isRequired,
refine: _react.PropTypes.func.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
transformItems: _react.PropTypes.func
};
CurrentRefinements.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
clearFilter: '✕'
})(CurrentRefinements);
/***/ }),
/* 377 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _pick2 = __webpack_require__(113);
var _pick3 = _interopRequireDefault(_pick2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _List = __webpack_require__(211);
var _List2 = _interopRequireDefault(_List);
var _Link = __webpack_require__(234);
var _Link2 = _interopRequireDefault(_Link);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('HierarchicalMenu');
var itemsPropType = _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string.isRequired,
value: _react.PropTypes.string,
count: _react.PropTypes.number.isRequired,
items: function items() {
return itemsPropType.apply(undefined, arguments);
}
}));
var HierarchicalMenu = function (_Component) {
_inherits(HierarchicalMenu, _Component);
function HierarchicalMenu() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, HierarchicalMenu);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props,
createURL = _this$props.createURL,
refine = _this$props.refine;
return _react2.default.createElement(
_Link2.default,
_extends({}, cx('itemLink'), {
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value)
}),
_react2.default.createElement(
'span',
cx('itemLabel'),
item.label
),
' ',
_react2.default.createElement(
'span',
cx('itemCount'),
item.count
)
);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(HierarchicalMenu, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(_List2.default, _extends({
renderItem: this.renderItem,
cx: cx
}, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isEmpty', 'canRefine'])));
}
}]);
return HierarchicalMenu;
}(_react.Component);
HierarchicalMenu.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
createURL: _react.PropTypes.func.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
items: itemsPropType,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
transformItems: _react.PropTypes.func
};
HierarchicalMenu.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
}
})(HierarchicalMenu);
/***/ }),
/* 378 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = Highlight;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Highlighter = __webpack_require__(343);
var _Highlighter2 = _interopRequireDefault(_Highlighter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Highlight(props) {
return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_highlightResult' }, props));
}
Highlight.propTypes = {
hit: _react2.default.PropTypes.object.isRequired,
attributeName: _react2.default.PropTypes.string.isRequired,
highlight: _react2.default.PropTypes.func.isRequired
};
/***/ }),
/* 379 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Hits');
var Hits = function (_Component) {
_inherits(Hits, _Component);
function Hits() {
_classCallCheck(this, Hits);
return _possibleConstructorReturn(this, (Hits.__proto__ || Object.getPrototypeOf(Hits)).apply(this, arguments));
}
_createClass(Hits, [{
key: 'render',
value: function render() {
var _props = this.props,
ItemComponent = _props.hitComponent,
hits = _props.hits;
return _react2.default.createElement(
'div',
cx('root'),
hits.map(function (hit) {
return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit });
})
);
}
}]);
return Hits;
}(_react.Component);
Hits.propTypes = {
hits: _react.PropTypes.array,
hitComponent: _react.PropTypes.func.isRequired
};
Hits.defaultProps = {
hitComponent: function hitComponent(hit) {
return _react2.default.createElement(
'div',
{
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px'
}
},
JSON.stringify(hit).slice(0, 100),
'...'
);
}
};
exports.default = Hits;
/***/ }),
/* 380 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Select = __webpack_require__(345);
var _Select2 = _interopRequireDefault(_Select);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('HitsPerPage');
var HitsPerPage = function (_Component) {
_inherits(HitsPerPage, _Component);
function HitsPerPage() {
_classCallCheck(this, HitsPerPage);
return _possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments));
}
_createClass(HitsPerPage, [{
key: 'render',
value: function render() {
var _props = this.props,
currentRefinement = _props.currentRefinement,
refine = _props.refine,
items = _props.items;
return _react2.default.createElement(_Select2.default, {
onSelect: refine,
selectedItem: currentRefinement,
items: items,
cx: cx
});
}
}]);
return HitsPerPage;
}(_react.Component);
HitsPerPage.propTypes = {
refine: _react.PropTypes.func.isRequired,
currentRefinement: _react.PropTypes.number.isRequired,
transformItems: _react.PropTypes.func,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
/**
* Number of hits to display.
*/
value: _react.PropTypes.number.isRequired,
/**
* Label to display on the option.
*/
label: _react.PropTypes.string
}))
};
exports.default = HitsPerPage;
/***/ }),
/* 381 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('InfiniteHits');
var InfiniteHits = function (_Component) {
_inherits(InfiniteHits, _Component);
function InfiniteHits() {
_classCallCheck(this, InfiniteHits);
return _possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments));
}
_createClass(InfiniteHits, [{
key: 'render',
value: function render() {
var _props = this.props,
ItemComponent = _props.hitComponent,
hits = _props.hits,
hasMore = _props.hasMore,
refine = _props.refine;
var renderedHits = hits.map(function (hit) {
return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit });
});
var loadMoreButton = hasMore ? _react2.default.createElement(
'button',
_extends({}, cx('loadMore'), { onClick: function onClick() {
return refine();
} }),
'Load more'
) : _react2.default.createElement(
'button',
_extends({}, cx('loadMore'), { disabled: true }),
'Load more'
);
return _react2.default.createElement(
'div',
cx('root'),
renderedHits,
loadMoreButton
);
}
}]);
return InfiniteHits;
}(_react.Component);
InfiniteHits.propTypes = {
hits: _react.PropTypes.array,
hitComponent: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]).isRequired,
hasMore: _react.PropTypes.bool.isRequired,
refine: _react.PropTypes.func.isRequired
};
InfiniteHits.defaultProps = {
hitComponent: function hitComponent(hit) {
return _react2.default.createElement(
'div',
{
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px'
}
},
JSON.stringify(hit).slice(0, 100),
'...'
);
}
};
exports.default = InfiniteHits;
/***/ }),
/* 382 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _has2 = __webpack_require__(74);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Link = __webpack_require__(234);
var _Link2 = _interopRequireDefault(_Link);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var LinkList = function (_Component) {
_inherits(LinkList, _Component);
function LinkList() {
_classCallCheck(this, LinkList);
return _possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments));
}
_createClass(LinkList, [{
key: 'render',
value: function render() {
var _props = this.props,
cx = _props.cx,
createURL = _props.createURL,
items = _props.items,
selectedItem = _props.selectedItem,
onSelect = _props.onSelect,
canRefine = _props.canRefine;
return _react2.default.createElement(
'ul',
cx('root', !canRefine && 'noRefinement'),
items.map(function (item) {
return _react2.default.createElement(
'li',
_extends({
key: (0, _has3.default)(item, 'key') ? item.key : item.value
}, cx('item',
// on purpose == following, see
// https://github.com/algolia/instantsearch.js/commit/bfed1f3512e40fb1e9989453582b4a2c2d90e3f2
// eslint-disable-next-line
item.value == selectedItem && !item.disabled && 'itemSelected', item.disabled && 'itemDisabled', item.modifier), {
disabled: item.disabled
}),
item.disabled ? _react2.default.createElement(
'span',
cx('itemLink', 'itemLinkDisabled'),
(0, _has3.default)(item, 'label') ? item.label : item.value
) : _react2.default.createElement(
_Link2.default,
_extends({}, cx('itemLink', item.value === selectedItem && 'itemLinkSelected'), {
'aria-label': item.ariaLabel,
href: createURL(item.value),
onClick: onSelect.bind(null, item.value)
}),
(0, _has3.default)(item, 'label') ? item.label : item.value
)
);
})
);
}
}]);
return LinkList;
}(_react.Component);
LinkList.propTypes = {
cx: _react.PropTypes.func.isRequired,
createURL: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
value: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number, _react.PropTypes.object]).isRequired,
key: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]),
label: _react.PropTypes.node,
modifier: _react.PropTypes.string,
ariaLabel: _react.PropTypes.string,
disabled: _react.PropTypes.bool
})),
selectedItem: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number, _react.PropTypes.object]),
onSelect: _react.PropTypes.func.isRequired,
canRefine: _react.PropTypes.bool.isRequired
};
exports.default = LinkList;
/***/ }),
/* 383 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _pick2 = __webpack_require__(113);
var _pick3 = _interopRequireDefault(_pick2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _List = __webpack_require__(211);
var _List2 = _interopRequireDefault(_List);
var _Link = __webpack_require__(234);
var _Link2 = _interopRequireDefault(_Link);
var _Highlight = __webpack_require__(233);
var _Highlight2 = _interopRequireDefault(_Highlight);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Menu');
var Menu = function (_Component) {
_inherits(Menu, _Component);
function Menu() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Menu);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props,
refine = _this$props.refine,
createURL = _this$props.createURL;
var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label;
return _react2.default.createElement(
_Link2.default,
_extends({}, cx('itemLink', item.isRefined && 'itemLinkSelected'), {
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value)
}),
_react2.default.createElement(
'span',
cx('itemLabel', item.isRefined && 'itemLabelSelected'),
label
),
' ',
_react2.default.createElement(
'span',
cx('itemCount', item.isRefined && 'itemCountSelected'),
item.count
)
);
}, _this.selectItem = function (item) {
_this.props.refine(item.value);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Menu, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(_List2.default, _extends({
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx
}, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine'])));
}
}]);
return Menu;
}(_react.Component);
Menu.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
searchForItems: _react.PropTypes.func.isRequired,
withSearchBox: _react.PropTypes.bool,
createURL: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string.isRequired,
value: _react.PropTypes.string.isRequired,
count: _react.PropTypes.number.isRequired,
isRefined: _react.PropTypes.bool.isRequired
})),
isFromSearch: _react.PropTypes.bool.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
transformItems: _react.PropTypes.func
};
Menu.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
},
noResults: 'No results',
submit: null,
reset: null,
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(Menu);
/***/ }),
/* 384 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _List = __webpack_require__(211);
var _List2 = _interopRequireDefault(_List);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('MultiRange');
var MultiRange = function (_Component) {
_inherits(MultiRange, _Component);
function MultiRange() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, MultiRange);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MultiRange.__proto__ || Object.getPrototypeOf(MultiRange)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props,
refine = _this$props.refine,
translate = _this$props.translate;
var label = item.value === '' ? translate('all') : item.label;
return _react2.default.createElement(
'label',
cx(item.value === '' && 'itemAll'),
_react2.default.createElement('input', _extends({}, cx('itemRadio', item.isRefined && 'itemRadioSelected'), {
type: 'radio',
checked: item.isRefined,
disabled: item.noRefinement,
onChange: refine.bind(null, item.value)
})),
_react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')),
_react2.default.createElement(
'span',
cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'),
label
)
);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(MultiRange, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
items = _props.items,
canRefine = _props.canRefine;
return _react2.default.createElement(_List2.default, {
renderItem: this.renderItem,
showMore: false,
canRefine: canRefine,
cx: cx,
items: items.map(function (item) {
return _extends({}, item, { key: item.value });
})
});
}
}]);
return MultiRange;
}(_react.Component);
MultiRange.propTypes = {
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.node.isRequired,
value: _react.PropTypes.string.isRequired,
isRefined: _react.PropTypes.bool.isRequired,
noRefinement: _react.PropTypes.bool.isRequired
})).isRequired,
refine: _react.PropTypes.func.isRequired,
transformItems: _react.PropTypes.func,
canRefine: _react.PropTypes.bool.isRequired,
translate: _react.PropTypes.func.isRequired
};
MultiRange.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
all: 'All'
})(MultiRange);
/***/ }),
/* 385 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _range2 = __webpack_require__(420);
var _range3 = _interopRequireDefault(_range2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(54);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _LinkList = __webpack_require__(382);
var _LinkList2 = _interopRequireDefault(_LinkList);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Pagination');
function getPagesDisplayedCount(padding, total) {
return Math.min(2 * padding + 1, total);
}
function calculatePaddingLeft(current, padding, total, totalDisplayedPages) {
if (current <= padding) {
return current;
}
if (current >= total - padding) {
return totalDisplayedPages - (total - current);
}
return padding;
}
function getPages(page, total, padding) {
var totalDisplayedPages = getPagesDisplayedCount(padding, total);
if (totalDisplayedPages === total) return (0, _range3.default)(1, total + 1);
var paddingLeft = calculatePaddingLeft(page, padding, total, totalDisplayedPages);
var paddingRight = totalDisplayedPages - paddingLeft;
var first = page - paddingLeft;
var last = page + paddingRight;
return (0, _range3.default)(first + 1, last + 1);
}
var Pagination = function (_Component) {
_inherits(Pagination, _Component);
function Pagination() {
_classCallCheck(this, Pagination);
return _possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments));
}
_createClass(Pagination, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'getItem',
value: function getItem(modifier, translationKey, value) {
var _props = this.props,
nbPages = _props.nbPages,
maxPages = _props.maxPages,
translate = _props.translate;
return {
key: modifier + '.' + value,
modifier: modifier,
disabled: value < 1 || value >= Math.min(maxPages, nbPages),
label: translate(translationKey, value),
value: value,
ariaLabel: translate('aria' + (0, _utils.capitalize)(translationKey), value)
};
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props,
nbPages = _props2.nbPages,
maxPages = _props2.maxPages,
currentRefinement = _props2.currentRefinement,
pagesPadding = _props2.pagesPadding,
showFirst = _props2.showFirst,
showPrevious = _props2.showPrevious,
showNext = _props2.showNext,
showLast = _props2.showLast,
refine = _props2.refine,
createURL = _props2.createURL,
translate = _props2.translate,
ListComponent = _props2.listComponent,
otherProps = _objectWithoutProperties(_props2, ['nbPages', 'maxPages', 'currentRefinement', 'pagesPadding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'translate', 'listComponent']);
var totalPages = Math.min(nbPages, maxPages);
var lastPage = totalPages;
var items = [];
if (showFirst) {
items.push({
key: 'first',
modifier: 'itemFirst',
disabled: currentRefinement === 1,
label: translate('first'),
value: 1,
ariaLabel: translate('ariaFirst')
});
}
if (showPrevious) {
items.push({
key: 'previous',
modifier: 'itemPrevious',
disabled: currentRefinement === 1,
label: translate('previous'),
value: currentRefinement - 1,
ariaLabel: translate('ariaPrevious')
});
}
var samePage = {
valueOf: function valueOf() {
return currentRefinement;
},
isSamePage: true
};
items = items.concat(getPages(currentRefinement, totalPages, pagesPadding).map(function (value) {
return {
key: value,
modifier: 'itemPage',
label: translate('page', value),
value: value === currentRefinement ? samePage : value,
ariaLabel: translate('ariaPage', value)
};
}));
if (showNext) {
items.push({
key: 'next',
modifier: 'itemNext',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('next'),
value: currentRefinement + 1,
ariaLabel: translate('ariaNext')
});
}
if (showLast) {
items.push({
key: 'last',
modifier: 'itemLast',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('last'),
value: lastPage,
ariaLabel: translate('ariaLast')
});
}
return _react2.default.createElement(ListComponent, _extends({}, otherProps, {
cx: cx,
items: items,
selectedItem: currentRefinement,
onSelect: refine,
createURL: createURL
}));
}
}]);
return Pagination;
}(_react.Component);
Pagination.propTypes = {
nbPages: _react.PropTypes.number.isRequired,
currentRefinement: _react.PropTypes.number.isRequired,
refine: _react.PropTypes.func.isRequired,
createURL: _react.PropTypes.func.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
translate: _react.PropTypes.func.isRequired,
listComponent: _react.PropTypes.func,
showFirst: _react.PropTypes.bool,
showPrevious: _react.PropTypes.bool,
showNext: _react.PropTypes.bool,
showLast: _react.PropTypes.bool,
pagesPadding: _react.PropTypes.number,
maxPages: _react.PropTypes.number
};
Pagination.defaultProps = {
listComponent: _LinkList2.default,
showFirst: true,
showPrevious: true,
showNext: true,
showLast: false,
pagesPadding: 3,
maxPages: Infinity
};
Pagination.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
previous: '‹',
next: '›',
first: '«',
last: '»',
page: function page(currentRefinement) {
return currentRefinement.toString();
},
ariaPrevious: 'Previous page',
ariaNext: 'Next page',
ariaFirst: 'First page',
ariaLast: 'Last page',
ariaPage: function ariaPage(currentRefinement) {
return 'Page ' + currentRefinement.toString();
}
})(Pagination);
/***/ }),
/* 386 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Panel');
var Panel = function (_Component) {
_inherits(Panel, _Component);
_createClass(Panel, [{
key: 'getChildContext',
value: function getChildContext() {
return { canRefine: this.canRefine };
}
}]);
function Panel(props) {
_classCallCheck(this, Panel);
var _this = _possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props));
_this.state = { canRefine: true };
_this.canRefine = function (canRefine) {
_this.setState({ canRefine: canRefine });
};
return _this;
}
_createClass(Panel, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
cx('root', !this.state.canRefine && 'noRefinement'),
_react2.default.createElement(
'h5',
cx('title'),
this.props.title
),
this.props.children
);
}
}]);
return Panel;
}(_react.Component);
Panel.propTypes = {
title: _react.PropTypes.string.isRequired,
children: _react.PropTypes.node
};
Panel.childContextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = Panel;
/***/ }),
/* 387 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('PoweredBy');
/* eslint-disable max-len */
var AlgoliaLogo = function AlgoliaLogo() {
return _react2.default.createElement(
'svg',
{ xmlns: 'http://www.w3.org/2000/svg', baseProfile: 'basic', viewBox: '0 0 1366 362' },
_react2.default.createElement(
'linearGradient',
{ id: 'g', x1: '428.258', x2: '434.145', y1: '404.15', y2: '409.85', gradientUnits: 'userSpaceOnUse', gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)' },
_react2.default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }),
_react2.default.createElement('stop', { offset: '1', stopColor: '#3369E7' })
),
_react2.default.createElement('path', { d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z', fill: 'url(#g)' }),
_react2.default.createElement('path', { d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z', fill: '#FFFFFF' }),
_react2.default.createElement('path', { d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-10-3-16.7-3c-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1s19.5-2.6 30.3-2.6zm3.3 141.9c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18 5.9 3.6 13.7 5.3 23.6 5.3zM512.9 103c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4 5.3 5.8 8.9 13.5 11.1 21.7 2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6-12.2 1.8-25.9 2.7-41.1 2.7-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8 4.7.5 9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2-4.4-1.7-10-3-16.7-3-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1 9.4-1.8 19.5-2.6 30.3-2.6zm3.4 142c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z', fill: '#182359' })
);
};
/* eslint-enable max-len */
var PoweredBy = function (_Component) {
_inherits(PoweredBy, _Component);
function PoweredBy() {
_classCallCheck(this, PoweredBy);
return _possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments));
}
_createClass(PoweredBy, [{
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
url = _props.url;
return _react2.default.createElement(
'div',
cx('root'),
_react2.default.createElement(
'span',
cx('searchBy'),
translate('searchBy'),
' '
),
_react2.default.createElement(
'a',
_extends({ href: url, target: '_blank' }, cx('algoliaLink')),
_react2.default.createElement(AlgoliaLogo, null)
)
);
}
}]);
return PoweredBy;
}(_react.Component);
PoweredBy.propTypes = {
url: _react.PropTypes.string.isRequired,
translate: _react.PropTypes.func.isRequired
};
exports.default = (0, _translatable2.default)({
searchBy: 'Search by'
})(PoweredBy);
/***/ }),
/* 388 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isNaN2 = __webpack_require__(216);
var _isNaN3 = _interopRequireDefault(_isNaN2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('RangeInput');
var RangeInput = function (_Component) {
_inherits(RangeInput, _Component);
function RangeInput(props) {
_classCallCheck(this, RangeInput);
var _this = _possibleConstructorReturn(this, (RangeInput.__proto__ || Object.getPrototypeOf(RangeInput)).call(this, props));
_this.onSubmit = function (e) {
e.preventDefault();
e.stopPropagation();
if (!(0, _isNaN3.default)(parseFloat(_this.state.from, 10)) && !(0, _isNaN3.default)(parseFloat(_this.state.to, 10))) {
_this.props.refine({ min: _this.state.from, max: _this.state.to });
}
};
_this.state = _this.props.canRefine ? { from: props.currentRefinement.min, to: props.currentRefinement.max } : { from: '', to: '' };
return _this;
}
_createClass(RangeInput, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (nextProps.canRefine) {
this.setState({ from: nextProps.currentRefinement.min, to: nextProps.currentRefinement.max });
}
if (this.context.canRefine) this.context.canRefine(nextProps.canRefine);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props,
translate = _props.translate,
canRefine = _props.canRefine;
return _react2.default.createElement(
'form',
_extends({}, cx('root', !canRefine && 'noRefinement'), { onSubmit: this.onSubmit }),
_react2.default.createElement(
'fieldset',
_extends({ disabled: !canRefine }, cx('fieldset')),
_react2.default.createElement(
'label',
cx('labelMin'),
_react2.default.createElement('input', _extends({}, cx('inputMin'), {
type: 'number', value: this.state.from, onChange: function onChange(e) {
return _this2.setState({ from: e.target.value });
}
}))
),
_react2.default.createElement(
'span',
cx('separator'),
translate('separator')
),
_react2.default.createElement(
'label',
cx('labelMax'),
_react2.default.createElement('input', _extends({}, cx('inputMax'), {
type: 'number', value: this.state.to, onChange: function onChange(e) {
return _this2.setState({ to: e.target.value });
}
}))
),
_react2.default.createElement(
'button',
_extends({}, cx('submit'), { type: 'submit' }),
translate('submit')
)
)
);
}
}]);
return RangeInput;
}(_react.Component);
RangeInput.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
min: _react.PropTypes.number,
max: _react.PropTypes.number,
currentRefinement: _react.PropTypes.shape({
min: _react.PropTypes.number,
max: _react.PropTypes.number
}),
canRefine: _react.PropTypes.bool.isRequired
};
RangeInput.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
submit: 'ok',
separator: 'to'
})(RangeInput);
/***/ }),
/* 389 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _pick2 = __webpack_require__(113);
var _pick3 = _interopRequireDefault(_pick2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _List = __webpack_require__(211);
var _List2 = _interopRequireDefault(_List);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
var _Highlight = __webpack_require__(233);
var _Highlight2 = _interopRequireDefault(_Highlight);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('RefinementList');
var RefinementList = function (_Component) {
_inherits(RefinementList, _Component);
function RefinementList(props) {
_classCallCheck(this, RefinementList);
var _this = _possibleConstructorReturn(this, (RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call(this, props));
_this.selectItem = function (item) {
_this.props.refine(item.value);
};
_this.renderItem = function (item) {
var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label;
return _react2.default.createElement(
'label',
null,
_react2.default.createElement('input', _extends({}, cx('itemCheckbox', item.isRefined && 'itemCheckboxSelected'), {
type: 'checkbox',
checked: item.isRefined,
onChange: function onChange() {
return _this.selectItem(item);
}
})),
_react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')),
_react2.default.createElement(
'span',
cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'),
label
),
' ',
_react2.default.createElement(
'span',
cx('itemCount', item.isRefined && 'itemCountSelected'),
item.count
)
);
};
_this.state = { query: '' };
return _this;
}
_createClass(RefinementList, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(_List2.default, _extends({
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx
}, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine'])))
);
}
}]);
return RefinementList;
}(_react.Component);
RefinementList.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
searchForItems: _react.PropTypes.func.isRequired,
withSearchBox: _react.PropTypes.bool,
createURL: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string.isRequired,
value: _react.PropTypes.arrayOf(_react.PropTypes.string).isRequired,
count: _react.PropTypes.number.isRequired,
isRefined: _react.PropTypes.bool.isRequired
})),
isFromSearch: _react.PropTypes.bool.isRequired,
canRefine: _react.PropTypes.bool.isRequired,
showMore: _react.PropTypes.bool,
limitMin: _react.PropTypes.number,
limitMax: _react.PropTypes.number,
transformItems: _react.PropTypes.func
};
RefinementList.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
},
noResults: 'No results',
submit: null,
reset: null,
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(RefinementList);
/***/ }),
/* 390 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _reactDom = __webpack_require__(424);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ScrollTo = function (_Component) {
_inherits(ScrollTo, _Component);
function ScrollTo() {
_classCallCheck(this, ScrollTo);
return _possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments));
}
_createClass(ScrollTo, [{
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
var value = this.props.value;
if (value !== prevProps.value) {
var el = (0, _reactDom.findDOMNode)(this);
el.scrollIntoView();
}
}
}, {
key: 'render',
value: function render() {
return _react.Children.only(this.props.children);
}
}]);
return ScrollTo;
}(_react.Component);
ScrollTo.propTypes = {
value: _react.PropTypes.any,
children: _react.PropTypes.node
};
exports.default = ScrollTo;
/***/ }),
/* 391 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = Snippet;
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Highlighter = __webpack_require__(343);
var _Highlighter2 = _interopRequireDefault(_Highlighter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Snippet(props) {
return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_snippetResult' }, props));
}
Snippet.propTypes = {
hit: _react2.default.PropTypes.object.isRequired,
attributeName: _react2.default.PropTypes.string.isRequired,
highlight: _react2.default.PropTypes.func.isRequired
};
/***/ }),
/* 392 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _Select = __webpack_require__(345);
var _Select2 = _interopRequireDefault(_Select);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('SortBy');
var SortBy = function (_Component) {
_inherits(SortBy, _Component);
function SortBy() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, SortBy);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = SortBy.__proto__ || Object.getPrototypeOf(SortBy)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) {
_this.props.refine(e.target.value);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(SortBy, [{
key: 'render',
value: function render() {
var _props = this.props,
refine = _props.refine,
items = _props.items,
currentRefinement = _props.currentRefinement;
return _react2.default.createElement(_Select2.default, {
cx: cx,
selectedItem: currentRefinement,
onSelect: refine,
items: items
});
}
}]);
return SortBy;
}(_react.Component);
SortBy.propTypes = {
refine: _react.PropTypes.func.isRequired,
items: _react.PropTypes.arrayOf(_react.PropTypes.shape({
label: _react.PropTypes.string,
value: _react.PropTypes.string.isRequired
})).isRequired,
currentRefinement: _react.PropTypes.string.isRequired,
transformItems: _react.PropTypes.func
};
exports.default = SortBy;
/***/ }),
/* 393 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEmpty2 = __webpack_require__(7);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('StarRating');
var StarRating = function (_Component) {
_inherits(StarRating, _Component);
function StarRating() {
_classCallCheck(this, StarRating);
return _possibleConstructorReturn(this, (StarRating.__proto__ || Object.getPrototypeOf(StarRating)).apply(this, arguments));
}
_createClass(StarRating, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'onClick',
value: function onClick(min, max, e) {
e.preventDefault();
e.stopPropagation();
if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) {
this.props.refine({ min: this.props.min, max: this.props.max });
} else {
this.props.refine({ min: min, max: max });
}
}
}, {
key: 'buildItem',
value: function buildItem(_ref) {
var max = _ref.max,
lowerBound = _ref.lowerBound,
count = _ref.count,
translate = _ref.translate,
createURL = _ref.createURL,
isLastSelectableItem = _ref.isLastSelectableItem;
var disabled = !count;
var isCurrentMinLower = this.props.currentRefinement.min < lowerBound;
var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max;
var icons = [];
for (var icon = 0; icon < max; icon++) {
var iconTheme = icon >= lowerBound ? 'ratingIconEmpty' : 'ratingIcon';
icons.push(_react2.default.createElement('span', _extends({
key: icon
}, cx(iconTheme, selected && iconTheme + 'Selected', disabled && iconTheme + 'Disabled'))));
}
// The last item of the list (the default item), should not
// be clickable if it is selected.
var isLastAndSelect = isLastSelectableItem && selected;
var StarsWrapper = isLastAndSelect ? 'div' : 'a';
var onClickHandler = isLastAndSelect ? {} : {
href: createURL({ min: lowerBound, max: max }),
onClick: this.onClick.bind(this, lowerBound, max)
};
return _react2.default.createElement(
StarsWrapper,
_extends({}, cx('ratingLink', selected && 'ratingLinkSelected', disabled && 'ratingLinkDisabled'), {
disabled: disabled,
key: lowerBound
}, onClickHandler),
icons,
_react2.default.createElement(
'span',
cx('ratingLabel', selected && 'ratingLabelSelected', disabled && 'ratingLabelDisabled'),
translate('ratingLabel')
),
_react2.default.createElement(
'span',
null,
' '
),
_react2.default.createElement(
'span',
cx('ratingCount', selected && 'ratingCountSelected', disabled && 'ratingCountDisabled'),
count
)
);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props,
translate = _props.translate,
refine = _props.refine,
min = _props.min,
max = _props.max,
count = _props.count,
createURL = _props.createURL,
canRefine = _props.canRefine;
var items = [];
var _loop = function _loop(i) {
var hasCount = !(0, _isEmpty3.default)(count.filter(function (item) {
return Number(item.value) === i;
}));
var lastSelectableItem = count.reduce(function (acc, item) {
return item.value < acc.value || !acc.value && hasCount ? item : acc;
}, {});
var itemCount = count.reduce(function (acc, item) {
return item.value >= i && hasCount ? acc + item.count : acc;
}, 0);
items.push(_this2.buildItem({
lowerBound: i,
max: max,
refine: refine,
count: itemCount,
translate: translate,
createURL: createURL,
isLastSelectableItem: i === Number(lastSelectableItem.value)
}));
};
for (var i = max; i >= min; i--) {
_loop(i);
}
return _react2.default.createElement(
'div',
cx('root', !canRefine && 'noRefinement'),
items
);
}
}]);
return StarRating;
}(_react.Component);
StarRating.propTypes = {
translate: _react.PropTypes.func.isRequired,
refine: _react.PropTypes.func.isRequired,
createURL: _react.PropTypes.func.isRequired,
min: _react.PropTypes.number,
max: _react.PropTypes.number,
currentRefinement: _react.PropTypes.shape({
min: _react.PropTypes.number,
max: _react.PropTypes.number
}),
count: _react.PropTypes.arrayOf(_react.PropTypes.shape({
value: _react.PropTypes.string,
count: _react.PropTypes.number
})),
canRefine: _react.PropTypes.bool.isRequired
};
StarRating.contextTypes = {
canRefine: _react.PropTypes.func
};
exports.default = (0, _translatable2.default)({
ratingLabel: ' & Up'
})(StarRating);
/***/ }),
/* 394 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _translatable = __webpack_require__(34);
var _translatable2 = _interopRequireDefault(_translatable);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Stats');
var Stats = function (_Component) {
_inherits(Stats, _Component);
function Stats() {
_classCallCheck(this, Stats);
return _possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments));
}
_createClass(Stats, [{
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
nbHits = _props.nbHits,
processingTimeMS = _props.processingTimeMS;
return _react2.default.createElement(
'span',
cx('root'),
translate('stats', nbHits, processingTimeMS)
);
}
}]);
return Stats;
}(_react.Component);
Stats.propTypes = {
translate: _react.PropTypes.func.isRequired,
nbHits: _react.PropTypes.number.isRequired,
processingTimeMS: _react.PropTypes.number.isRequired
};
exports.default = (0, _translatable2.default)({
stats: function stats(n, ms) {
return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms';
}
})(Stats);
/***/ }),
/* 395 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _classNames = __webpack_require__(14);
var _classNames2 = _interopRequireDefault(_classNames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var cx = (0, _classNames2.default)('Toggle');
var Toggle = function (_Component) {
_inherits(Toggle, _Component);
function Toggle() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Toggle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Toggle.__proto__ || Object.getPrototypeOf(Toggle)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) {
_this.props.refine(e.target.checked);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Toggle, [{
key: 'render',
value: function render() {
var _props = this.props,
currentRefinement = _props.currentRefinement,
label = _props.label;
return _react2.default.createElement(
'label',
cx('root'),
_react2.default.createElement('input', _extends({}, cx('checkbox'), {
type: 'checkbox',
checked: currentRefinement,
onChange: this.onChange
})),
_react2.default.createElement(
'span',
cx('label'),
label
)
);
}
}]);
return Toggle;
}(_react.Component);
Toggle.propTypes = {
currentRefinement: _react.PropTypes.bool.isRequired,
refine: _react.PropTypes.func.isRequired,
label: _react.PropTypes.string.isRequired
};
exports.default = Toggle;
/***/ }),
/* 396 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(0);
var _react2 = _interopRequireDefault(_react);
var _createInstantSearchManager = __webpack_require__(397);
var _createInstantSearchManager2 = _interopRequireDefault(_createInstantSearchManager);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function validateNextProps(props, nextProps) {
if (!props.searchState && nextProps.searchState) {
throw new Error('You can\'t switch <InstantSearch> from being uncontrolled to controlled');
} else if (props.searchState && !nextProps.searchState) {
throw new Error('You can\'t switch <InstantSearch> from being controlled to uncontrolled');
}
}
/* eslint valid-jsdoc: 0 */
/**
* @description
* `<InstantSearch>` is the root component of all React InstantSearch implementations.
* It provides all the connected components (aka widgets) a means to interact
* with the searchState.
* @kind widget
* @requirements You will need to have an Algolia account to be able to use this widget.
* [Create one now](https://www.algolia.com/users/sign_up).
* @propType {string} appId - Your Algolia application id.
* @propType {string} apiKey - Your Algolia search-only API key.
* @propType {string} indexName - Main index in which to search.
* @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html).
* @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html).
* @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html).
* @example
* import {InstantSearch, SearchBox, Hits} from 'react-instantsearch/dom';
*
* export default function Search() {
* return (
* <InstantSearch
* appId="appId"
* apiKey="apiKey"
* indexName="indexName"
* >
* <SearchBox />
* <Hits />
* </InstantSearch>
* );
* }
*/
var InstantSearch = function (_Component) {
_inherits(InstantSearch, _Component);
function InstantSearch(props) {
_classCallCheck(this, InstantSearch);
var _this = _possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props));
_this.isControlled = Boolean(props.searchState);
var initialState = _this.isControlled ? props.searchState : {};
_this.aisManager = (0, _createInstantSearchManager2.default)({
indexName: props.indexName,
searchParameters: props.searchParameters,
algoliaClient: props.algoliaClient,
initialState: initialState
});
return _this;
}
_createClass(InstantSearch, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
validateNextProps(this.props, nextProps);
if (this.props.indexName !== nextProps.indexName) {
this.aisManager.updateIndex(nextProps.indexName);
}
if (this.isControlled) {
this.aisManager.onExternalStateUpdate(nextProps.searchState);
}
}
}, {
key: 'getChildContext',
value: function getChildContext() {
// If not already cached, cache the bound methods so that we can forward them as part
// of the context.
if (!this._aisContextCache) {
this._aisContextCache = {
ais: {
onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this),
createHrefForState: this.createHrefForState.bind(this),
onSearchForFacetValues: this.onSearchForFacetValues.bind(this),
onSearchStateChange: this.onSearchStateChange.bind(this)
}
};
}
return {
ais: _extends({}, this._aisContextCache.ais, {
store: this.aisManager.store,
widgetsManager: this.aisManager.widgetsManager
})
};
}
}, {
key: 'createHrefForState',
value: function createHrefForState(searchState) {
searchState = this.aisManager.transitionState(searchState);
return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#';
}
}, {
key: 'onWidgetsInternalStateUpdate',
value: function onWidgetsInternalStateUpdate(searchState) {
searchState = this.aisManager.transitionState(searchState);
this.onSearchStateChange(searchState);
if (!this.isControlled) {
this.aisManager.onExternalStateUpdate(searchState);
}
}
}, {
key: 'onSearchStateChange',
value: function onSearchStateChange(searchState) {
if (this.props.onSearchStateChange) {
this.props.onSearchStateChange(searchState);
}
}
}, {
key: 'onSearchForFacetValues',
value: function onSearchForFacetValues(searchState) {
this.aisManager.onSearchForFacetValues(searchState);
}
}, {
key: 'getKnownKeys',
value: function getKnownKeys() {
return this.aisManager.getWidgetsIds();
}
}, {
key: 'render',
value: function render() {
var childrenCount = _react.Children.count(this.props.children);
var _props$root = this.props.root,
Root = _props$root.Root,
props = _props$root.props;
if (childrenCount === 0) return null;else return _react2.default.createElement(
Root,
props,
this.props.children
);
}
}]);
return InstantSearch;
}(_react.Component);
InstantSearch.propTypes = {
// @TODO: These props are currently constant.
indexName: _react.PropTypes.string.isRequired,
algoliaClient: _react.PropTypes.object.isRequired,
searchParameters: _react.PropTypes.object,
createURL: _react.PropTypes.func,
searchState: _react.PropTypes.object,
onSearchStateChange: _react.PropTypes.func,
children: _react.PropTypes.node,
root: _react.PropTypes.shape({
Root: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.func]),
props: _react.PropTypes.object
}).isRequired
};
InstantSearch.childContextTypes = {
// @TODO: more precise widgets manager propType
ais: _react.PropTypes.object.isRequired
};
exports.default = InstantSearch;
/***/ }),
/* 397 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(4);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = createInstantSearchManager;
var _algoliasearchHelper = __webpack_require__(213);
var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper);
var _createWidgetsManager = __webpack_require__(399);
var _createWidgetsManager2 = _interopRequireDefault(_createWidgetsManager);
var _createStore = __webpack_require__(398);
var _createStore2 = _interopRequireDefault(_createStore);
var _highlightTags = __webpack_require__(212);
var _highlightTags2 = _interopRequireDefault(_highlightTags);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/
function createInstantSearchManager(_ref) {
var indexName = _ref.indexName,
_ref$initialState = _ref.initialState,
initialState = _ref$initialState === undefined ? {} : _ref$initialState,
algoliaClient = _ref.algoliaClient,
_ref$searchParameters = _ref.searchParameters,
searchParameters = _ref$searchParameters === undefined ? {} : _ref$searchParameters;
var baseSP = new _algoliasearchHelper.SearchParameters(_extends({}, searchParameters, {
index: indexName
}, _highlightTags2.default));
var helper = (0, _algoliasearchHelper2.default)(algoliaClient, indexName, baseSP);
helper.on('result', handleSearchSuccess);
helper.on('error', handleSearchError);
var initialSearchParameters = helper.state;
var widgetsManager = (0, _createWidgetsManager2.default)(onWidgetsUpdate);
var store = (0, _createStore2.default)({
widgets: initialState,
metadata: [],
results: null,
error: null,
searching: false
});
function updateClient(client) {
helper.setClient(client);
search();
}
function getMetadata(state) {
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getMetadata);
}).map(function (widget) {
return widget.getMetadata(state);
});
}
function getSearchParameters() {
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, initialSearchParameters);
}
function search() {
var widgetSearchParameters = getSearchParameters(helper.state);
helper.setState(widgetSearchParameters).search();
}
function handleSearchSuccess(content) {
var nextState = (0, _omit3.default)(_extends({}, store.getState(), {
results: content,
searching: false
}), 'resultsFacetValues');
store.setState(nextState);
}
function handleSearchError(error) {
var nextState = (0, _omit3.default)(_extends({}, store.getState(), {
error: error,
searching: false
}), 'resultsFacetValues');
store.setState(nextState);
}
// Called whenever a widget has been rendered with new props.
function onWidgetsUpdate() {
var metadata = getMetadata(store.getState().widgets);
store.setState(_extends({}, store.getState(), {
metadata: metadata,
searching: true
}));
// Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
}
function transitionState(nextSearchState) {
var searchState = store.getState().widgets;
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.transitionState);
}).reduce(function (res, widget) {
return widget.transitionState(searchState, res);
}, nextSearchState);
}
function onExternalStateUpdate(nextSearchState) {
var metadata = getMetadata(nextSearchState);
store.setState(_extends({}, store.getState(), {
widgets: nextSearchState,
metadata: metadata,
searching: true
}));
search();
}
function onSearchForFacetValues(nextSearchState) {
store.setState(_extends({}, store.getState(), {
searchingForFacetValues: true
}));
helper.searchForFacetValues(nextSearchState.facetName, nextSearchState.query).then(function (content) {
var _extends2;
store.setState(_extends({}, store.getState(), {
resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_extends2 = {}, _defineProperty(_extends2, nextSearchState.facetName, content.facetHits), _defineProperty(_extends2, 'query', nextSearchState.query), _extends2)),
searchingForFacetValues: false
}));
}, function (error) {
store.setState(_extends({}, store.getState(), {
error: error,
searchingForFacetValues: false
}));
}).catch(function (error) {
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(function () {
throw error;
});
});
}
function updateIndex(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
search();
}
function getWidgetsIds() {
return store.getState().metadata.reduce(function (res, meta) {
return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res;
}, []);
}
return {
store: store,
widgetsManager: widgetsManager,
getWidgetsIds: getWidgetsIds,
onExternalStateUpdate: onExternalStateUpdate,
transitionState: transitionState,
onSearchForFacetValues: onSearchForFacetValues,
updateClient: updateClient,
updateIndex: updateIndex
};
}
/***/ }),
/* 398 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createStore;
function createStore(initialState) {
var state = initialState;
var listeners = [];
function dispatch() {
listeners.forEach(function (listener) {
return listener();
});
}
return {
getState: function getState() {
return state;
},
setState: function setState(nextState) {
state = nextState;
dispatch();
},
subscribe: function subscribe(listener) {
listeners.push(listener);
return function unsubcribe() {
listeners.splice(listeners.indexOf(listener), 1);
};
}
};
}
/***/ }),
/* 399 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createWidgetsManager;
var _utils = __webpack_require__(54);
function createWidgetsManager(onWidgetsUpdate) {
var widgets = [];
// Is an update scheduled?
var scheduled = false;
// The state manager's updates need to be batched since more than one
// component can register or unregister widgets during the same tick.
function scheduleUpdate() {
if (scheduled) {
return;
}
scheduled = true;
(0, _utils.defer)(function () {
scheduled = false;
onWidgetsUpdate();
});
}
return {
registerWidget: function registerWidget(widget) {
widgets.push(widget);
scheduleUpdate();
return function unregisterWidget() {
widgets.splice(widgets.indexOf(widget), 1);
scheduleUpdate();
};
},
update: scheduleUpdate,
getWidgets: function getWidgets() {
return widgets;
}
};
}
/***/ }),
/* 400 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.withKeysPropType = exports.stateManagerPropType = exports.configManagerPropType = undefined;
var _react = __webpack_require__(0);
var configManagerPropType = exports.configManagerPropType = _react.PropTypes.shape({
register: _react.PropTypes.func.isRequired,
swap: _react.PropTypes.func.isRequired,
unregister: _react.PropTypes.func.isRequired
});
var stateManagerPropType = exports.stateManagerPropType = _react.PropTypes.shape({
createURL: _react.PropTypes.func.isRequired,
setState: _react.PropTypes.func.isRequired,
getState: _react.PropTypes.func.isRequired,
unlisten: _react.PropTypes.func.isRequired
});
var withKeysPropType = exports.withKeysPropType = function withKeysPropType(keys) {
return function (props, propName, componentName) {
var prop = props[propName];
if (prop) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
if (keys.indexOf(key) === -1) {
return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.'));
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return undefined;
};
};
/***/ }),
/* 401 */
/***/ (function(module, exports, __webpack_require__) {
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug.debug = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = __webpack_require__(402);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting
args = exports.formatArgs.apply(self, args);
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
/***/ }),
/* 402 */
/***/ (function(module, exports) {
/**
* Helpers.
*/
var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {}
var type = typeof val
if (type === 'string' && val.length > 0) {
return parse(val)
} else if (type === 'number' && isNaN(val) === false) {
return options.long ?
fmtLong(val) :
fmtShort(val)
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str)
if (str.length > 10000) {
return
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
if (!match) {
return
}
var n = parseFloat(match[1])
var type = (match[2] || 'ms').toLowerCase()
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y
case 'days':
case 'day':
case 'd':
return n * d
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n
default:
return undefined
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd'
}
if (ms >= h) {
return Math.round(ms / h) + 'h'
}
if (ms >= m) {
return Math.round(ms / m) + 'm'
}
if (ms >= s) {
return Math.round(ms / s) + 's'
}
return ms + 'ms'
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms'
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name
}
return Math.ceil(ms / n) + ' ' + name + 's'
}
/***/ }),
/* 403 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = AlgoliaSearch;
var Index = __webpack_require__(405);
var deprecate = __webpack_require__(249);
var deprecatedMessage = __webpack_require__(250);
var AlgoliaSearchCore = __webpack_require__(404);
var inherits = __webpack_require__(122);
var errors = __webpack_require__(111);
function AlgoliaSearch() {
AlgoliaSearchCore.apply(this, arguments);
}
inherits(AlgoliaSearch, AlgoliaSearchCore);
/*
* Delete an index
*
* @param indexName the name of index to delete
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.deleteIndex = function(indexName, callback) {
return this._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexName),
hostType: 'write',
callback: callback
});
};
/**
* Move an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of
* srcIndexName (destination will be overriten if it already exist).
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.moveIndex = function(srcIndexName, dstIndexName, callback) {
var postObj = {
operation: 'move', destination: dstIndexName
};
return this._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Copy an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy
* of srcIndexName (destination will be overriten if it already exist).
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.copyIndex = function(srcIndexName, dstIndexName, callback) {
var postObj = {
operation: 'copy', destination: dstIndexName
};
return this._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Return last log entries.
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting
* at offset. Maximum allowed value: 1000.
* @param type Specify the maximum number of entries to retrieve starting
* at offset. Maximum allowed value: 1000.
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.getLogs = function(offset, length, callback) {
var clone = __webpack_require__(77);
var params = {};
if (typeof offset === 'object') {
// getLogs(params)
params = clone(offset);
callback = length;
} else if (arguments.length === 0 || typeof offset === 'function') {
// getLogs([cb])
callback = offset;
} else if (arguments.length === 1 || typeof length === 'function') {
// getLogs(1, [cb)]
callback = length;
params.offset = offset;
} else {
// getLogs(1, 2, [cb])
params.offset = offset;
params.length = length;
}
if (params.offset === undefined) params.offset = 0;
if (params.length === undefined) params.length = 10;
return this._jsonRequest({
method: 'GET',
url: '/1/logs?' + this._getSearchParams(params, ''),
hostType: 'read',
callback: callback
});
};
/*
* List all existing indexes (paginated)
*
* @param page The page to retrieve, starting at 0.
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with index list
*/
AlgoliaSearch.prototype.listIndexes = function(page, callback) {
var params = '';
if (page === undefined || typeof page === 'function') {
callback = page;
} else {
params = '?page=' + page;
}
return this._jsonRequest({
method: 'GET',
url: '/1/indexes' + params,
hostType: 'read',
callback: callback
});
};
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearch.prototype.initIndex = function(indexName) {
return new Index(this, indexName);
};
/*
* List all existing user keys with their associated ACLs
*
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
AlgoliaSearch.prototype.listUserKeys = function(callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/keys',
hostType: 'read',
callback: callback
});
};
/*
* Get ACL of a user key
*
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
AlgoliaSearch.prototype.getUserKeyACL = function(key, callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/keys/' + key,
hostType: 'read',
callback: callback
});
};
/*
* Delete an existing user key
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
AlgoliaSearch.prototype.deleteUserKey = function(key, callback) {
return this._jsonRequest({
method: 'DELETE',
url: '/1/keys/' + key,
hostType: 'write',
callback: callback
});
};
/*
* Add a new global API key
*
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string[]} params.indexes - Allowed targeted indexes for this key
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.addUserKey(['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* indexes: ['fruits'],
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#AddKey|Algolia REST API Documentation}
*/
AlgoliaSearch.prototype.addUserKey = function(acls, params, callback) {
var isArray = __webpack_require__(35);
var usage = 'Usage: client.addUserKey(arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 1 || typeof params === 'function') {
callback = params;
params = null;
}
var postObj = {
acl: acls
};
if (params) {
postObj.validity = params.validity;
postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
postObj.maxHitsPerQuery = params.maxHitsPerQuery;
postObj.indexes = params.indexes;
postObj.description = params.description;
if (params.queryParameters) {
postObj.queryParameters = this._getSearchParams(params.queryParameters, '');
}
postObj.referers = params.referers;
}
return this._jsonRequest({
method: 'POST',
url: '/1/keys',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Add a new global API key
* @deprecated Please use client.addUserKey()
*/
AlgoliaSearch.prototype.addUserKeyWithValidity = deprecate(function(acls, params, callback) {
return this.addUserKey(acls, params, callback);
}, deprecatedMessage('client.addUserKeyWithValidity()', 'client.addUserKey()'));
/**
* Update an existing API key
* @param {string} key - The key to update
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string[]} params.indexes - Allowed targeted indexes for this key
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.updateUserKey('APIKEY', ['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* indexes: ['fruits'],
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation}
*/
AlgoliaSearch.prototype.updateUserKey = function(key, acls, params, callback) {
var isArray = __webpack_require__(35);
var usage = 'Usage: client.updateUserKey(key, arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 2 || typeof params === 'function') {
callback = params;
params = null;
}
var putObj = {
acl: acls
};
if (params) {
putObj.validity = params.validity;
putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
putObj.maxHitsPerQuery = params.maxHitsPerQuery;
putObj.indexes = params.indexes;
putObj.description = params.description;
if (params.queryParameters) {
putObj.queryParameters = this._getSearchParams(params.queryParameters, '');
}
putObj.referers = params.referers;
}
return this._jsonRequest({
method: 'PUT',
url: '/1/keys/' + key,
body: putObj,
hostType: 'write',
callback: callback
});
};
/**
* Initialize a new batch of search queries
* @deprecated use client.search()
*/
AlgoliaSearch.prototype.startQueriesBatch = deprecate(function startQueriesBatchDeprecated() {
this._batch = [];
}, deprecatedMessage('client.startQueriesBatch()', 'client.search()'));
/**
* Add a search query in the batch
* @deprecated use client.search()
*/
AlgoliaSearch.prototype.addQueryInBatch = deprecate(function addQueryInBatchDeprecated(indexName, query, args) {
this._batch.push({
indexName: indexName,
query: query,
params: args
});
}, deprecatedMessage('client.addQueryInBatch()', 'client.search()'));
/**
* Launch the batch of queries using XMLHttpRequest.
* @deprecated use client.search()
*/
AlgoliaSearch.prototype.sendQueriesBatch = deprecate(function sendQueriesBatchDeprecated(callback) {
return this.search(this._batch, callback);
}, deprecatedMessage('client.sendQueriesBatch()', 'client.search()'));
/**
* Perform write operations accross multiple indexes.
*
* To reduce the amount of time spent on network round trips,
* you can create, update, or delete several objects in one call,
* using the batch endpoint (all operations are done in the given order).
*
* Available actions:
* - addObject
* - updateObject
* - partialUpdateObject
* - partialUpdateObjectNoCreate
* - deleteObject
*
* https://www.algolia.com/doc/rest_api#Indexes
* @param {Object[]} operations An array of operations to perform
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.batch([{
* action: 'addObject',
* indexName: 'clients',
* body: {
* name: 'Bill'
* }
* }, {
* action: 'udpateObject',
* indexName: 'fruits',
* body: {
* objectID: '29138',
* name: 'banana'
* }
* }], cb)
*/
AlgoliaSearch.prototype.batch = function(operations, callback) {
var isArray = __webpack_require__(35);
var usage = 'Usage: client.batch(operations[, callback])';
if (!isArray(operations)) {
throw new Error(usage);
}
return this._jsonRequest({
method: 'POST',
url: '/1/indexes/*/batch',
body: {
requests: operations
},
hostType: 'write',
callback: callback
});
};
// environment specific methods
AlgoliaSearch.prototype.destroy = notImplemented;
AlgoliaSearch.prototype.enableRateLimitForward = notImplemented;
AlgoliaSearch.prototype.disableRateLimitForward = notImplemented;
AlgoliaSearch.prototype.useSecuredAPIKey = notImplemented;
AlgoliaSearch.prototype.disableSecuredAPIKey = notImplemented;
AlgoliaSearch.prototype.generateSecuredApiKey = notImplemented;
function notImplemented() {
var message = 'Not implemented in this environment.\n' +
'If you feel this is a mistake, write to support@algolia.com';
throw new errors.AlgoliaSearchError(message);
}
/***/ }),
/* 404 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {module.exports = AlgoliaSearchCore;
var errors = __webpack_require__(111);
var exitPromise = __webpack_require__(348);
var IndexCore = __webpack_require__(346);
var store = __webpack_require__(413);
// We will always put the API KEY in the JSON body in case of too long API KEY,
// to avoid query string being too long and failing in various conditions (our server limit, browser limit,
// proxies limit)
var MAX_API_KEY_LENGTH = 500;
var RESET_APP_DATA_TIMER =
process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) ||
60 * 2 * 1000; // after 2 minutes reset to first host
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API.
* Set to 'https:' to force using https.
* Default to document.location.protocol in browsers
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = __webpack_require__(214)('algoliasearch');
var clone = __webpack_require__(77);
var isArray = __webpack_require__(35);
var map = __webpack_require__(121);
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
this.hosts = {
read: [],
write: []
};
opts = opts || {};
var protocol = opts.protocol || 'https:';
this._timeouts = opts.timeouts || {
connect: 1 * 1000, // 500ms connect is GPRS latency
read: 2 * 1000,
write: 30 * 1000
};
// backward compat, if opts.timeout is passed, we use it to configure all timeouts like before
if (opts.timeout) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout;
}
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
this._checkAppIdData();
if (!opts.hosts) {
var defaultHosts = map(this._shuffleResult, function(hostNumber) {
return applicationID + '-' + hostNumber + '.algolianet.com';
});
// no hosts given, compute defaults
this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
// when passing custom hosts, we need to have a different host index if the number
// of write/read hosts are different.
this.hosts.read = clone(opts.hosts);
this.hosts.write = clone(opts.hosts);
} else {
this.hosts.read = clone(opts.hosts.read);
this.hosts.write = clone(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.extraHeaders = [];
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders.push({
name: name.toLowerCase(), value: value
});
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
if (this._ua.indexOf(';' + algoliaAgent) === -1) {
this._ua += ';' + algoliaAgent;
}
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
this._checkAppIdData();
var requestDebug = __webpack_require__(214)('algoliasearch:' + initialOpts.url);
var body;
var additionalUA = initialOpts.additionalUA || '';
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders(additionalUA, false);
} else {
headers = this._computeRequestHeaders(additionalUA);
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
client._checkAppIdData();
var startTime = new Date();
var cacheID;
if (client._useCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (client._useCache && cache && cache[cacheID] !== undefined) {
requestDebug('serving response from cache');
return client._promise.resolve(JSON.parse(cache[cacheID]));
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to support@algolia.com to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders(additionalUA);
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
client._setHostIndexByType(0, initialOpts.hostType);
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client._getHostByType(initialOpts.hostType);
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeouts: reqOpts.timeouts,
debug: requestDebug
};
requestDebug('method: %s, url: %s, headers: %j, timeouts: %d',
options.method, url, options.headers, options.timeouts);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return httpResponse.body;
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occured, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client._incrementHostIndex(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client._incrementHostIndex(initialOpts.hostType);
client._incrementTimeoutMultipler();
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
}
var promise = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeouts: client._getTimeoutsForRequest(initialOpts.hostType)
}
);
// either we have a callback
// either we are using promises
if (initialOpts.callback) {
promise.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, content);
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
return promise;
}
};
/*
* Transform search param object in query string
* @param {object} args arguments to add to the current query string
* @param {string} params current query string
* @return {string} the final query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) {
var forEach = __webpack_require__(112);
var ua = additionalUA ?
this._ua + ';' + additionalUA :
this._ua;
var requestHeaders = {
'x-algolia-agent': ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (withAPIKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
if (this.extraHeaders) {
forEach(this.extraHeaders, function addToRequestHeaders(header) {
requestHeaders[header.name] = header.value;
});
}
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = __webpack_require__(35);
var map = __webpack_require__(121);
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
url += '?strategy=' + opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
* @deprecated
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds;
}
};
/**
* Set the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) {
this._timeouts = timeouts;
};
/**
* Get the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.getTimeouts = function() {
return this._timeouts;
};
AlgoliaSearchCore.prototype._getAppIdData = function() {
var data = store.get(this.applicationID);
if (data !== null) this._cacheAppIdData(data);
return data;
};
AlgoliaSearchCore.prototype._setAppIdData = function(data) {
data.lastChange = (new Date()).getTime();
this._cacheAppIdData(data);
return store.set(this.applicationID, data);
};
AlgoliaSearchCore.prototype._checkAppIdData = function() {
var data = this._getAppIdData();
var now = (new Date()).getTime();
if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) {
return this._resetInitialAppIdData(data);
}
return data;
};
AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) {
var newData = data || {};
newData.hostIndexes = {read: 0, write: 0};
newData.timeoutMultiplier = 1;
newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]);
return this._setAppIdData(newData);
};
AlgoliaSearchCore.prototype._cacheAppIdData = function(data) {
this._hostIndexes = data.hostIndexes;
this._timeoutMultiplier = data.timeoutMultiplier;
this._shuffleResult = data.shuffleResult;
};
AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) {
var foreach = __webpack_require__(112);
var currentData = this._getAppIdData();
foreach(newData, function(value, key) {
currentData[key] = value;
});
return this._setAppIdData(currentData);
};
AlgoliaSearchCore.prototype._getHostByType = function(hostType) {
return this.hosts[hostType][this._getHostIndexByType(hostType)];
};
AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() {
return this._timeoutMultiplier;
};
AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) {
return this._hostIndexes[hostType];
};
AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) {
var clone = __webpack_require__(77);
var newHostIndexes = clone(this._hostIndexes);
newHostIndexes[hostType] = hostIndex;
this._partialAppIdDataUpdate({hostIndexes: newHostIndexes});
return hostIndex;
};
AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) {
return this._setHostIndexByType(
(this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType
);
};
AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() {
var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4);
return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier});
};
AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) {
return {
connect: this._timeouts.connect * this._timeoutMultiplier,
complete: this._timeouts[hostType] * this._timeoutMultiplier
};
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110)))
/***/ }),
/* 405 */
/***/ (function(module, exports, __webpack_require__) {
var inherits = __webpack_require__(122);
var IndexCore = __webpack_require__(346);
var deprecate = __webpack_require__(249);
var deprecatedMessage = __webpack_require__(250);
var exitPromise = __webpack_require__(348);
var errors = __webpack_require__(111);
var deprecateForwardToSlaves = deprecate(
function() {},
deprecatedMessage('forwardToSlaves', 'forwardToReplicas')
);
module.exports = Index;
function Index() {
IndexCore.apply(this, arguments);
}
inherits(Index, IndexCore);
/*
* Add an object in this index
*
* @param content contains the javascript object to add inside the index
* @param objectID (optional) an objectID you want to attribute to this object
* (if the attribute already exist the old object will be overwrite)
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.addObject = function(content, objectID, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof objectID === 'function') {
callback = objectID;
objectID = undefined;
}
return this.as._jsonRequest({
method: objectID !== undefined ?
'PUT' : // update or create
'POST', // create (API generates an objectID)
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + // create
(objectID !== undefined ? '/' + encodeURIComponent(objectID) : ''), // update or create
body: content,
hostType: 'write',
callback: callback
});
};
/*
* Add several objects
*
* @param objects contains an array of objects to add
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.addObjects = function(objects, callback) {
var isArray = __webpack_require__(35);
var usage = 'Usage: index.addObjects(arrayOfObjects[, callback])';
if (!isArray(objects)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: []
};
for (var i = 0; i < objects.length; ++i) {
var request = {
action: 'addObject',
body: objects[i]
};
postObj.requests.push(request);
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Update partially an object (only update attributes passed in argument)
*
* @param partialObject contains the javascript attributes to override, the
* object must contains an objectID attribute
* @param createIfNotExists (optional) if false, avoid an automatic creation of the object
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.partialUpdateObject = function(partialObject, createIfNotExists, callback) {
if (arguments.length === 1 || typeof createIfNotExists === 'function') {
callback = createIfNotExists;
createIfNotExists = undefined;
}
var indexObj = this;
var url = '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(partialObject.objectID) + '/partial';
if (createIfNotExists === false) {
url += '?createIfNotExists=false';
}
return this.as._jsonRequest({
method: 'POST',
url: url,
body: partialObject,
hostType: 'write',
callback: callback
});
};
/*
* Partially Override the content of several objects
*
* @param objects contains an array of objects to update (each object must contains a objectID attribute)
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.partialUpdateObjects = function(objects, callback) {
var isArray = __webpack_require__(35);
var usage = 'Usage: index.partialUpdateObjects(arrayOfObjects[, callback])';
if (!isArray(objects)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: []
};
for (var i = 0; i < objects.length; ++i) {
var request = {
action: 'partialUpdateObject',
objectID: objects[i].objectID,
body: objects[i]
};
postObj.requests.push(request);
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Override the content of object
*
* @param object contains the javascript object to save, the object must contains an objectID attribute
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.saveObject = function(object, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(object.objectID),
body: object,
hostType: 'write',
callback: callback
});
};
/*
* Override the content of several objects
*
* @param objects contains an array of objects to update (each object must contains a objectID attribute)
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.saveObjects = function(objects, callback) {
var isArray = __webpack_require__(35);
var usage = 'Usage: index.saveObjects(arrayOfObjects[, callback])';
if (!isArray(objects)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: []
};
for (var i = 0; i < objects.length; ++i) {
var request = {
action: 'updateObject',
objectID: objects[i].objectID,
body: objects[i]
};
postObj.requests.push(request);
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Delete an object from the index
*
* @param objectID the unique identifier of object to delete
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.deleteObject = function(objectID, callback) {
if (typeof objectID === 'function' || typeof objectID !== 'string' && typeof objectID !== 'number') {
var err = new errors.AlgoliaSearchError('Cannot delete an object without an objectID');
callback = objectID;
if (typeof callback === 'function') {
return callback(err);
}
return this.as._promise.reject(err);
}
var indexObj = this;
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID),
hostType: 'write',
callback: callback
});
};
/*
* Delete several objects from an index
*
* @param objectIDs contains an array of objectID to delete
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.deleteObjects = function(objectIDs, callback) {
var isArray = __webpack_require__(35);
var map = __webpack_require__(121);
var usage = 'Usage: index.deleteObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: map(objectIDs, function prepareRequest(objectID) {
return {
action: 'deleteObject',
objectID: objectID,
body: {
objectID: objectID
}
};
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Delete all objects matching a query
*
* @param query the query string
* @param params the optional query parameters
* @param callback (optional) the result callback called with one argument
* error: null or Error('message')
*/
Index.prototype.deleteByQuery = function(query, params, callback) {
var clone = __webpack_require__(77);
var map = __webpack_require__(121);
var indexObj = this;
var client = indexObj.as;
if (arguments.length === 1 || typeof params === 'function') {
callback = params;
params = {};
} else {
params = clone(params);
}
params.attributesToRetrieve = 'objectID';
params.hitsPerPage = 1000;
params.distinct = false;
// when deleting, we should never use cache to get the
// search results
this.clearCache();
// there's a problem in how we use the promise chain,
// see how waitTask is done
var promise = this
.search(query, params)
.then(stopOrDelete);
function stopOrDelete(searchContent) {
// stop here
if (searchContent.nbHits === 0) {
// return indexObj.as._request.resolve();
return searchContent;
}
// continue and do a recursive call
var objectIDs = map(searchContent.hits, function getObjectID(object) {
return object.objectID;
});
return indexObj
.deleteObjects(objectIDs)
.then(waitTask)
.then(doDeleteByQuery);
}
function waitTask(deleteObjectsContent) {
return indexObj.waitTask(deleteObjectsContent.taskID);
}
function doDeleteByQuery() {
return indexObj.deleteByQuery(query, params);
}
if (!callback) {
return promise;
}
promise.then(success, failure);
function success() {
exitPromise(function exit() {
callback(null);
}, client._setTimeout || setTimeout);
}
function failure(err) {
exitPromise(function exit() {
callback(err);
}, client._setTimeout || setTimeout);
}
};
/*
* Browse all content from an index using events. Basically this will do
* .browse() -> .browseFrom -> .browseFrom -> .. until all the results are returned
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @return {EventEmitter}
* @example
* var browser = index.browseAll('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* });
*
* browser.on('result', function resultCallback(content) {
* console.log(content.hits);
* });
*
* // if any error occurs, you get it
* browser.on('error', function(err) {
* throw err;
* });
*
* // when you have browsed the whole index, you get this event
* browser.on('end', function() {
* console.log('finished');
* });
*
* // at any point if you want to stop the browsing process, you can stop it manually
* // otherwise it will go on and on
* browser.stop();
*
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
Index.prototype.browseAll = function(query, queryParameters) {
if (typeof query === 'object') {
queryParameters = query;
query = undefined;
}
var merge = __webpack_require__(349);
var IndexBrowser = __webpack_require__(406);
var browser = new IndexBrowser();
var client = this.as;
var index = this;
var params = client._getSearchParams(
merge({}, queryParameters || {}, {
query: query
}), ''
);
// start browsing
browseLoop();
function browseLoop(cursor) {
if (browser._stopped) {
return;
}
var body;
if (cursor !== undefined) {
body = {
cursor: cursor
};
} else {
body = {
params: params
};
}
client._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(index.indexName) + '/browse',
hostType: 'read',
body: body,
callback: browseCallback
});
}
function browseCallback(err, content) {
if (browser._stopped) {
return;
}
if (err) {
browser._error(err);
return;
}
browser._result(content);
// no cursor means we are finished browsing
if (content.cursor === undefined) {
browser._end();
return;
}
browseLoop(content.cursor);
}
return browser;
};
/*
* Get a Typeahead.js adapter
* @param searchParams contains an object with query parameters (see search for details)
*/
Index.prototype.ttAdapter = function(params) {
var self = this;
return function ttAdapter(query, syncCb, asyncCb) {
var cb;
if (typeof asyncCb === 'function') {
// typeahead 0.11
cb = asyncCb;
} else {
// pre typeahead 0.11
cb = syncCb;
}
self.search(query, params, function searchDone(err, content) {
if (err) {
cb(err);
return;
}
cb(content.hits);
});
};
};
/*
* Wait the publication of a task on the server.
* All server task are asynchronous and you can check with this method that the task is published.
*
* @param taskID the id of the task returned by server
* @param callback the result callback with with two arguments:
* error: null or Error('message')
* content: the server answer that contains the list of results
*/
Index.prototype.waitTask = function(taskID, callback) {
// wait minimum 100ms before retrying
var baseDelay = 100;
// wait maximum 5s before retrying
var maxDelay = 5000;
var loop = 0;
// waitTask() must be handled differently from other methods,
// it's a recursive method using a timeout
var indexObj = this;
var client = indexObj.as;
var promise = retryLoop();
function retryLoop() {
return client._jsonRequest({
method: 'GET',
hostType: 'read',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/task/' + taskID
}).then(function success(content) {
loop++;
var delay = baseDelay * loop * loop;
if (delay > maxDelay) {
delay = maxDelay;
}
if (content.status !== 'published') {
return client._promise.delay(delay).then(retryLoop);
}
return content;
});
}
if (!callback) {
return promise;
}
promise.then(successCb, failureCb);
function successCb(content) {
exitPromise(function exit() {
callback(null, content);
}, client._setTimeout || setTimeout);
}
function failureCb(err) {
exitPromise(function exit() {
callback(err);
}, client._setTimeout || setTimeout);
}
};
/*
* This function deletes the index content. Settings and index specific API keys are kept untouched.
*
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the settings object or the error message if a failure occured
*/
Index.prototype.clearIndex = function(callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/clear',
hostType: 'write',
callback: callback
});
};
/*
* Get settings of this index
*
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the settings object or the error message if a failure occured
*/
Index.prototype.getSettings = function(callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?getVersion=2',
hostType: 'read',
callback: callback
});
};
Index.prototype.searchSynonyms = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = {};
} else if (params === undefined) {
params = {};
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/search',
body: params,
hostType: 'read',
callback: callback
});
};
Index.prototype.saveSynonym = function(synonym, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(synonym.objectID) +
'?forwardToReplicas=' + forwardToReplicas,
body: synonym,
hostType: 'write',
callback: callback
});
};
Index.prototype.getSynonym = function(objectID, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID),
hostType: 'read',
callback: callback
});
};
Index.prototype.deleteSynonym = function(objectID, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID) +
'?forwardToReplicas=' + forwardToReplicas,
hostType: 'write',
callback: callback
});
};
Index.prototype.clearSynonyms = function(opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/clear' +
'?forwardToReplicas=' + forwardToReplicas,
hostType: 'write',
callback: callback
});
};
Index.prototype.batchSynonyms = function(synonyms, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/batch' +
'?forwardToReplicas=' + forwardToReplicas +
'&replaceExistingSynonyms=' + (opts.replaceExistingSynonyms ? 'true' : 'false'),
hostType: 'write',
body: synonyms,
callback: callback
});
};
/*
* Set settings for this index
*
* @param settigns the settings object that can contains :
* - minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3).
* - minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7).
* - hitsPerPage: (integer) the number of hits per page (default = 10).
* - attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects.
* If set to null, all attributes are retrieved.
* - attributesToHighlight: (array of strings) default list of attributes to highlight.
* If set to null, all indexed attributes are highlighted.
* - attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number
* of words to return (syntax is attributeName:nbWords).
* By default no snippet is computed. If set to null, no snippet is computed.
* - attributesToIndex: (array of strings) the list of fields you want to index.
* If set to null, all textual and numerical attributes of your objects are indexed,
* but you should update it to get optimal results.
* This parameter has two important uses:
* - Limit the attributes to index: For example if you store a binary image in base64,
* you want to store it and be able to
* retrieve it but you don't want to search in the base64 string.
* - Control part of the ranking*: (see the ranking parameter for full explanation)
* Matches in attributes at the beginning of
* the list will be considered more important than matches in attributes further down the list.
* In one attribute, matching text at the beginning of the attribute will be
* considered more important than text after, you can disable
* this behavior if you add your attribute inside `unordered(AttributeName)`,
* for example attributesToIndex: ["title", "unordered(text)"].
* - attributesForFaceting: (array of strings) The list of fields you want to use for faceting.
* All strings in the attribute selected for faceting are extracted and added as a facet.
* If set to null, no attribute is used for faceting.
* - attributeForDistinct: (string) The attribute name used for the Distinct feature.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in query with the distinct=1 parameter, all hits containing a duplicate
* value for this attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best one is kept and others are removed.
* - ranking: (array of strings) controls the way results are sorted.
* We have six available criteria:
* - typo: sort according to number of typos,
* - geo: sort according to decreassing distance when performing a geo-location based search,
* - proximity: sort according to the proximity of query words in hits,
* - attribute: sort according to the order of attributes defined by attributesToIndex,
* - exact:
* - if the user query contains one word: sort objects having an attribute
* that is exactly the query word before others.
* For example if you search for the "V" TV show, you want to find it
* with the "V" query and avoid to have all popular TV
* show starting by the v letter before it.
* - if the user query contains multiple words: sort according to the
* number of words that matched exactly (and not as a prefix).
* - custom: sort according to a user defined formula set in **customRanking** attribute.
* The standard order is ["typo", "geo", "proximity", "attribute", "exact", "custom"]
* - customRanking: (array of strings) lets you specify part of the ranking.
* The syntax of this condition is an array of strings containing attributes
* prefixed by asc (ascending order) or desc (descending order) operator.
* For example `"customRanking" => ["desc(population)", "asc(name)"]`
* - queryType: Select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - highlightPreTag: (string) Specify the string that is inserted before
* the highlighted parts in the query result (default to "<em>").
* - highlightPostTag: (string) Specify the string that is inserted after
* the highlighted parts in the query result (default to "</em>").
* - optionalWords: (array of strings) Specify a list of words that should
* be considered as optional when found in the query.
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the server answer or the error message if a failure occured
*/
Index.prototype.setSettings = function(settings, opts, callback) {
if (arguments.length === 1 || typeof opts === 'function') {
callback = opts;
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
var indexObj = this;
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?forwardToReplicas='
+ forwardToReplicas,
hostType: 'write',
body: settings,
callback: callback
});
};
/*
* List all existing user keys associated to this index
*
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
Index.prototype.listUserKeys = function(callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys',
hostType: 'read',
callback: callback
});
};
/*
* Get ACL of a user key associated to this index
*
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
Index.prototype.getUserKeyACL = function(key, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
hostType: 'read',
callback: callback
});
};
/*
* Delete an existing user key associated to this index
*
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
*/
Index.prototype.deleteUserKey = function(key, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
hostType: 'write',
callback: callback
});
};
/*
* Add a new API key to this index
*
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will
* be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.addUserKey(['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#AddIndexKey|Algolia REST API Documentation}
*/
Index.prototype.addUserKey = function(acls, params, callback) {
var isArray = __webpack_require__(35);
var usage = 'Usage: index.addUserKey(arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 1 || typeof params === 'function') {
callback = params;
params = null;
}
var postObj = {
acl: acls
};
if (params) {
postObj.validity = params.validity;
postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
postObj.maxHitsPerQuery = params.maxHitsPerQuery;
postObj.description = params.description;
if (params.queryParameters) {
postObj.queryParameters = this.as._getSearchParams(params.queryParameters, '');
}
postObj.referers = params.referers;
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Add an existing user key associated to this index
* @deprecated use index.addUserKey()
*/
Index.prototype.addUserKeyWithValidity = deprecate(function deprecatedAddUserKeyWithValidity(acls, params, callback) {
return this.addUserKey(acls, params, callback);
}, deprecatedMessage('index.addUserKeyWithValidity()', 'index.addUserKey()'));
/**
* Update an existing API key of this index
* @param {string} key - The key to update
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will
* be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.updateUserKey('APIKEY', ['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation}
*/
Index.prototype.updateUserKey = function(key, acls, params, callback) {
var isArray = __webpack_require__(35);
var usage = 'Usage: index.updateUserKey(key, arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 2 || typeof params === 'function') {
callback = params;
params = null;
}
var putObj = {
acl: acls
};
if (params) {
putObj.validity = params.validity;
putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
putObj.maxHitsPerQuery = params.maxHitsPerQuery;
putObj.description = params.description;
if (params.queryParameters) {
putObj.queryParameters = this.as._getSearchParams(params.queryParameters, '');
}
putObj.referers = params.referers;
}
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys/' + key,
body: putObj,
hostType: 'write',
callback: callback
});
};
/***/ }),
/* 406 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This is the object returned by the `index.browseAll()` method
module.exports = IndexBrowser;
var inherits = __webpack_require__(122);
var EventEmitter = __webpack_require__(109).EventEmitter;
function IndexBrowser() {
}
inherits(IndexBrowser, EventEmitter);
IndexBrowser.prototype.stop = function() {
this._stopped = true;
this._clean();
};
IndexBrowser.prototype._end = function() {
this.emit('end');
this._clean();
};
IndexBrowser.prototype._error = function(err) {
this.emit('error', err);
this._clean();
};
IndexBrowser.prototype._result = function(content) {
this.emit('result', content);
};
IndexBrowser.prototype._clean = function() {
this.removeAllListeners('stop');
this.removeAllListeners('end');
this.removeAllListeners('error');
this.removeAllListeners('result');
};
/***/ }),
/* 407 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(417);
var Promise = global.Promise || __webpack_require__(416).Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = __webpack_require__(122);
var errors = __webpack_require__(111);
var inlineHeaders = __webpack_require__(409);
var jsonpRequest = __webpack_require__(410);
var places = __webpack_require__(412);
uaSuffix = uaSuffix || '';
if (false) {
require('debug').enable('algoliasearch*');
}
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = __webpack_require__(77);
var getDocumentProtocol = __webpack_require__(408);
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = __webpack_require__(414);
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
global.__algolia = {
debug: __webpack_require__(214),
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in global,
hasXDomainRequest: 'XDomainRequest' in global
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var reqTimeout;
var timedOut;
var connected = false;
reqTimeout = setTimeout(onTimeout, opts.timeouts.connect);
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = onProgress;
if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange;
req.onload = onLoad;
req.onerror = onError;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
} else {
req.open(opts.method, url);
}
// headers are meant to be sent after open
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
req.send(body);
// event object not received in IE8, at least
// but we do not use it, still important to note
function onLoad(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function onError(event) {
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors.Network({
more: event
})
);
}
function onTimeout() {
timedOut = true;
req.abort();
reject(new errors.RequestTimeout());
}
function onConnect() {
connected = true;
clearTimeout(reqTimeout);
reqTimeout = setTimeout(onTimeout, opts.timeouts.complete);
}
function onProgress() {
if (!connected) onConnect();
}
function onReadyStateChange() {
if (!connected && req.readyState > 1) onConnect();
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise.reject(val);
},
resolve: function resolvePromise(val) {
return Promise.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
}
};
return algoliasearch;
};
/***/ }),
/* 408 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = getDocumentProtocol;
function getDocumentProtocol() {
var protocol = window.document.location.protocol;
// when in `file:` mode (local html file), default to `http:`
if (protocol !== 'http:' && protocol !== 'https:') {
protocol = 'http:';
}
return protocol;
}
/***/ }),
/* 409 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = inlineHeaders;
var encode = __webpack_require__(423);
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode(headers);
}
/***/ }),
/* 410 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = jsonpRequest;
var errors = __webpack_require__(111);
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeouts.complete);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
/***/ }),
/* 411 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = function omit(obj, test) {
var keys = __webpack_require__(421);
var foreach = __webpack_require__(112);
var filtered = {};
foreach(keys(obj), function doFilter(keyName) {
if (test(keyName) !== true) {
filtered[keyName] = obj[keyName];
}
});
return filtered;
};
/***/ }),
/* 412 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = createPlacesClient;
var buildSearchMethod = __webpack_require__(347);
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = __webpack_require__(77);
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod('query', '/1/places/query');
return index;
};
}
/***/ }),
/* 413 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var debug = __webpack_require__(214)('algoliasearch:src/hostIndexState.js');
var localStorageNamespace = 'algoliasearch-client-js';
var store;
var moduleStore = {
state: {},
set: function(key, data) {
this.state[key] = data;
return this.state[key];
},
get: function(key) {
return this.state[key] || null;
}
};
var localStorageStore = {
set: function(key, data) {
moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure
try {
var namespace = JSON.parse(global.localStorage[localStorageNamespace]);
namespace[key] = data;
global.localStorage[localStorageNamespace] = JSON.stringify(namespace);
return namespace[key];
} catch (e) {
return localStorageFailure(key, e);
}
},
get: function(key) {
try {
return JSON.parse(global.localStorage[localStorageNamespace])[key] || null;
} catch (e) {
return localStorageFailure(key, e);
}
}
};
function localStorageFailure(key, e) {
debug('localStorage failed with', e);
cleanup();
store = moduleStore;
return store.get(key);
}
store = supportsLocalStorage() ? localStorageStore : moduleStore;
module.exports = {
get: getOrSet,
set: getOrSet,
supportsLocalStorage: supportsLocalStorage
};
function getOrSet(key, data) {
if (arguments.length === 1) {
return store.get(key);
}
return store.set(key, data);
}
function supportsLocalStorage() {
try {
if ('localStorage' in global &&
global.localStorage !== null) {
if (!global.localStorage[localStorageNamespace]) {
// actual creation of the namespace
global.localStorage.setItem(localStorageNamespace, JSON.stringify({}));
}
return true;
}
return false;
} catch (_) {
return false;
}
}
// In case of any error on localStorage, we clean our own namespace, this should handle
// quota errors when a lot of keys + data are used
function cleanup() {
try {
global.localStorage.removeItem(localStorageNamespace);
} catch (_) {
// nothing to do
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(52)))
/***/ }),
/* 414 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = '3.21.1';
/***/ }),
/* 415 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ }),
/* 416 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process, global) {var require;/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version 4.0.5
*/
(function (global, factory) {
true ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ES6Promise = factory());
}(this, (function () { 'use strict';
function objectOrFunction(x) {
return typeof x === 'function' || typeof x === 'object' && x !== null;
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = undefined;
if (!Array.isArray) {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
_isArray = Array.isArray;
}
var isArray = _isArray;
var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = require;
var vertx = __webpack_require__(425);
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && "function" === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var _arguments = arguments;
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
(function () {
var callback = _arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
})();
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
_resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
_resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
_reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
_reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
_reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return _resolve(promise, value);
}, function (reason) {
return _reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$) {
if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$ === GET_THEN_ERROR) {
_reject(promise, GET_THEN_ERROR.error);
} else if (then$$ === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$)) {
handleForeignThenable(promise, maybeThenable, then$$);
} else {
fulfill(promise, maybeThenable);
}
}
}
function _resolve(promise, value) {
if (promise === value) {
_reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function _reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = undefined,
callback = undefined,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = undefined,
error = undefined,
succeeded = undefined,
failed = undefined;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
_reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
_resolve(promise, value);
} else if (failed) {
_reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
_reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
_resolve(promise, value);
}, function rejectPromise(reason) {
_reject(promise, reason);
});
} catch (e) {
_reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
_reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
};
Enumerator.prototype._enumerate = function () {
var length = this.length;
var _input = this._input;
for (var i = 0; this._state === PENDING && i < length; i++) {
this._eachEntry(_input[i], i);
}
};
Enumerator.prototype._eachEntry = function (entry, i) {
var c = this._instanceConstructor;
var resolve$$ = c.resolve;
if (resolve$$ === resolve) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$) {
return resolve$$(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$(entry), i);
}
};
Enumerator.prototype._settledAt = function (state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
_reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
Promise.all = all;
Promise.race = race;
Promise.resolve = resolve;
Promise.reject = reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;
Promise.prototype = {
constructor: Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function _catch(onRejection) {
return this.then(null, onRejection);
}
};
function polyfill() {
var local = undefined;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise;
}
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;
return Promise;
})));
//# sourceMappingURL=es6-promise.map
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110), __webpack_require__(52)))
/***/ }),
/* 417 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(52)))
/***/ }),
/* 418 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeMax = Math.max;
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
module.exports = baseRange;
/***/ }),
/* 419 */
/***/ (function(module, exports, __webpack_require__) {
var baseRange = __webpack_require__(418),
isIterateeCall = __webpack_require__(215),
toFinite = __webpack_require__(217);
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
module.exports = createRange;
/***/ }),
/* 420 */
/***/ (function(module, exports, __webpack_require__) {
var createRange = __webpack_require__(419);
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range = createRange();
module.exports = range;
/***/ }),
/* 421 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = __webpack_require__(422);
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
/***/ }),
/* 422 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
/***/ }),
/* 423 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
/***/ }),
/* 424 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_424__;
/***/ }),
/* 425 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 426 */,
/* 427 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Panel = exports.Toggle = exports.Stats = exports.SortBy = exports.SearchBox = exports.ScrollTo = exports.ClearAll = exports.RefinementList = exports.StarRating = exports.RangeSlider = exports.RangeInput = exports.PoweredBy = exports.Pagination = exports.MultiRange = exports.Menu = exports.InfiniteHits = exports.HitsPerPage = exports.Hits = exports.Snippet = exports.Highlight = exports.HierarchicalMenu = exports.CurrentRefinements = exports.Configure = exports.InstantSearch = undefined;
var _Configure = __webpack_require__(352);
Object.defineProperty(exports, 'Configure', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Configure).default;
}
});
var _CurrentRefinements = __webpack_require__(353);
Object.defineProperty(exports, 'CurrentRefinements', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_CurrentRefinements).default;
}
});
var _HierarchicalMenu = __webpack_require__(354);
Object.defineProperty(exports, 'HierarchicalMenu', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_HierarchicalMenu).default;
}
});
var _Highlight = __webpack_require__(233);
Object.defineProperty(exports, 'Highlight', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Highlight).default;
}
});
var _Snippet = __webpack_require__(368);
Object.defineProperty(exports, 'Snippet', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Snippet).default;
}
});
var _Hits = __webpack_require__(355);
Object.defineProperty(exports, 'Hits', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Hits).default;
}
});
var _HitsPerPage = __webpack_require__(356);
Object.defineProperty(exports, 'HitsPerPage', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_HitsPerPage).default;
}
});
var _InfiniteHits = __webpack_require__(357);
Object.defineProperty(exports, 'InfiniteHits', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_InfiniteHits).default;
}
});
var _Menu = __webpack_require__(358);
Object.defineProperty(exports, 'Menu', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Menu).default;
}
});
var _MultiRange = __webpack_require__(359);
Object.defineProperty(exports, 'MultiRange', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_MultiRange).default;
}
});
var _Pagination = __webpack_require__(360);
Object.defineProperty(exports, 'Pagination', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Pagination).default;
}
});
var _PoweredBy = __webpack_require__(362);
Object.defineProperty(exports, 'PoweredBy', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_PoweredBy).default;
}
});
var _RangeInput = __webpack_require__(363);
Object.defineProperty(exports, 'RangeInput', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_RangeInput).default;
}
});
var _RangeSlider = __webpack_require__(364);
Object.defineProperty(exports, 'RangeSlider', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_RangeSlider).default;
}
});
var _StarRating = __webpack_require__(370);
Object.defineProperty(exports, 'StarRating', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_StarRating).default;
}
});
var _RefinementList = __webpack_require__(365);
Object.defineProperty(exports, 'RefinementList', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_RefinementList).default;
}
});
var _ClearAll = __webpack_require__(351);
Object.defineProperty(exports, 'ClearAll', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_ClearAll).default;
}
});
var _ScrollTo = __webpack_require__(366);
Object.defineProperty(exports, 'ScrollTo', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_ScrollTo).default;
}
});
var _SearchBox = __webpack_require__(367);
Object.defineProperty(exports, 'SearchBox', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_SearchBox).default;
}
});
var _SortBy = __webpack_require__(369);
Object.defineProperty(exports, 'SortBy', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_SortBy).default;
}
});
var _Stats = __webpack_require__(371);
Object.defineProperty(exports, 'Stats', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Stats).default;
}
});
var _Toggle = __webpack_require__(372);
Object.defineProperty(exports, 'Toggle', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Toggle).default;
}
});
var _Panel = __webpack_require__(361);
Object.defineProperty(exports, 'Panel', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Panel).default;
}
});
var _createInstantSearch = __webpack_require__(350);
var _createInstantSearch2 = _interopRequireDefault(_createInstantSearch);
var _algoliasearch = __webpack_require__(373);
var _algoliasearch2 = _interopRequireDefault(_algoliasearch);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var InstantSearch = (0, _createInstantSearch2.default)(_algoliasearch2.default, {
Root: 'div',
props: { className: 'ais-InstantSearch__root' }
});
exports.InstantSearch = InstantSearch;
/***/ })
/******/ ]);
});
//# sourceMappingURL=Dom.js.map |
packages/material-ui-icons/src/KeyboardReturnTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7h-2z" /></g></React.Fragment>
, 'KeyboardReturnTwoTone');
|
src/main/webapp/extjs/src/form/Panel.js | martinvale/propial | /*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314)
*/
/**
* @docauthor Jason Johnston <jason@sencha.com>
*
* FormPanel provides a standard container for forms. It is essentially a standard {@link Ext.panel.Panel} which
* automatically creates a {@link Ext.form.Basic BasicForm} for managing any {@link Ext.form.field.Field}
* objects that are added as descendants of the panel. It also includes conveniences for configuring and
* working with the BasicForm and the collection of Fields.
*
* # Layout
*
* By default, FormPanel is configured with `{@link Ext.layout.container.Anchor layout:'anchor'}` for
* the layout of its immediate child items. This can be changed to any of the supported container layouts.
* The layout of sub-containers is configured in {@link Ext.container.Container#layout the standard way}.
*
* # BasicForm
*
* Although **not listed** as configuration options of FormPanel, the FormPanel class accepts all
* of the config options supported by the {@link Ext.form.Basic} class, and will pass them along to
* the internal BasicForm when it is created.
*
* The following events fired by the BasicForm will be re-fired by the FormPanel and can therefore be
* listened for on the FormPanel itself:
*
* - {@link Ext.form.Basic#beforeaction beforeaction}
* - {@link Ext.form.Basic#actionfailed actionfailed}
* - {@link Ext.form.Basic#actioncomplete actioncomplete}
* - {@link Ext.form.Basic#validitychange validitychange}
* - {@link Ext.form.Basic#dirtychange dirtychange}
*
* # Field Defaults
*
* The {@link #fieldDefaults} config option conveniently allows centralized configuration of default values
* for all fields added as descendants of the FormPanel. Any config option recognized by implementations
* of {@link Ext.form.Labelable} may be included in this object. See the {@link #fieldDefaults} documentation
* for details of how the defaults are applied.
*
* # Form Validation
*
* With the default configuration, form fields are validated on-the-fly while the user edits their values.
* This can be controlled on a per-field basis (or via the {@link #fieldDefaults} config) with the field
* config properties {@link Ext.form.field.Field#validateOnChange} and {@link Ext.form.field.Base#checkChangeEvents},
* and the FormPanel's config properties {@link #pollForChanges} and {@link #pollInterval}.
*
* Any component within the FormPanel can be configured with `formBind: true`. This will cause that
* component to be automatically disabled when the form is invalid, and enabled when it is valid. This is most
* commonly used for Button components to prevent submitting the form in an invalid state, but can be used on
* any component type.
*
* For more information on form validation see the following:
*
* - {@link Ext.form.field.Field#validateOnChange}
* - {@link #pollForChanges} and {@link #pollInterval}
* - {@link Ext.form.field.VTypes}
* - {@link Ext.form.Basic#doAction BasicForm.doAction clientValidation notes}
*
* # Form Submission
*
* By default, Ext Forms are submitted through Ajax, using {@link Ext.form.action.Action}. See the documentation for
* {@link Ext.form.Basic} for details.
*
* # Example usage
*
* @example
* Ext.create('Ext.form.Panel', {
* title: 'Simple Form',
* bodyPadding: 5,
* width: 350,
*
* // The form will submit an AJAX request to this URL when submitted
* url: 'save-form.php',
*
* // Fields will be arranged vertically, stretched to full width
* layout: 'anchor',
* defaults: {
* anchor: '100%'
* },
*
* // The fields
* defaultType: 'textfield',
* items: [{
* fieldLabel: 'First Name',
* name: 'first',
* allowBlank: false
* },{
* fieldLabel: 'Last Name',
* name: 'last',
* allowBlank: false
* }],
*
* // Reset and Submit buttons
* buttons: [{
* text: 'Reset',
* handler: function() {
* this.up('form').getForm().reset();
* }
* }, {
* text: 'Submit',
* formBind: true, //only enabled once the form is valid
* disabled: true,
* handler: function() {
* var form = this.up('form').getForm();
* if (form.isValid()) {
* form.submit({
* success: function(form, action) {
* Ext.Msg.alert('Success', action.result.msg);
* },
* failure: function(form, action) {
* Ext.Msg.alert('Failed', action.result.msg);
* }
* });
* }
* }
* }],
* renderTo: Ext.getBody()
* });
*
*/
Ext.define('Ext.form.Panel', {
extend:'Ext.panel.Panel',
mixins: {
fieldAncestor: 'Ext.form.FieldAncestor'
},
alias: 'widget.form',
alternateClassName: ['Ext.FormPanel', 'Ext.form.FormPanel'],
requires: ['Ext.form.Basic', 'Ext.util.TaskRunner'],
/**
* @cfg {Boolean} pollForChanges
* If set to `true`, sets up an interval task (using the {@link #pollInterval}) in which the
* panel's fields are repeatedly checked for changes in their values. This is in addition to the normal detection
* each field does on its own input element, and is not needed in most cases. It does, however, provide a
* means to absolutely guarantee detection of all changes including some edge cases in some browsers which
* do not fire native events. Defaults to `false`.
*/
/**
* @cfg {Number} pollInterval
* Interval in milliseconds at which the form's fields are checked for value changes. Only used if
* the {@link #pollForChanges} option is set to `true`. Defaults to 500 milliseconds.
*/
/**
* @cfg {Ext.enums.Layout/Object} layout
* The {@link Ext.container.Container#layout} for the form panel's immediate child items.
*/
layout: 'anchor',
ariaRole: 'form',
basicFormConfigs: [
'api',
'baseParams',
'errorReader',
'jsonSubmit',
'method',
'paramOrder',
'paramsAsHash',
'reader',
'standardSubmit',
'timeout',
'trackResetOnLoad',
'url',
'waitMsgTarget',
'waitTitle'
],
initComponent: function() {
var me = this;
if (me.frame) {
me.border = false;
}
me.initFieldAncestor();
me.callParent();
me.relayEvents(me.form, [
/**
* @event beforeaction
* @inheritdoc Ext.form.Basic#beforeaction
*/
'beforeaction',
/**
* @event actionfailed
* @inheritdoc Ext.form.Basic#actionfailed
*/
'actionfailed',
/**
* @event actioncomplete
* @inheritdoc Ext.form.Basic#actioncomplete
*/
'actioncomplete',
/**
* @event validitychange
* @inheritdoc Ext.form.Basic#validitychange
*/
'validitychange',
/**
* @event dirtychange
* @inheritdoc Ext.form.Basic#dirtychange
*/
'dirtychange'
]);
// Start polling if configured
if (me.pollForChanges) {
me.startPolling(me.pollInterval || 500);
}
},
initItems: function() {
// Create the BasicForm
this.callParent();
this.initMonitor();
this.form = this.createForm();
},
// Initialize the BasicForm after all layouts have been completed.
afterFirstLayout: function() {
this.callParent(arguments);
this.form.initialize();
},
/**
* @private
*/
createForm: function() {
var cfg = {},
props = this.basicFormConfigs,
len = props.length,
i = 0,
prop;
for (; i < len; ++i) {
prop = props[i];
cfg[prop] = this[prop];
}
return new Ext.form.Basic(this, cfg);
},
/**
* Provides access to the {@link Ext.form.Basic Form} which this Panel contains.
* @return {Ext.form.Basic} The {@link Ext.form.Basic Form} which this Panel contains.
*/
getForm: function() {
return this.form;
},
/**
* Loads an {@link Ext.data.Model} into this form (internally just calls {@link Ext.form.Basic#loadRecord})
* See also {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}.
* @param {Ext.data.Model} record The record to load
* @return {Ext.form.Basic} The Ext.form.Basic attached to this FormPanel
*/
loadRecord: function(record) {
return this.getForm().loadRecord(record);
},
/**
* Returns the currently loaded Ext.data.Model instance if one was loaded via {@link #loadRecord}.
* @return {Ext.data.Model} The loaded instance
*/
getRecord: function() {
return this.getForm().getRecord();
},
/**
* Persists the values in this form into the passed {@link Ext.data.Model} object in a beginEdit/endEdit block.
* If the record is not specified, it will attempt to update (if it exists) the record provided to {@link #loadRecord}.
* @param {Ext.data.Model} [record] The record to edit
* @return {Ext.form.Basic} The Ext.form.Basic attached to this FormPanel
*/
updateRecord: function(record) {
return this.getForm().updateRecord(record);
},
/**
* Convenience function for fetching the current value of each field in the form. This is the same as calling
* {@link Ext.form.Basic#getValues this.getForm().getValues()}.
*
* @inheritdoc Ext.form.Basic#getValues
*/
getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) {
return this.getForm().getValues(asString, dirtyOnly, includeEmptyText, useDataValues);
},
/**
* Convenience function to check if the form has any dirty fields. This is the same as calling
* {@link Ext.form.Basic#isDirty this.getForm().isDirty()}.
*
* @inheritdoc Ext.form.Basic#isDirty
*/
isDirty: function () {
return this.form.isDirty();
},
/**
* Convenience function to check if the form has all valid fields. This is the same as calling
* {@link Ext.form.Basic#isValid this.getForm().isValid()}.
*
* @inheritdoc Ext.form.Basic#isValid
*/
isValid: function () {
return this.form.isValid();
},
/**
* Convenience function to check if the form has any invalid fields. This is the same as calling
* {@link Ext.form.Basic#hasInvalidField this.getForm().hasInvalidField()}.
*
* @inheritdoc Ext.form.Basic#hasInvalidField
*/
hasInvalidField: function () {
return this.form.hasInvalidField();
},
beforeDestroy: function() {
this.stopPolling();
this.form.destroy();
this.callParent();
},
/**
* This is a proxy for the underlying BasicForm's {@link Ext.form.Basic#load} call.
* @param {Object} options The options to pass to the action (see {@link Ext.form.Basic#load} and
* {@link Ext.form.Basic#doAction} for details)
*/
load: function(options) {
this.form.load(options);
},
/**
* This is a proxy for the underlying BasicForm's {@link Ext.form.Basic#submit} call.
* @param {Object} options The options to pass to the action (see {@link Ext.form.Basic#submit} and
* {@link Ext.form.Basic#doAction} for details)
*/
submit: function(options) {
this.form.submit(options);
},
/**
* Start an interval task to continuously poll all the fields in the form for changes in their
* values. This is normally started automatically by setting the {@link #pollForChanges} config.
* @param {Number} interval The interval in milliseconds at which the check should run.
*/
startPolling: function(interval) {
this.stopPolling();
var task = new Ext.util.TaskRunner(interval);
task.start({
interval: 0,
run: this.checkChange,
scope: this
});
this.pollTask = task;
},
/**
* Stop a running interval task that was started by {@link #startPolling}.
*/
stopPolling: function() {
var task = this.pollTask;
if (task) {
task.stopAll();
delete this.pollTask;
}
},
/**
* Forces each field within the form panel to
* {@link Ext.form.field.Field#checkChange check if its value has changed}.
*/
checkChange: function() {
var fields = this.form.getFields().items,
f,
fLen = fields.length;
for (f = 0; f < fLen; f++) {
fields[f].checkChange();
}
}
});
|
ajax/libs/yasgui/1.0.0/yasgui.min.js | upgle/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASGUI=e()}}(function(){var e;return function t(e,n,r){function i(s,a){if(!n[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var p=n[s]={exports:{}};e[s][0].call(p.exports,function(t){var n=e[s][1][t];return i(n?n:t)},p,p.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t){t.exports=e("./main.js")},{"./main.js":92}],2:[function(e,t){function n(){this._events=this._events||{};this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function i(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=n;n.EventEmitter=n;n.prototype._events=void 0;n.prototype._maxListeners=void 0;n.defaultMaxListeners=10;n.prototype.setMaxListeners=function(e){if(!i(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");this._maxListeners=e;return this};n.prototype.emit=function(e){var t,n,i,a,l,u;this._events||(this._events={});if("error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){t=arguments[1];if(t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}n=this._events[e];if(s(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:i=arguments.length;a=new Array(i-1);for(l=1;i>l;l++)a[l-1]=arguments[l];n.apply(this,a)}else if(o(n)){i=arguments.length;a=new Array(i-1);for(l=1;i>l;l++)a[l-1]=arguments[l];u=n.slice();i=u.length;for(l=0;i>l;l++)u[l].apply(this,a)}return!0};n.prototype.addListener=function(e,t){var i;if(!r(t))throw TypeError("listener must be a function");this._events||(this._events={});this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t);this._events[e]?o(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t;if(o(this._events[e])&&!this._events[e].warned){var i;i=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners;if(i&&i>0&&this._events[e].length>i){this._events[e].warned=!0;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length);"function"==typeof console.trace&&console.trace()}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(e,t){function n(){this.removeListener(e,n);if(!i){i=!0;t.apply(this,arguments)}}if(!r(t))throw TypeError("listener must be a function");var i=!1;n.listener=t;this.on(e,n);return this};n.prototype.removeListener=function(e,t){var n,i,s,a;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;n=this._events[e];s=n.length;i=-1;if(n===t||r(n.listener)&&n.listener===t){delete this._events[e];this._events.removeListener&&this.emit("removeListener",e,t)}else if(o(n)){for(a=s;a-->0;)if(n[a]===t||n[a].listener&&n[a].listener===t){i=a;break}if(0>i)return this;if(1===n.length){n.length=0;delete this._events[e]}else n.splice(i,1);this._events.removeListener&&this.emit("removeListener",e,t)}return this};n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener){0===arguments.length?this._events={}:this._events[e]&&delete this._events[e];return this}if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);this.removeAllListeners("removeListener");this._events={};return this}n=this._events[e];if(r(n))this.removeListener(e,n);else for(;n.length;)this.removeListener(e,n[n.length-1]);delete this._events[e];return this};n.prototype.listeners=function(e){var t;t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[];return t};n.listenerCount=function(e,t){var n;n=e._events&&e._events[t]?r(e._events[t])?1:e._events[t].length:0;return n}},{}],3:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();(function(e,t){function n(e,t,n){return[parseFloat(e[0])*(f.test(e[0])?t/100:1),parseFloat(e[1])*(f.test(e[1])?n/100:1)]}function r(t,n){return parseInt(e.css(t,n),10)||0}function i(t){var n=t[0];return 9===n.nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(n)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:n.preventDefault?{width:0,height:0,offset:{top:n.pageY,left:n.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var o,s=Math.max,a=Math.abs,l=Math.round,u=/left|center|right/,p=/top|center|bottom/,c=/[\+\-]\d+(\.[\d]+)?%?/,d=/^\w+/,f=/%$/,h=e.fn.position;e.position={scrollbarWidth:function(){if(o!==t)return o;var n,r,i=e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),s=i.children()[0];e("body").append(i);n=s.offsetWidth;i.css("overflow","scroll");r=s.offsetWidth;n===r&&(r=i[0].clientWidth);i.remove();return o=n-r},getScrollInfo:function(t){var n=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),r=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),i="scroll"===n||"auto"===n&&t.width<t.element[0].scrollWidth,o="scroll"===r||"auto"===r&&t.height<t.element[0].scrollHeight;return{width:o?e.position.scrollbarWidth():0,height:i?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]),i=!!n[0]&&9===n[0].nodeType;return{element:n,isWindow:r,isDocument:i,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r?n.width():n.outerWidth(),height:r?n.height():n.outerHeight()}}};e.fn.position=function(t){if(!t||!t.of)return h.apply(this,arguments);t=e.extend({},t);var o,f,g,m,E,v,x=e(t.of),y=e.position.getWithinInfo(t.within),N=e.position.getScrollInfo(y),I=(t.collision||"flip").split(" "),A={};v=i(x);x[0].preventDefault&&(t.at="left top");f=v.width;g=v.height;m=v.offset;E=e.extend({},m);e.each(["my","at"],function(){var e,n,r=(t[this]||"").split(" ");1===r.length&&(r=u.test(r[0])?r.concat(["center"]):p.test(r[0])?["center"].concat(r):["center","center"]);r[0]=u.test(r[0])?r[0]:"center";r[1]=p.test(r[1])?r[1]:"center";e=c.exec(r[0]);n=c.exec(r[1]);A[this]=[e?e[0]:0,n?n[0]:0];t[this]=[d.exec(r[0])[0],d.exec(r[1])[0]]});1===I.length&&(I[1]=I[0]);"right"===t.at[0]?E.left+=f:"center"===t.at[0]&&(E.left+=f/2);"bottom"===t.at[1]?E.top+=g:"center"===t.at[1]&&(E.top+=g/2);o=n(A.at,f,g);E.left+=o[0];E.top+=o[1];return this.each(function(){var i,u,p=e(this),c=p.outerWidth(),d=p.outerHeight(),h=r(this,"marginLeft"),v=r(this,"marginTop"),T=c+h+r(this,"marginRight")+N.width,L=d+v+r(this,"marginBottom")+N.height,S=e.extend({},E),C=n(A.my,p.outerWidth(),p.outerHeight());"right"===t.my[0]?S.left-=c:"center"===t.my[0]&&(S.left-=c/2);"bottom"===t.my[1]?S.top-=d:"center"===t.my[1]&&(S.top-=d/2);S.left+=C[0];S.top+=C[1];if(!e.support.offsetFractions){S.left=l(S.left);S.top=l(S.top)}i={marginLeft:h,marginTop:v};e.each(["left","top"],function(n,r){e.ui.position[I[n]]&&e.ui.position[I[n]][r](S,{targetWidth:f,targetHeight:g,elemWidth:c,elemHeight:d,collisionPosition:i,collisionWidth:T,collisionHeight:L,offset:[o[0]+C[0],o[1]+C[1]],my:t.my,at:t.at,within:y,elem:p})});t.using&&(u=function(e){var n=m.left-S.left,r=n+f-c,i=m.top-S.top,o=i+g-d,l={target:{element:x,left:m.left,top:m.top,width:f,height:g},element:{element:p,left:S.left,top:S.top,width:c,height:d},horizontal:0>r?"left":n>0?"right":"center",vertical:0>o?"top":i>0?"bottom":"middle"};c>f&&a(n+r)<f&&(l.horizontal="center");d>g&&a(i+o)<g&&(l.vertical="middle");l.important=s(a(n),a(r))>s(a(i),a(o))?"horizontal":"vertical";t.using.call(this,e,l)});p.offset(e.extend(S,{using:u}))})};e.ui.position={fit:{left:function(e,t){var n,r=t.within,i=r.isWindow?r.scrollLeft:r.offset.left,o=r.width,a=e.left-t.collisionPosition.marginLeft,l=i-a,u=a+t.collisionWidth-o-i;if(t.collisionWidth>o)if(l>0&&0>=u){n=e.left+l+t.collisionWidth-o-i;e.left+=l-n}else e.left=u>0&&0>=l?i:l>u?i+o-t.collisionWidth:i;else l>0?e.left+=l:u>0?e.left-=u:e.left=s(e.left-a,e.left)},top:function(e,t){var n,r=t.within,i=r.isWindow?r.scrollTop:r.offset.top,o=t.within.height,a=e.top-t.collisionPosition.marginTop,l=i-a,u=a+t.collisionHeight-o-i;if(t.collisionHeight>o)if(l>0&&0>=u){n=e.top+l+t.collisionHeight-o-i;e.top+=l-n}else e.top=u>0&&0>=l?i:l>u?i+o-t.collisionHeight:i;else l>0?e.top+=l:u>0?e.top-=u:e.top=s(e.top-a,e.top)}},flip:{left:function(e,t){var n,r,i=t.within,o=i.offset.left+i.scrollLeft,s=i.width,l=i.isWindow?i.scrollLeft:i.offset.left,u=e.left-t.collisionPosition.marginLeft,p=u-l,c=u+t.collisionWidth-s-l,d="left"===t.my[0]?-t.elemWidth:"right"===t.my[0]?t.elemWidth:0,f="left"===t.at[0]?t.targetWidth:"right"===t.at[0]?-t.targetWidth:0,h=-2*t.offset[0];if(0>p){n=e.left+d+f+h+t.collisionWidth-s-o;(0>n||n<a(p))&&(e.left+=d+f+h)}else if(c>0){r=e.left-t.collisionPosition.marginLeft+d+f+h-l;(r>0||a(r)<c)&&(e.left+=d+f+h)}},top:function(e,t){var n,r,i=t.within,o=i.offset.top+i.scrollTop,s=i.height,l=i.isWindow?i.scrollTop:i.offset.top,u=e.top-t.collisionPosition.marginTop,p=u-l,c=u+t.collisionHeight-s-l,d="top"===t.my[1],f=d?-t.elemHeight:"bottom"===t.my[1]?t.elemHeight:0,h="top"===t.at[1]?t.targetHeight:"bottom"===t.at[1]?-t.targetHeight:0,g=-2*t.offset[1];if(0>p){r=e.top+f+h+g+t.collisionHeight-s-o;e.top+f+h+g>p&&(0>r||r<a(p))&&(e.top+=f+h+g)}else if(c>0){n=e.top-t.collisionPosition.marginTop+f+h+g-l;e.top+f+h+g>c&&(n>0||a(n)<c)&&(e.top+=f+h+g)}}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments);e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments);e.ui.position.fit.top.apply(this,arguments)}}};(function(){var t,n,r,i,o,s=document.getElementsByTagName("body")[0],a=document.createElement("div");t=document.createElement(s?"div":"body");r={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"};s&&e.extend(r,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in r)t.style[o]=r[o];t.appendChild(a);n=s||document.documentElement;n.insertBefore(t,n.firstChild);a.style.cssText="position: absolute; left: 10.7432222px;";i=e(a).offset().left;e.support.offsetFractions=i>10&&11>i;t.innerHTML="";n.removeChild(t)})()})(t)},{jquery:void 0}],4:[function(t,n,r){(function(t,i){"function"==typeof e&&e.amd?e(i):"object"==typeof r?n.exports=i():t.MicroPlugin=i()})(this,function(){var e={};e.mixin=function(e){e.plugins={};e.prototype.initializePlugins=function(e){var n,r,i,o=this,s=[];o.plugins={names:[],settings:{},requested:{},loaded:{}};if(t.isArray(e))for(n=0,r=e.length;r>n;n++)if("string"==typeof e[n])s.push(e[n]);else{o.plugins.settings[e[n].name]=e[n].options;s.push(e[n].name)}else if(e)for(i in e)if(e.hasOwnProperty(i)){o.plugins.settings[i]=e[i];s.push(i)}for(;s.length;)o.require(s.shift())};e.prototype.loadPlugin=function(t){var n=this,r=n.plugins,i=e.plugins[t];if(!e.plugins.hasOwnProperty(t))throw new Error('Unable to find "'+t+'" plugin');r.requested[t]=!0;r.loaded[t]=i.fn.apply(n,[n.plugins.settings[t]||{}]);r.names.push(t)};e.prototype.require=function(e){var t=this,n=t.plugins;if(!t.plugins.loaded.hasOwnProperty(e)){if(n.requested[e])throw new Error('Plugin has circular dependency ("'+e+'")');t.loadPlugin(e)}return n.loaded[e]};e.define=function(t,n){e.plugins[t]={name:t,fn:n}}};var t={isArray:Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}};return e})},{}],5:[function(t,n,r){(function(i,o){"function"==typeof e&&e.amd?e(["jquery","sifter","microplugin"],o):"object"==typeof r?n.exports=o(function(){try{return t("jquery")}catch(e){return window.jQuery}}(),t("sifter"),t("microplugin")):i.Selectize=o(i.jQuery,i.Sifter,i.MicroPlugin)})(this,function(e,t,n){"use strict";var r=function(e,t){if("string"!=typeof t||t.length){var n="string"==typeof t?new RegExp(t,"i"):t,r=function(e){var t=0;if(3===e.nodeType){var i=e.data.search(n);if(i>=0&&e.data.length>0){var o=e.data.match(n),s=document.createElement("span");s.className="highlight";var a=e.splitText(i),l=(a.splitText(o[0].length),a.cloneNode(!0));s.appendChild(l);a.parentNode.replaceChild(s,a);t=1}}else if(1===e.nodeType&&e.childNodes&&!/(script|style)/i.test(e.tagName))for(var u=0;u<e.childNodes.length;++u)u+=r(e.childNodes[u]);return t};return e.each(function(){r(this)})}},i=function(){};i.prototype={on:function(e,t){this._events=this._events||{};this._events[e]=this._events[e]||[];this._events[e].push(t)},off:function(e,t){var n=arguments.length;if(0===n)return delete this._events;if(1===n)return delete this._events[e];this._events=this._events||{};e in this._events!=!1&&this._events[e].splice(this._events[e].indexOf(t),1)},trigger:function(e){this._events=this._events||{};if(e in this._events!=!1)for(var t=0;t<this._events[e].length;t++)this._events[e][t].apply(this,Array.prototype.slice.call(arguments,1))}};i.mixin=function(e){for(var t=["on","off","trigger"],n=0;n<t.length;n++)e.prototype[t[n]]=i.prototype[t[n]]};var o=/Mac/.test(navigator.userAgent),s=65,a=13,l=27,u=37,p=38,c=80,d=39,f=40,h=78,g=8,m=46,E=16,v=o?91:17,x=o?18:17,y=9,N=1,I=2,A=function(e){return"undefined"!=typeof e},T=function(e){return"undefined"==typeof e||null===e?null:"boolean"==typeof e?e?"1":"0":e+""},L=function(e){return(e+"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")},S=function(e){return(e+"").replace(/\$/g,"$$$$")},C={};C.before=function(e,t,n){var r=e[t];e[t]=function(){n.apply(e,arguments);return r.apply(e,arguments)}};C.after=function(e,t,n){var r=e[t];e[t]=function(){var t=r.apply(e,arguments);n.apply(e,arguments);return t}};var b=function(t,n){if(!e.isArray(n))return n;var r,i,o={};for(r=0,i=n.length;i>r;r++)n[r].hasOwnProperty(t)&&(o[n[r][t]]=n[r]);return o},R=function(e){var t=!1;return function(){if(!t){t=!0;e.apply(this,arguments)}}},w=function(e,t){var n;return function(){var r=this,i=arguments;window.clearTimeout(n);n=window.setTimeout(function(){e.apply(r,i)},t)}},O=function(e,t,n){var r,i=e.trigger,o={};e.trigger=function(){var n=arguments[0];if(-1===t.indexOf(n))return i.apply(e,arguments);o[n]=arguments;return void 0};n.apply(e,[]);e.trigger=i;for(r in o)o.hasOwnProperty(r)&&i.apply(e,o[r])},_=function(e,t,n,r){e.on(t,n,function(t){for(var n=t.target;n&&n.parentNode!==e[0];)n=n.parentNode;t.currentTarget=n;return r.apply(this,[t])})},F=function(e){var t={};if("selectionStart"in e){t.start=e.selectionStart;t.length=e.selectionEnd-t.start}else if(document.selection){e.focus();var n=document.selection.createRange(),r=document.selection.createRange().text.length;n.moveStart("character",-e.value.length);t.start=n.text.length-r;t.length=r}return t},P=function(e,t,n){var r,i,o={};if(n)for(r=0,i=n.length;i>r;r++)o[n[r]]=e.css(n[r]);else o=e.css();t.css(o)},M=function(t,n){if(!t)return 0;var r=e("<test>").css({position:"absolute",top:-99999,left:-99999,width:"auto",padding:0,whiteSpace:"pre"}).text(t).appendTo("body");P(n,r,["letterSpacing","fontSize","fontFamily","fontWeight","textTransform"]);var i=r.width();r.remove();return i},k=function(e){var t=null,n=function(n,r){var i,o,s,a,l,u,p,c;n=n||window.event||{};r=r||{};if(!n.metaKey&&!n.altKey&&(r.force||e.data("grow")!==!1)){i=e.val();if(n.type&&"keydown"===n.type.toLowerCase()){o=n.keyCode;s=o>=97&&122>=o||o>=65&&90>=o||o>=48&&57>=o||32===o;if(o===m||o===g){c=F(e[0]);c.length?i=i.substring(0,c.start)+i.substring(c.start+c.length):o===g&&c.start?i=i.substring(0,c.start-1)+i.substring(c.start+1):o===m&&"undefined"!=typeof c.start&&(i=i.substring(0,c.start)+i.substring(c.start+1))}else if(s){u=n.shiftKey;p=String.fromCharCode(n.keyCode);p=u?p.toUpperCase():p.toLowerCase();i+=p}}a=e.attr("placeholder");!i&&a&&(i=a);l=M(i,e)+4;if(l!==t){t=l;e.width(l);e.triggerHandler("resize")}}};e.on("keydown keyup update blur",n);n()},D=function(n,r){var i,o,s=this;o=n[0];o.selectize=s;var a=window.getComputedStyle&&window.getComputedStyle(o,null);i=a?a.getPropertyValue("direction"):o.currentStyle&&o.currentStyle.direction;i=i||n.parents("[dir]:first").attr("dir")||"";e.extend(s,{settings:r,$input:n,tagType:"select"===o.tagName.toLowerCase()?N:I,rtl:/rtl/i.test(i),eventNS:".selectize"+ ++D.count,highlightedValue:null,isOpen:!1,isDisabled:!1,isRequired:n.is("[required]"),isInvalid:!1,isLocked:!1,isFocused:!1,isInputHidden:!1,isSetup:!1,isShiftDown:!1,isCmdDown:!1,isCtrlDown:!1,ignoreFocus:!1,ignoreBlur:!1,ignoreHover:!1,hasOptions:!1,currentResults:null,lastValue:"",caretPos:0,loading:0,loadedSearches:{},$activeOption:null,$activeItems:[],optgroups:{},options:{},userOptions:{},items:[],renderCache:{},onSearchChange:null===r.loadThrottle?s.onSearchChange:w(s.onSearchChange,r.loadThrottle)});s.sifter=new t(this.options,{diacritics:r.diacritics});e.extend(s.options,b(r.valueField,r.options));delete s.settings.options;e.extend(s.optgroups,b(r.optgroupValueField,r.optgroups));delete s.settings.optgroups;s.settings.mode=s.settings.mode||(1===s.settings.maxItems?"single":"multi");"boolean"!=typeof s.settings.hideSelected&&(s.settings.hideSelected="multi"===s.settings.mode);s.initializePlugins(s.settings.plugins);s.setupCallbacks();s.setupTemplates();s.setup()};i.mixin(D);n.mixin(D);e.extend(D.prototype,{setup:function(){var t,n,r,i,s,a,l,u,p,c,d=this,f=d.settings,h=d.eventNS,g=e(window),m=e(document),y=d.$input;l=d.settings.mode;u=y.attr("tabindex")||"";p=y.attr("class")||"";t=e("<div>").addClass(f.wrapperClass).addClass(p).addClass(l);n=e("<div>").addClass(f.inputClass).addClass("items").appendTo(t);r=e('<input type="text" autocomplete="off" />').appendTo(n).attr("tabindex",u);a=e(f.dropdownParent||t);i=e("<div>").addClass(f.dropdownClass).addClass(l).hide().appendTo(a);s=e("<div>").addClass(f.dropdownContentClass).appendTo(i);d.settings.copyClassesToDropdown&&i.addClass(p);t.css({width:y[0].style.width});if(d.plugins.names.length){c="plugin-"+d.plugins.names.join(" plugin-");t.addClass(c);i.addClass(c)}(null===f.maxItems||f.maxItems>1)&&d.tagType===N&&y.attr("multiple","multiple");d.settings.placeholder&&r.attr("placeholder",f.placeholder);y.attr("autocorrect")&&r.attr("autocorrect",y.attr("autocorrect"));y.attr("autocapitalize")&&r.attr("autocapitalize",y.attr("autocapitalize"));d.$wrapper=t;d.$control=n;d.$control_input=r;d.$dropdown=i;d.$dropdown_content=s;i.on("mouseenter","[data-selectable]",function(){return d.onOptionHover.apply(d,arguments)});i.on("mousedown","[data-selectable]",function(){return d.onOptionSelect.apply(d,arguments)});_(n,"mousedown","*:not(input)",function(){return d.onItemSelect.apply(d,arguments)});k(r);n.on({mousedown:function(){return d.onMouseDown.apply(d,arguments)},click:function(){return d.onClick.apply(d,arguments)}});r.on({mousedown:function(e){e.stopPropagation()},keydown:function(){return d.onKeyDown.apply(d,arguments)},keyup:function(){return d.onKeyUp.apply(d,arguments)},keypress:function(){return d.onKeyPress.apply(d,arguments)},resize:function(){d.positionDropdown.apply(d,[])},blur:function(){return d.onBlur.apply(d,arguments)},focus:function(){d.ignoreBlur=!1;return d.onFocus.apply(d,arguments)},paste:function(){return d.onPaste.apply(d,arguments)}});m.on("keydown"+h,function(e){d.isCmdDown=e[o?"metaKey":"ctrlKey"];d.isCtrlDown=e[o?"altKey":"ctrlKey"];d.isShiftDown=e.shiftKey});m.on("keyup"+h,function(e){e.keyCode===x&&(d.isCtrlDown=!1);e.keyCode===E&&(d.isShiftDown=!1);e.keyCode===v&&(d.isCmdDown=!1)});m.on("mousedown"+h,function(e){if(d.isFocused){if(e.target===d.$dropdown[0]||e.target.parentNode===d.$dropdown[0])return!1;d.$control.has(e.target).length||e.target===d.$control[0]||d.blur()}});g.on(["scroll"+h,"resize"+h].join(" "),function(){d.isOpen&&d.positionDropdown.apply(d,arguments)});g.on("mousemove"+h,function(){d.ignoreHover=!1});this.revertSettings={$children:y.children().detach(),tabindex:y.attr("tabindex")};y.attr("tabindex",-1).hide().after(d.$wrapper);if(e.isArray(f.items)){d.setValue(f.items);delete f.items}y[0].validity&&y.on("invalid"+h,function(e){e.preventDefault();d.isInvalid=!0;d.refreshState()});d.updateOriginalInput();d.refreshItems();d.refreshState();d.updatePlaceholder();d.isSetup=!0;y.is(":disabled")&&d.disable();d.on("change",this.onChange);y.data("selectize",d);y.addClass("selectized");d.trigger("initialize");f.preload===!0&&d.onSearchChange("")},setupTemplates:function(){var t=this,n=t.settings.labelField,r=t.settings.optgroupLabelField,i={optgroup:function(e){return'<div class="optgroup">'+e.html+"</div>"},optgroup_header:function(e,t){return'<div class="optgroup-header">'+t(e[r])+"</div>"},option:function(e,t){return'<div class="option">'+t(e[n])+"</div>"},item:function(e,t){return'<div class="item">'+t(e[n])+"</div>"},option_create:function(e,t){return'<div class="create">Add <strong>'+t(e.input)+"</strong>…</div>"}};t.settings.render=e.extend({},i,t.settings.render)},setupCallbacks:function(){var e,t,n={initialize:"onInitialize",change:"onChange",item_add:"onItemAdd",item_remove:"onItemRemove",clear:"onClear",option_add:"onOptionAdd",option_remove:"onOptionRemove",option_clear:"onOptionClear",dropdown_open:"onDropdownOpen",dropdown_close:"onDropdownClose",type:"onType",load:"onLoad"};for(e in n)if(n.hasOwnProperty(e)){t=this.settings[n[e]];t&&this.on(e,t)}},onClick:function(e){var t=this;if(!t.isFocused){t.focus();e.preventDefault()}},onMouseDown:function(t){{var n=this,r=t.isDefaultPrevented();e(t.target)}if(n.isFocused){if(t.target!==n.$control_input[0]){"single"===n.settings.mode?n.isOpen?n.close():n.open():r||n.setActiveItem(null);return!1}}else r||window.setTimeout(function(){n.focus()},0)},onChange:function(){this.$input.trigger("change")},onPaste:function(e){var t=this;(t.isFull()||t.isInputHidden||t.isLocked)&&e.preventDefault()},onKeyPress:function(e){if(this.isLocked)return e&&e.preventDefault();var t=String.fromCharCode(e.keyCode||e.which);if(this.settings.create&&t===this.settings.delimiter){this.createItem();e.preventDefault();return!1}},onKeyDown:function(e){var t=(e.target===this.$control_input[0],this);if(t.isLocked)e.keyCode!==y&&e.preventDefault();else{switch(e.keyCode){case s:if(t.isCmdDown){t.selectAll();return}break;case l:t.close();return;case h:if(!e.ctrlKey||e.altKey)break;case f:if(!t.isOpen&&t.hasOptions)t.open();else if(t.$activeOption){t.ignoreHover=!0;var n=t.getAdjacentOption(t.$activeOption,1);n.length&&t.setActiveOption(n,!0,!0)}e.preventDefault();return;case c:if(!e.ctrlKey||e.altKey)break;case p:if(t.$activeOption){t.ignoreHover=!0;var r=t.getAdjacentOption(t.$activeOption,-1);r.length&&t.setActiveOption(r,!0,!0)}e.preventDefault();return;case a:t.isOpen&&t.$activeOption&&t.onOptionSelect({currentTarget:t.$activeOption});e.preventDefault();return;case u:t.advanceSelection(-1,e);return;case d:t.advanceSelection(1,e);return;case y:if(t.settings.selectOnTab&&t.isOpen&&t.$activeOption){t.onOptionSelect({currentTarget:t.$activeOption});e.preventDefault()}t.settings.create&&t.createItem()&&e.preventDefault();return;case g:case m:t.deleteSelection(e);return}!t.isFull()&&!t.isInputHidden||(o?e.metaKey:e.ctrlKey)||e.preventDefault()}},onKeyUp:function(e){var t=this;if(t.isLocked)return e&&e.preventDefault();var n=t.$control_input.val()||"";if(t.lastValue!==n){t.lastValue=n;t.onSearchChange(n);t.refreshOptions();t.trigger("type",n)}},onSearchChange:function(e){var t=this,n=t.settings.load;if(n&&!t.loadedSearches.hasOwnProperty(e)){t.loadedSearches[e]=!0;t.load(function(r){n.apply(t,[e,r])})}},onFocus:function(e){var t=this;t.isFocused=!0;if(t.isDisabled){t.blur();e&&e.preventDefault();return!1}if(!t.ignoreFocus){"focus"===t.settings.preload&&t.onSearchChange("");if(!t.$activeItems.length){t.showInput();t.setActiveItem(null);t.refreshOptions(!!t.settings.openOnFocus)}t.refreshState()}},onBlur:function(e){var t=this;t.isFocused=!1;if(!t.ignoreFocus)if(t.ignoreBlur||document.activeElement!==t.$dropdown_content[0]){t.settings.create&&t.settings.createOnBlur&&t.createItem(!1);t.close();t.setTextboxValue("");t.setActiveItem(null);t.setActiveOption(null);t.setCaret(t.items.length);t.refreshState()}else{t.ignoreBlur=!0;t.onFocus(e)}},onOptionHover:function(e){this.ignoreHover||this.setActiveOption(e.currentTarget,!1)},onOptionSelect:function(t){var n,r,i=this;if(t.preventDefault){t.preventDefault();t.stopPropagation()}r=e(t.currentTarget);if(r.hasClass("create"))i.createItem();else{n=r.attr("data-value");if("undefined"!=typeof n){i.lastQuery=null;i.setTextboxValue("");i.addItem(n);!i.settings.hideSelected&&t.type&&/mouse/.test(t.type)&&i.setActiveOption(i.getOption(n))}}},onItemSelect:function(e){var t=this;if(!t.isLocked&&"multi"===t.settings.mode){e.preventDefault();t.setActiveItem(e.currentTarget,e)}},load:function(e){var t=this,n=t.$wrapper.addClass("loading");t.loading++;e.apply(t,[function(e){t.loading=Math.max(t.loading-1,0);if(e&&e.length){t.addOption(e);t.refreshOptions(t.isFocused&&!t.isInputHidden)}t.loading||n.removeClass("loading");t.trigger("load",e)}])},setTextboxValue:function(e){var t=this.$control_input,n=t.val()!==e;if(n){t.val(e).triggerHandler("update");this.lastValue=e}},getValue:function(){return this.tagType===N&&this.$input.attr("multiple")?this.items:this.items.join(this.settings.delimiter)},setValue:function(e){O(this,["change"],function(){this.clear();this.addItems(e)})},setActiveItem:function(t,n){var r,i,o,s,a,l,u,p,c=this;if("single"!==c.settings.mode){t=e(t);if(t.length){r=n&&n.type.toLowerCase();if("mousedown"===r&&c.isShiftDown&&c.$activeItems.length){p=c.$control.children(".active:last");s=Array.prototype.indexOf.apply(c.$control[0].childNodes,[p[0]]);a=Array.prototype.indexOf.apply(c.$control[0].childNodes,[t[0]]);if(s>a){u=s;s=a;a=u}for(i=s;a>=i;i++){l=c.$control[0].childNodes[i];if(-1===c.$activeItems.indexOf(l)){e(l).addClass("active");c.$activeItems.push(l)}}n.preventDefault()}else if("mousedown"===r&&c.isCtrlDown||"keydown"===r&&this.isShiftDown)if(t.hasClass("active")){o=c.$activeItems.indexOf(t[0]);c.$activeItems.splice(o,1);t.removeClass("active")}else c.$activeItems.push(t.addClass("active")[0]);else{e(c.$activeItems).removeClass("active");c.$activeItems=[t.addClass("active")[0]]}c.hideInput();this.isFocused||c.focus()}else{e(c.$activeItems).removeClass("active");c.$activeItems=[];c.isFocused&&c.showInput()}}},setActiveOption:function(t,n,r){var i,o,s,a,l,u=this;u.$activeOption&&u.$activeOption.removeClass("active");u.$activeOption=null;t=e(t);if(t.length){u.$activeOption=t.addClass("active");if(n||!A(n)){i=u.$dropdown_content.height();o=u.$activeOption.outerHeight(!0);n=u.$dropdown_content.scrollTop()||0;s=u.$activeOption.offset().top-u.$dropdown_content.offset().top+n;a=s;l=s-i+o;s+o>i+n?u.$dropdown_content.stop().animate({scrollTop:l},r?u.settings.scrollDuration:0):n>s&&u.$dropdown_content.stop().animate({scrollTop:a},r?u.settings.scrollDuration:0)}}},selectAll:function(){var e=this;if("single"!==e.settings.mode){e.$activeItems=Array.prototype.slice.apply(e.$control.children(":not(input)").addClass("active"));if(e.$activeItems.length){e.hideInput();e.close()}e.focus()}},hideInput:function(){var e=this;e.setTextboxValue("");e.$control_input.css({opacity:0,position:"absolute",left:e.rtl?1e4:-1e4});e.isInputHidden=!0},showInput:function(){this.$control_input.css({opacity:1,position:"relative",left:0});this.isInputHidden=!1},focus:function(){var e=this;if(!e.isDisabled){e.ignoreFocus=!0;e.$control_input[0].focus();window.setTimeout(function(){e.ignoreFocus=!1;e.onFocus()},0)}},blur:function(){this.$control_input.trigger("blur")},getScoreFunction:function(e){return this.sifter.getScoreFunction(e,this.getSearchOptions())},getSearchOptions:function(){var e=this.settings,t=e.sortField;"string"==typeof t&&(t={field:t});return{fields:e.searchField,conjunction:e.searchConjunction,sort:t}},search:function(t){var n,r,i,o=this,s=o.settings,a=this.getSearchOptions();if(s.score){i=o.settings.score.apply(this,[t]);if("function"!=typeof i)throw new Error('Selectize "score" setting must be a function that returns a function')}if(t!==o.lastQuery){o.lastQuery=t;r=o.sifter.search(t,e.extend(a,{score:i}));o.currentResults=r}else r=e.extend(!0,{},o.currentResults);if(s.hideSelected)for(n=r.items.length-1;n>=0;n--)-1!==o.items.indexOf(T(r.items[n].id))&&r.items.splice(n,1);return r},refreshOptions:function(t){var n,i,o,s,a,l,u,p,c,d,f,h,g,m,E,v;"undefined"==typeof t&&(t=!0);var x=this,y=e.trim(x.$control_input.val()),N=x.search(y),I=x.$dropdown_content,A=x.$activeOption&&T(x.$activeOption.attr("data-value"));s=N.items.length;"number"==typeof x.settings.maxOptions&&(s=Math.min(s,x.settings.maxOptions));a={};if(x.settings.optgroupOrder){l=x.settings.optgroupOrder;for(n=0;n<l.length;n++)a[l[n]]=[]}else l=[];for(n=0;s>n;n++){u=x.options[N.items[n].id];p=x.render("option",u);c=u[x.settings.optgroupField]||"";d=e.isArray(c)?c:[c];for(i=0,o=d&&d.length;o>i;i++){c=d[i];x.optgroups.hasOwnProperty(c)||(c="");if(!a.hasOwnProperty(c)){a[c]=[];l.push(c)}a[c].push(p)}}f=[];for(n=0,s=l.length;s>n;n++){c=l[n];if(x.optgroups.hasOwnProperty(c)&&a[c].length){h=x.render("optgroup_header",x.optgroups[c])||"";h+=a[c].join("");f.push(x.render("optgroup",e.extend({},x.optgroups[c],{html:h})))}else f.push(a[c].join(""))}I.html(f.join(""));if(x.settings.highlight&&N.query.length&&N.tokens.length)for(n=0,s=N.tokens.length;s>n;n++)r(I,N.tokens[n].regex);if(!x.settings.hideSelected)for(n=0,s=x.items.length;s>n;n++)x.getOption(x.items[n]).addClass("selected");g=x.canCreate(y);if(g){I.prepend(x.render("option_create",{input:y}));v=e(I[0].childNodes[0])}x.hasOptions=N.items.length>0||g;if(x.hasOptions){if(N.items.length>0){E=A&&x.getOption(A);E&&E.length?m=E:"single"===x.settings.mode&&x.items.length&&(m=x.getOption(x.items[0]));m&&m.length||(m=v&&!x.settings.addPrecedence?x.getAdjacentOption(v,1):I.find("[data-selectable]:first"))}else m=v;x.setActiveOption(m);t&&!x.isOpen&&x.open()}else{x.setActiveOption(null);t&&x.isOpen&&x.close()}},addOption:function(t){var n,r,i,o=this;if(e.isArray(t))for(n=0,r=t.length;r>n;n++)o.addOption(t[n]);else{i=T(t[o.settings.valueField]);if("string"==typeof i&&!o.options.hasOwnProperty(i)){o.userOptions[i]=!0;o.options[i]=t;o.lastQuery=null;o.trigger("option_add",i,t)}}},addOptionGroup:function(e,t){this.optgroups[e]=t;this.trigger("optgroup_add",e,t)},updateOption:function(t,n){var r,i,o,s,a,l,u=this;t=T(t);o=T(n[u.settings.valueField]);if(null!==t&&u.options.hasOwnProperty(t)){if("string"!=typeof o)throw new Error("Value must be set in option data");if(o!==t){delete u.options[t];s=u.items.indexOf(t);-1!==s&&u.items.splice(s,1,o)}u.options[o]=n;a=u.renderCache.item;l=u.renderCache.option;if(a){delete a[t];delete a[o]}if(l){delete l[t];delete l[o]}if(-1!==u.items.indexOf(o)){r=u.getItem(t);i=e(u.render("item",n));r.hasClass("active")&&i.addClass("active");r.replaceWith(i)}u.lastQuery=null;u.isOpen&&u.refreshOptions(!1)}},removeOption:function(e){var t=this;e=T(e);var n=t.renderCache.item,r=t.renderCache.option;n&&delete n[e];r&&delete r[e];delete t.userOptions[e];delete t.options[e];t.lastQuery=null;t.trigger("option_remove",e);t.removeItem(e)},clearOptions:function(){var e=this;e.loadedSearches={};e.userOptions={};e.renderCache={};e.options=e.sifter.items={};e.lastQuery=null;e.trigger("option_clear");e.clear()},getOption:function(e){return this.getElementWithValue(e,this.$dropdown_content.find("[data-selectable]"))},getAdjacentOption:function(t,n){var r=this.$dropdown.find("[data-selectable]"),i=r.index(t)+n;return i>=0&&i<r.length?r.eq(i):e()},getElementWithValue:function(t,n){t=T(t);if("undefined"!=typeof t&&null!==t)for(var r=0,i=n.length;i>r;r++)if(n[r].getAttribute("data-value")===t)return e(n[r]);
return e()},getItem:function(e){return this.getElementWithValue(e,this.$control.children())},addItems:function(t){for(var n=e.isArray(t)?t:[t],r=0,i=n.length;i>r;r++){this.isPending=i-1>r;this.addItem(n[r])}},addItem:function(t){O(this,["change"],function(){var n,r,i,o,s,a=this,l=a.settings.mode;t=T(t);if(-1===a.items.indexOf(t)){if(a.options.hasOwnProperty(t)){"single"===l&&a.clear();if("multi"!==l||!a.isFull()){n=e(a.render("item",a.options[t]));s=a.isFull();a.items.splice(a.caretPos,0,t);a.insertAtCaret(n);(!a.isPending||!s&&a.isFull())&&a.refreshState();if(a.isSetup){i=a.$dropdown_content.find("[data-selectable]");if(!a.isPending){r=a.getOption(t);o=a.getAdjacentOption(r,1).attr("data-value");a.refreshOptions(a.isFocused&&"single"!==l);o&&a.setActiveOption(a.getOption(o))}!i.length||a.isFull()?a.close():a.positionDropdown();a.updatePlaceholder();a.trigger("item_add",t,n);a.updateOriginalInput()}}}}else"single"===l&&a.close()})},removeItem:function(e){var t,n,r,i=this;t="object"==typeof e?e:i.getItem(e);e=T(t.attr("data-value"));n=i.items.indexOf(e);if(-1!==n){t.remove();if(t.hasClass("active")){r=i.$activeItems.indexOf(t[0]);i.$activeItems.splice(r,1)}i.items.splice(n,1);i.lastQuery=null;!i.settings.persist&&i.userOptions.hasOwnProperty(e)&&i.removeOption(e);n<i.caretPos&&i.setCaret(i.caretPos-1);i.refreshState();i.updatePlaceholder();i.updateOriginalInput();i.positionDropdown();i.trigger("item_remove",e)}},createItem:function(t){var n=this,r=e.trim(n.$control_input.val()||""),i=n.caretPos;if(!n.canCreate(r))return!1;n.lock();"undefined"==typeof t&&(t=!0);var o="function"==typeof n.settings.create?this.settings.create:function(e){var t={};t[n.settings.labelField]=e;t[n.settings.valueField]=e;return t},s=R(function(e){n.unlock();if(e&&"object"==typeof e){var r=T(e[n.settings.valueField]);if("string"==typeof r){n.setTextboxValue("");n.addOption(e);n.setCaret(i);n.addItem(r);n.refreshOptions(t&&"single"!==n.settings.mode)}}}),a=o.apply(this,[r,s]);"undefined"!=typeof a&&s(a);return!0},refreshItems:function(){this.lastQuery=null;if(this.isSetup)for(var e=0;e<this.items.length;e++)this.addItem(this.items);this.refreshState();this.updateOriginalInput()},refreshState:function(){var e,t=this;if(t.isRequired){t.items.length&&(t.isInvalid=!1);t.$control_input.prop("required",e)}t.refreshClasses()},refreshClasses:function(){var t=this,n=t.isFull(),r=t.isLocked;t.$wrapper.toggleClass("rtl",t.rtl);t.$control.toggleClass("focus",t.isFocused).toggleClass("disabled",t.isDisabled).toggleClass("required",t.isRequired).toggleClass("invalid",t.isInvalid).toggleClass("locked",r).toggleClass("full",n).toggleClass("not-full",!n).toggleClass("input-active",t.isFocused&&!t.isInputHidden).toggleClass("dropdown-active",t.isOpen).toggleClass("has-options",!e.isEmptyObject(t.options)).toggleClass("has-items",t.items.length>0);t.$control_input.data("grow",!n&&!r)},isFull:function(){return null!==this.settings.maxItems&&this.items.length>=this.settings.maxItems},updateOriginalInput:function(){var e,t,n,r=this;if(r.tagType===N){n=[];for(e=0,t=r.items.length;t>e;e++)n.push('<option value="'+L(r.items[e])+'" selected="selected"></option>');n.length||this.$input.attr("multiple")||n.push('<option value="" selected="selected"></option>');r.$input.html(n.join(""))}else{r.$input.val(r.getValue());r.$input.attr("value",r.$input.val())}r.isSetup&&r.trigger("change",r.$input.val())},updatePlaceholder:function(){if(this.settings.placeholder){var e=this.$control_input;this.items.length?e.removeAttr("placeholder"):e.attr("placeholder",this.settings.placeholder);e.triggerHandler("update",{force:!0})}},open:function(){var e=this;if(!(e.isLocked||e.isOpen||"multi"===e.settings.mode&&e.isFull())){e.focus();e.isOpen=!0;e.refreshState();e.$dropdown.css({visibility:"hidden",display:"block"});e.positionDropdown();e.$dropdown.css({visibility:"visible"});e.trigger("dropdown_open",e.$dropdown)}},close:function(){var e=this,t=e.isOpen;"single"===e.settings.mode&&e.items.length&&e.hideInput();e.isOpen=!1;e.$dropdown.hide();e.setActiveOption(null);e.refreshState();t&&e.trigger("dropdown_close",e.$dropdown)},positionDropdown:function(){var e=this.$control,t="body"===this.settings.dropdownParent?e.offset():e.position();t.top+=e.outerHeight(!0);this.$dropdown.css({width:e.outerWidth(),top:t.top,left:t.left})},clear:function(){var e=this;if(e.items.length){e.$control.children(":not(input)").remove();e.items=[];e.lastQuery=null;e.setCaret(0);e.setActiveItem(null);e.updatePlaceholder();e.updateOriginalInput();e.refreshState();e.showInput();e.trigger("clear")}},insertAtCaret:function(t){var n=Math.min(this.caretPos,this.items.length);0===n?this.$control.prepend(t):e(this.$control[0].childNodes[n]).before(t);this.setCaret(n+1)},deleteSelection:function(t){var n,r,i,o,s,a,l,u,p,c=this;i=t&&t.keyCode===g?-1:1;o=F(c.$control_input[0]);c.$activeOption&&!c.settings.hideSelected&&(l=c.getAdjacentOption(c.$activeOption,-1).attr("data-value"));s=[];if(c.$activeItems.length){p=c.$control.children(".active:"+(i>0?"last":"first"));a=c.$control.children(":not(input)").index(p);i>0&&a++;for(n=0,r=c.$activeItems.length;r>n;n++)s.push(e(c.$activeItems[n]).attr("data-value"));if(t){t.preventDefault();t.stopPropagation()}}else(c.isFocused||"single"===c.settings.mode)&&c.items.length&&(0>i&&0===o.start&&0===o.length?s.push(c.items[c.caretPos-1]):i>0&&o.start===c.$control_input.val().length&&s.push(c.items[c.caretPos]));if(!s.length||"function"==typeof c.settings.onDelete&&c.settings.onDelete.apply(c,[s])===!1)return!1;"undefined"!=typeof a&&c.setCaret(a);for(;s.length;)c.removeItem(s.pop());c.showInput();c.positionDropdown();c.refreshOptions(!0);if(l){u=c.getOption(l);u.length&&c.setActiveOption(u)}return!0},advanceSelection:function(e,t){var n,r,i,o,s,a,l=this;if(0!==e){l.rtl&&(e*=-1);n=e>0?"last":"first";r=F(l.$control_input[0]);if(l.isFocused&&!l.isInputHidden){o=l.$control_input.val().length;s=0>e?0===r.start&&0===r.length:r.start===o;s&&!o&&l.advanceCaret(e,t)}else{a=l.$control.children(".active:"+n);if(a.length){i=l.$control.children(":not(input)").index(a);l.setActiveItem(null);l.setCaret(e>0?i+1:i)}}}},advanceCaret:function(e,t){var n,r,i=this;if(0!==e){n=e>0?"next":"prev";if(i.isShiftDown){r=i.$control_input[n]();if(r.length){i.hideInput();i.setActiveItem(r);t&&t.preventDefault()}}else i.setCaret(i.caretPos+e)}},setCaret:function(t){var n=this;t="single"===n.settings.mode?n.items.length:Math.max(0,Math.min(n.items.length,t));if(!n.isPending){var r,i,o,s;o=n.$control.children(":not(input)");for(r=0,i=o.length;i>r;r++){s=e(o[r]).detach();t>r?n.$control_input.before(s):n.$control.append(s)}}n.caretPos=t},lock:function(){this.close();this.isLocked=!0;this.refreshState()},unlock:function(){this.isLocked=!1;this.refreshState()},disable:function(){var e=this;e.$input.prop("disabled",!0);e.isDisabled=!0;e.lock()},enable:function(){var e=this;e.$input.prop("disabled",!1);e.isDisabled=!1;e.unlock()},destroy:function(){var t=this,n=t.eventNS,r=t.revertSettings;t.trigger("destroy");t.off();t.$wrapper.remove();t.$dropdown.remove();t.$input.html("").append(r.$children).removeAttr("tabindex").removeClass("selectized").attr({tabindex:r.tabindex}).show();t.$control_input.removeData("grow");t.$input.removeData("selectize");e(window).off(n);e(document).off(n);e(document.body).off(n);delete t.$input[0].selectize},render:function(e,t){var n,r,i="",o=!1,s=this,a=/^[\t ]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;if("option"===e||"item"===e){n=T(t[s.settings.valueField]);o=!!n}if(o){A(s.renderCache[e])||(s.renderCache[e]={});if(s.renderCache[e].hasOwnProperty(n))return s.renderCache[e][n]}i=s.settings.render[e].apply(this,[t,L]);("option"===e||"option_create"===e)&&(i=i.replace(a,"<$1 data-selectable"));if("optgroup"===e){r=t[s.settings.optgroupValueField]||"";i=i.replace(a,'<$1 data-group="'+S(L(r))+'"')}("option"===e||"item"===e)&&(i=i.replace(a,'<$1 data-value="'+S(L(n||""))+'"'));o&&(s.renderCache[e][n]=i);return i},clearCache:function(e){var t=this;"undefined"==typeof e?t.renderCache={}:delete t.renderCache[e]},canCreate:function(e){var t=this;if(!t.settings.create)return!1;var n=t.settings.createFilter;return!(!e.length||"function"==typeof n&&!n.apply(t,[e])||"string"==typeof n&&!new RegExp(n).test(e)||n instanceof RegExp&&!n.test(e))}});D.count=0;D.defaults={plugins:[],delimiter:",",persist:!0,diacritics:!0,create:!1,createOnBlur:!1,createFilter:null,highlight:!0,openOnFocus:!0,maxOptions:1e3,maxItems:null,hideSelected:null,addPrecedence:!1,selectOnTab:!1,preload:!1,allowEmptyOption:!1,scrollDuration:60,loadThrottle:300,dataAttr:"data-data",optgroupField:"optgroup",valueField:"value",labelField:"text",optgroupLabelField:"label",optgroupValueField:"value",optgroupOrder:null,sortField:"$order",searchField:["text"],searchConjunction:"and",mode:null,wrapperClass:"selectize-control",inputClass:"selectize-input",dropdownClass:"selectize-dropdown",dropdownContentClass:"selectize-dropdown-content",dropdownParent:null,copyClassesToDropdown:!0,render:{}};e.fn.selectize=function(t){var n=e.fn.selectize.defaults,r=e.extend({},n,t),i=r.dataAttr,o=r.labelField,s=r.valueField,a=r.optgroupField,l=r.optgroupLabelField,u=r.optgroupValueField,p=function(t,n){var i,a,l,u,p=e.trim(t.val()||"");if(r.allowEmptyOption||p.length){l=p.split(r.delimiter);for(i=0,a=l.length;a>i;i++){u={};u[o]=l[i];u[s]=l[i];n.options[l[i]]=u}n.items=l}},c=function(t,n){var p,c,d,f,h=0,g=n.options,m=function(e){var t=i&&e.attr(i);return"string"==typeof t&&t.length?JSON.parse(t):null},E=function(t,i){var l,u;t=e(t);l=t.attr("value")||"";if(l.length||r.allowEmptyOption)if(g.hasOwnProperty(l))i&&(g[l].optgroup?e.isArray(g[l].optgroup)?g[l].optgroup.push(i):g[l].optgroup=[g[l].optgroup,i]:g[l].optgroup=i);else{u=m(t)||{};u[o]=u[o]||t.text();u[s]=u[s]||l;u[a]=u[a]||i;u.$order=++h;g[l]=u;t.is(":selected")&&n.items.push(l)}},v=function(t){var r,i,o,s,a;t=e(t);o=t.attr("label");if(o){s=m(t)||{};s[l]=o;s[u]=o;n.optgroups[o]=s}a=e("option",t);for(r=0,i=a.length;i>r;r++)E(a[r],o)};n.maxItems=t.attr("multiple")?null:1;f=t.children();for(p=0,c=f.length;c>p;p++){d=f[p].tagName.toLowerCase();"optgroup"===d?v(f[p]):"option"===d&&E(f[p])}};return this.each(function(){if(!this.selectize){var i,o=e(this),s=this.tagName.toLowerCase(),a=o.attr("placeholder")||o.attr("data-placeholder");a||r.allowEmptyOption||(a=o.children('option[value=""]').text());var l={placeholder:a,options:{},optgroups:{},items:[]};"select"===s?c(o,l):p(o,l);i=new D(o,e.extend(!0,{},n,l,t))}})};e.fn.selectize.defaults=D.defaults;D.define("drag_drop",function(){if(!e.fn.sortable)throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');if("multi"===this.settings.mode){var t=this;t.lock=function(){var e=t.lock;return function(){var n=t.$control.data("sortable");n&&n.disable();return e.apply(t,arguments)}}();t.unlock=function(){var e=t.unlock;return function(){var n=t.$control.data("sortable");n&&n.enable();return e.apply(t,arguments)}}();t.setup=function(){var n=t.setup;return function(){n.apply(this,arguments);var r=t.$control.sortable({items:"[data-value]",forcePlaceholderSize:!0,disabled:t.isLocked,start:function(e,t){t.placeholder.css("width",t.helper.css("width"));r.css({overflow:"visible"})},stop:function(){r.css({overflow:"hidden"});var n=t.$activeItems?t.$activeItems.slice():null,i=[];r.children("[data-value]").each(function(){i.push(e(this).attr("data-value"))});t.setValue(i);t.setActiveItem(n)}})}}()}});D.define("dropdown_header",function(t){var n=this;t=e.extend({title:"Untitled",headerClass:"selectize-dropdown-header",titleRowClass:"selectize-dropdown-header-title",labelClass:"selectize-dropdown-header-label",closeClass:"selectize-dropdown-header-close",html:function(e){return'<div class="'+e.headerClass+'"><div class="'+e.titleRowClass+'"><span class="'+e.labelClass+'">'+e.title+'</span><a href="javascript:void(0)" class="'+e.closeClass+'">×</a></div></div>'}},t);n.setup=function(){var r=n.setup;return function(){r.apply(n,arguments);n.$dropdown_header=e(t.html(t));n.$dropdown.prepend(n.$dropdown_header)}}()});D.define("optgroup_columns",function(t){var n=this;t=e.extend({equalizeWidth:!0,equalizeHeight:!0},t);this.getAdjacentOption=function(t,n){var r=t.closest("[data-group]").find("[data-selectable]"),i=r.index(t)+n;return i>=0&&i<r.length?r.eq(i):e()};this.onKeyDown=function(){var e=n.onKeyDown;return function(t){var r,i,o,s;if(!this.isOpen||t.keyCode!==u&&t.keyCode!==d)return e.apply(this,arguments);n.ignoreHover=!0;s=this.$activeOption.closest("[data-group]");r=s.find("[data-selectable]").index(this.$activeOption);s=t.keyCode===u?s.prev("[data-group]"):s.next("[data-group]");o=s.find("[data-selectable]");i=o.eq(Math.min(o.length-1,r));i.length&&this.setActiveOption(i)}}();var r=function(){var e,t=r.width,n=document;if("undefined"==typeof t){e=n.createElement("div");e.innerHTML='<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';e=e.firstChild;n.body.appendChild(e);t=r.width=e.offsetWidth-e.clientWidth;n.body.removeChild(e)}return t},i=function(){var i,o,s,a,l,u,p;p=e("[data-group]",n.$dropdown_content);o=p.length;if(o&&n.$dropdown_content.width()){if(t.equalizeHeight){s=0;for(i=0;o>i;i++)s=Math.max(s,p.eq(i).height());p.css({height:s})}if(t.equalizeWidth){u=n.$dropdown_content.innerWidth()-r();a=Math.round(u/o);p.css({width:a});if(o>1){l=u-a*(o-1);p.eq(o-1).css({width:l})}}}};if(t.equalizeHeight||t.equalizeWidth){C.after(this,"positionDropdown",i);C.after(this,"refreshOptions",i)}});D.define("remove_button",function(t){if("single"!==this.settings.mode){t=e.extend({label:"×",title:"Remove",className:"remove",append:!0},t);var n=this,r='<a href="javascript:void(0)" class="'+t.className+'" tabindex="-1" title="'+L(t.title)+'">'+t.label+"</a>",i=function(e,t){var n=e.search(/(<\/[^>]+>\s*)$/);return e.substring(0,n)+t+e.substring(n)};this.setup=function(){var o=n.setup;return function(){if(t.append){var s=n.settings.render.item;n.settings.render.item=function(){return i(s.apply(this,arguments),r)}}o.apply(this,arguments);this.$control.on("click","."+t.className,function(t){t.preventDefault();if(!n.isLocked){var r=e(t.currentTarget).parent();n.setActiveItem(r);n.deleteSelection()&&n.setCaret(n.items.length)}})}}()}});D.define("restore_on_backspace",function(e){var t=this;e.text=e.text||function(e){return e[this.settings.labelField]};this.onKeyDown=function(){var n=t.onKeyDown;return function(t){var r,i;if(t.keyCode===g&&""===this.$control_input.val()&&!this.$activeItems.length){r=this.caretPos-1;if(r>=0&&r<this.items.length){i=this.options[this.items[r]];if(this.deleteSelection(t)){this.setTextboxValue(e.text.apply(this,[i]));this.refreshOptions(!0)}t.preventDefault();return}}return n.apply(this,arguments)}}()});return D})},{jquery:void 0,microplugin:4,sifter:6}],6:[function(t,n,r){(function(t,i){"function"==typeof e&&e.amd?e(i):"object"==typeof r?n.exports=i():t.Sifter=i()})(this,function(){var e=function(e,t){this.items=e;this.settings=t||{diacritics:!0}};e.prototype.tokenize=function(e){e=r(String(e||"").toLowerCase());if(!e||!e.length)return[];var t,n,o,a,l=[],u=e.split(/ +/);for(t=0,n=u.length;n>t;t++){o=i(u[t]);if(this.settings.diacritics)for(a in s)s.hasOwnProperty(a)&&(o=o.replace(new RegExp(a,"g"),s[a]));l.push({string:u[t],regex:new RegExp(o,"i")})}return l};e.prototype.iterator=function(e,t){var n;n=o(e)?Array.prototype.forEach||function(e){for(var t=0,n=this.length;n>t;t++)e(this[t],t,this)}:function(e){for(var t in this)this.hasOwnProperty(t)&&e(this[t],t,this)};n.apply(e,[t])};e.prototype.getScoreFunction=function(e,t){var n,r,i,o;n=this;e=n.prepareSearch(e,t);i=e.tokens;r=e.options.fields;o=i.length;var s=function(e,t){var n,r;if(!e)return 0;e=String(e||"");r=e.search(t.regex);if(-1===r)return 0;n=t.string.length/e.length;0===r&&(n+=.5);return n},a=function(){var e=r.length;return e?1===e?function(e,t){return s(t[r[0]],e)}:function(t,n){for(var i=0,o=0;e>i;i++)o+=s(n[r[i]],t);return o/e}:function(){return 0}}();return o?1===o?function(e){return a(i[0],e)}:"and"===e.options.conjunction?function(e){for(var t,n=0,r=0;o>n;n++){t=a(i[n],e);if(0>=t)return 0;r+=t}return r/o}:function(e){for(var t=0,n=0;o>t;t++)n+=a(i[t],e);return n/o}:function(){return 0}};e.prototype.getSortFunction=function(e,n){var r,i,o,s,a,l,u,p,c,d,f;o=this;e=o.prepareSearch(e,n);f=!e.query&&n.sort_empty||n.sort;c=function(e,t){return"$score"===e?t.score:o.items[t.id][e]};a=[];if(f)for(r=0,i=f.length;i>r;r++)(e.query||"$score"!==f[r].field)&&a.push(f[r]);if(e.query){d=!0;for(r=0,i=a.length;i>r;r++)if("$score"===a[r].field){d=!1;break}d&&a.unshift({field:"$score",direction:"desc"})}else for(r=0,i=a.length;i>r;r++)if("$score"===a[r].field){a.splice(r,1);break}p=[];for(r=0,i=a.length;i>r;r++)p.push("desc"===a[r].direction?-1:1);l=a.length;if(l){if(1===l){s=a[0].field;u=p[0];return function(e,n){return u*t(c(s,e),c(s,n))}}return function(e,n){var r,i,o;for(r=0;l>r;r++){o=a[r].field;i=p[r]*t(c(o,e),c(o,n));if(i)return i}return 0}}return null};e.prototype.prepareSearch=function(e,t){if("object"==typeof e)return e;t=n({},t);var r=t.fields,i=t.sort,s=t.sort_empty;r&&!o(r)&&(t.fields=[r]);i&&!o(i)&&(t.sort=[i]);s&&!o(s)&&(t.sort_empty=[s]);return{options:t,query:String(e||"").toLowerCase(),tokens:this.tokenize(e),total:0,items:[]}};e.prototype.search=function(e,t){var n,r,i,o,s=this;r=this.prepareSearch(e,t);t=r.options;e=r.query;o=t.score||s.getScoreFunction(r);e.length?s.iterator(s.items,function(e,i){n=o(e);(t.filter===!1||n>0)&&r.items.push({score:n,id:i})}):s.iterator(s.items,function(e,t){r.items.push({score:1,id:t})});i=s.getSortFunction(r,t);i&&r.items.sort(i);r.total=r.items.length;"number"==typeof t.limit&&(r.items=r.items.slice(0,t.limit));return r};var t=function(e,t){if("number"==typeof e&&"number"==typeof t)return e>t?1:t>e?-1:0;e=String(e||"").toLowerCase();t=String(t||"").toLowerCase();return e>t?1:t>e?-1:0},n=function(e){var t,n,r,i;for(t=1,n=arguments.length;n>t;t++){i=arguments[t];if(i)for(r in i)i.hasOwnProperty(r)&&(e[r]=i[r])}return e},r=function(e){return(e+"").replace(/^\s+|\s+$|/g,"")},i=function(e){return(e+"").replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")},o=Array.isArray||$&&$.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},s={a:"[aÀÁÂÃÄÅàáâãäåĀā]",c:"[cÇçćĆčČ]",d:"[dđĐďĎ]",e:"[eÈÉÊËèéêëěĚĒē]",i:"[iÌÍÎÏìíîïĪī]",n:"[nÑñňŇ]",o:"[oÒÓÔÕÕÖØòóôõöøŌō]",r:"[rřŘ]",s:"[sŠš]",t:"[tťŤ]",u:"[uÙÚÛÜùúûüůŮŪū]",y:"[yŸÿýÝ]",z:"[zŽž]"};return e})},{}],7:[function(t,n){(function(t){function r(){try{return l in t&&t[l]}catch(e){return!1}}function i(e){return e.replace(/^d/,"___$&").replace(h,"___")}var o,s={},a=t.document,l="localStorage",u="script";s.disabled=!1;s.version="1.3.17";s.set=function(){};s.get=function(){};s.has=function(e){return void 0!==s.get(e)};s.remove=function(){};s.clear=function(){};s.transact=function(e,t,n){if(null==n){n=t;t=null}null==t&&(t={});var r=s.get(e,t);n(r);s.set(e,r)};s.getAll=function(){};s.forEach=function(){};s.serialize=function(e){return JSON.stringify(e)};s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}};if(r()){o=t[l];s.set=function(e,t){if(void 0===t)return s.remove(e);o.setItem(e,s.serialize(t));return t};s.get=function(e,t){var n=s.deserialize(o.getItem(e));return void 0===n?t:n};s.remove=function(e){o.removeItem(e)};s.clear=function(){o.clear()};s.getAll=function(){var e={};s.forEach(function(t,n){e[t]=n});return e};s.forEach=function(e){for(var t=0;t<o.length;t++){var n=o.key(t);e(n,s.get(n))}}}else if(a.documentElement.addBehavior){var p,c;try{c=new ActiveXObject("htmlfile");c.open();c.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');c.close();p=c.w.frames[0].document;o=p.createElement("div")}catch(d){o=a.createElement("div");p=a.body}var f=function(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(o);p.appendChild(o);o.addBehavior("#default#userData");o.load(l);var n=e.apply(s,t);p.removeChild(o);return n}},h=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=f(function(e,t,n){t=i(t);if(void 0===n)return s.remove(t);e.setAttribute(t,s.serialize(n));e.save(l);return n});s.get=f(function(e,t,n){t=i(t);var r=s.deserialize(e.getAttribute(t));return void 0===r?n:r});s.remove=f(function(e,t){t=i(t);e.removeAttribute(t);e.save(l)});s.clear=f(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(l);for(var n,r=0;n=t[r];r++)e.removeAttribute(n.name);e.save(l)});s.getAll=function(){var e={};s.forEach(function(t,n){e[t]=n});return e};s.forEach=f(function(e,t){for(var n,r=e.XMLDocument.documentElement.attributes,i=0;n=r[i];++i)t(n.name,s.deserialize(e.getAttribute(n.name)))})}try{var g="__storejs__";s.set(g,g);s.get(g)!=g&&(s.disabled=!0);s.remove(g)}catch(d){s.disabled=!0}s.enabled=!s.disabled;"undefined"!=typeof n&&n.exports&&this.module!==n?n.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s})(Function("return this")())},{}],8:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.0",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:{name:"Laurens Rietveld"},maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",url:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"},readme:"A simple utils repo for the YASGUI tools\n",readmeFilename:"README.md",_id:"yasgui-utils@1.5.0",dist:{shasum:"56f463556922fe4f0eb97f650bb8cfe9700061a7"},_from:"yasgui-utils@1.5.0",_resolved:"https://registry.npmjs.org/yasgui-utils/-/yasgui-utils-1.5.0.tgz"}},{}],9:[function(e,t){window.console=window.console||{log:function(){}};t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":8,"./storage.js":10,"./svg.js":11}],10:[function(e,t){{var n=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,i){if(t){"string"==typeof i&&(i=r[i]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));n.set(e,{val:t,exp:i,time:(new Date).getTime()})}},remove:function(e){n.remove(e)},get:function(e){var t=n.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}}}},{store:7}],11:[function(e,t){t.exports={draw:function(e,n){if(e){var r=t.exports.getElement(n);r&&(e.append?e.append(r):e.appendChild(r))}},getElement:function(e){if(e&&0==e.indexOf("<svg")){var t=new DOMParser,n=t.parseFromString(e,"text/xml"),r=n.documentElement,i=document.createElement("div");i.className="svgImg";i.appendChild(r);return i}return!1}}},{}],12:[function(e){"use strict";var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.deparam=function(e,n){var r={},i={"true":!0,"false":!1,"null":null};t.each(e.replace(/\+/g," ").split("&"),function(e,o){var s,a=o.split("="),l=decodeURIComponent(a[0]),u=r,p=0,c=l.split("]["),d=c.length-1;if(/\[/.test(c[0])&&/\]$/.test(c[d])){c[d]=c[d].replace(/\]$/,"");c=c.shift().split("[").concat(c);d=c.length-1}else d=0;if(2===a.length){s=decodeURIComponent(a[1]);n&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==i[s]?i[s]:s);if(d)for(;d>=p;p++){l=""===c[p]?u.length:c[p];u=u[l]=d>p?u[l]||(c[p+1]&&isNaN(c[p+1])?{}:[]):s}else t.isArray(r[l])?r[l].push(s):r[l]=void 0!==r[l]?[r[l],s]:s}else l&&(r[l]=n?void 0:"")});return r}},{jquery:void 0}],13:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.defineMode("sparql11",function(e){function t(){var e,t,n="<[^<>\"'|{}^\\\x00- ]*>",r="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",i=r+"|_",o="("+i+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+i+"|[0-9])("+i+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,l="\\$"+s,p="("+r+")((("+o+")|\\.)*("+o+"))?",c="[0-9A-Fa-f]",d="(%"+c+c+")",f="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",h="("+d+"|"+f+")";if("sparql11"==u){e="("+i+"|:|[0-9]|"+h+")(("+o+"|\\.|:|"+h+")*("+o+"|:|"+h+"))?";t="_:("+i+"|[0-9])(("+o+"|\\.)*"+o+")?"}else{e="("+i+"|[0-9])((("+o+")|\\.)*("+o+"))?";t="_:"+e}var g="("+p+")?:",m=g+e,E="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",v="[eE][\\+-]?[0-9]+",x="[0-9]+",y="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",N="(([0-9]+\\.[0-9]*"+v+")|(\\.[0-9]+"+v+")|([0-9]+"+v+"))",I="\\+"+x,A="\\+"+y,T="\\+"+N,L="-"+x,S="-"+y,C="-"+N,b="\\\\[tbnrf\\\\\"']",R="'(([^\\x27\\x5C\\x0A\\x0D])|"+b+")*'",w='"(([^\\x22\\x5C\\x0A\\x0D])|'+b+')*"',O="'''(('|'')?([^'\\\\]|"+b+"))*'''",_='"""(("|"")?([^"\\\\]|'+b+'))*"""',F="[\\x20\\x09\\x0D\\x0A]",P="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",M="("+F+"|("+P+"))*",k="\\("+M+"\\)",D="\\["+M+"\\]",G={terminal:[{name:"WS",regex:new RegExp("^"+F+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+P),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+n),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+l),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+E),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+N),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+y),style:"number"},{name:"INTEGER",regex:new RegExp("^"+x),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+T),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+A),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+I),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+C),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+S),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+L),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+O),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+_),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+R),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+w),style:"string"},{name:"NIL",regex:new RegExp("^"+k),style:"punc"},{name:"ANON",regex:new RegExp("^"+D),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+g),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return G}function n(e){var t=[],n=o[e];if(void 0!=n)for(var r in n)t.push(r.toString());else t.push(e);return t}function r(e,t){function r(){for(var t=null,n=0;n<f.length;++n){t=e.match(f[n].regex,!0,!1);if(t)return{cat:f[n].name,style:f[n].style,text:t[0]}}t=e.match(s,!0,!1);if(t)return{cat:e.current().toUpperCase(),style:"keyword",text:t[0]};t=e.match(a,!0,!1);if(t)return{cat:e.current(),style:"punc",text:t[0]};t=e.match(/^.[A-Za-z0-9]*/,!0,!1);return{cat:"<invalid_token>",style:"error",text:t[0]}}function i(){var n=e.column();t.errorStartPos=n;t.errorEndPos=n+c.text.length}function l(e){null==t.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e||"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e)&&(t.queryType=e)}function u(e){"disallowVars"==e?t.allowVars=!1:"allowVars"==e?t.allowVars=!0:"disallowBnodes"==e?t.allowBnodes=!1:"allowBnodes"==e?t.allowBnodes=!0:"storeProperty"==e&&(t.storeProperty=!0)}function p(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var c=r();if("<invalid_token>"==c.cat){if(1==t.OK){t.OK=!1;i()}t.complete=!1;return c.style}if("WS"==c.cat||"COMMENT"==c.cat){t.possibleCurrent=t.possibleNext;return c.style}for(var d,h=!1,g=c.cat;t.stack.length>0&&g&&t.OK&&!h;){d=t.stack.pop();if(o[d]){var m=o[d][g];if(void 0!=m&&p(d)){for(var E=m.length-1;E>=0;--E)t.stack.push(m[E]);u(d)}else{t.OK=!1;t.complete=!1;i();t.stack.push(d)}}else if(d==g){h=!0;l(d);for(var v=!0,x=t.stack.length;x>0;--x){var y=o[t.stack[x-1]];y&&y.$||(v=!1)}t.complete=v;if(t.storeProperty&&"punc"!=g.cat){t.lastProperty=c.text;t.storeProperty=!1}}else{t.OK=!1;t.complete=!1;i()}}if(!h&&t.OK){t.OK=!1;t.complete=!1;i()}t.possibleCurrent=t.possibleNext;t.possibleNext=n(t.stack[t.stack.length-1]);return c.style}function i(t,n){var r=0,i=t.stack.length-1;if(/^[\}\]\)]/.test(n)){for(var o=n.substr(0,1);i>=0;--i)if(t.stack[i]==o){--i;break}}else{var s=h[t.stack[i]];if(s){r+=s;--i}}for(;i>=0;--i){var s=g[t.stack[i]];s&&(r+=s)}return r*e.indentUnit}var o=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,l=null,u="sparql11",p="sparql11",c=!0,d=t(),f=d.terminal,h={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},g={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1};
return{token:r,startState:function(){return{tokenize:r,OK:!0,complete:c,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:n(p),possibleNext:n(p),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[p]}},indent:i,electricChars:"}])"}});e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:void 0}],14:[function(e,t){var n=t.exports=function(){this.words=0;this.prefixes=0;this.children=[]};n.prototype={insert:function(e,t){if(0!=e.length){var r,i,o=this;void 0===t&&(t=0);if(t!==e.length){o.prefixes++;r=e[t];void 0===o.children[r]&&(o.children[r]=new n);i=o.children[r];i.insert(e,t+1)}else o.words++}},remove:function(e,t){if(0!=e.length){var n,r,i=this;void 0===t&&(t=0);if(void 0!==i)if(t!==e.length){i.prefixes--;n=e[t];r=i.children[n];r.remove(e,t+1)}else i.words--}},update:function(e,t){if(0!=e.length&&0!=t.length){this.remove(e);this.insert(t)}},countWord:function(e,t){if(0==e.length)return 0;var n,r,i=this,o=0;void 0===t&&(t=0);if(t===e.length)return i.words;n=e[t];r=i.children[n];void 0!==r&&(o=r.countWord(e,t+1));return o},countPrefix:function(e,t){if(0==e.length)return 0;var n,r,i=this,o=0;void 0===t&&(t=0);if(t===e.length)return i.prefixes;var n=e[t];r=i.children[n];void 0!==r&&(o=r.countPrefix(e,t+1));return o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,n,r=this,i=[];void 0===e&&(e="");if(void 0===r)return[];r.words>0&&i.push(e);for(t in r.children){n=r.children[t];i=i.concat(n.getAllWords(e+t))}return i},autoComplete:function(e,t){var n,r,i=this;if(0==e.length)return void 0===t?i.getAllWords(e):[];void 0===t&&(t=0);n=e[t];r=i.children[n];return void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1)}}},{}],15:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e){var t=e.getWrapperElement();e.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:t.style.width,height:t.style.height};t.style.width="";t.style.height="auto";t.className+=" CodeMirror-fullscreen";document.documentElement.style.overflow="hidden";e.refresh()}function n(e){var t=e.getWrapperElement();t.className=t.className.replace(/\s*CodeMirror-fullscreen\b/,"");document.documentElement.style.overflow="";var n=e.state.fullScreenRestore;t.style.width=n.width;t.style.height=n.height;window.scrollTo(n.scrollLeft,n.scrollTop);e.refresh()}e.defineOption("fullScreen",!1,function(r,i,o){o==e.Init&&(o=!1);!o!=!i&&(i?t(r):n(r))})})},{codemirror:void 0}],16:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){function t(e,t,r,i){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&a[o.text.charAt(l)]||a[o.text.charAt(++l)];if(!u)return null;var p=">"==u.charAt(1)?1:-1;if(r&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=n(e,s(t.line,l+(p>0?1:0)),p,c||null,i);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:p>0}}function n(e,t,n,r,i){for(var o=i&&i.maxScanLineLength||1e4,l=i&&i.maxScanLines||1e3,u=[],p=i&&i.bracketRegex?i.bracketRegex:/[(){}[\]]/,c=n>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=n){var f=e.getLine(d);if(f){var h=n>0?0:f.length-1,g=n>0?f.length:-1;if(!(f.length>o)){d==t.line&&(h=t.ch-(0>n?1:0));for(;h!=g;h+=n){var m=f.charAt(h);if(p.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,h+1))==r)){var E=a[m];if(">"==E.charAt(1)==n>0)u.push(m);else{if(!u.length)return{pos:s(d,h),ch:m};u.pop()}}}}}}return d-n==(n>0?e.lastLine():e.firstLine())?!1:null}function r(e,n,r){for(var i=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var p=l[u].empty()&&t(e,l[u].head,!1,r);if(p&&e.getLine(p.from.line).length<=i){var c=p.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(p.from,s(p.from.line,p.from.ch+1),{className:c}));p.to&&e.getLine(p.to.line).length<=i&&a.push(e.markText(p.to,s(p.to.line,p.to.ch+1),{className:c}))}}if(a.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!n)return d;setTimeout(d,800)}}function i(e){e.operation(function(){if(l){l();l=null}l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,n,r){r&&r!=e.Init&&t.off("cursorActivity",i);if(n){t.state.matchBrackets="object"==typeof n?n:{};t.on("cursorActivity",i)}});e.defineExtension("matchBrackets",function(){r(this,!0)});e.defineExtension("findMatchingBracket",function(e,n,r){return t(this,e,n,r)});e.defineExtension("scanForBracket",function(e,t,r,i){return n(this,e,t,r,i)})})},{codemirror:void 0}],17:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.registerHelper("fold","brace",function(t,n){function r(r){for(var i=n.ch,l=0;;){var u=0>=i?-1:a.lastIndexOf(r,i-1);if(-1!=u){if(1==l&&u<n.ch)break;o=t.getTokenTypeAt(e.Pos(s,u+1));if(!/^(comment|string)/.test(o))return u+1;i=u-1}else{if(1==l)break;l=1;i=a.length}}}var i,o,s=n.line,a=t.getLine(s),l="{",u="}",i=r("{");if(null==i){l="[",u="]";i=r("[")}if(null!=i){var p,c,d=1,f=t.lastLine();e:for(var h=s;f>=h;++h)for(var g=t.getLine(h),m=h==s?i:0;;){var E=g.indexOf(l,m),v=g.indexOf(u,m);0>E&&(E=g.length);0>v&&(v=g.length);m=Math.min(E,v);if(m==g.length)break;if(t.getTokenTypeAt(e.Pos(h,m+1))==o)if(m==E)++d;else if(!--d){p=h;c=m;break e}++m}if(null!=p&&(s!=p||c!=i))return{from:e.Pos(s,i),to:e.Pos(p,c)}}});e.registerHelper("fold","import",function(t,n){function r(n){if(n<t.firstLine()||n>t.lastLine())return null;var r=t.getTokenAt(e.Pos(n,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(n,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var i=n,o=Math.min(t.lastLine(),n+10);o>=i;++i){var s=t.getLine(i),a=s.indexOf(";");if(-1!=a)return{startCh:r.end,end:e.Pos(i,a)}}}var i,n=n.line,o=r(n);if(!o||r(n-1)||(i=r(n-2))&&i.end.line==n-1)return null;for(var s=o.end;;){var a=r(s.line+1);if(null==a)break;s=a.end}return{from:t.clipPos(e.Pos(n,o.startCh+1)),to:s}});e.registerHelper("fold","include",function(t,n){function r(n){if(n<t.firstLine()||n>t.lastLine())return null;var r=t.getTokenAt(e.Pos(n,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(n,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var n=n.line,i=r(n);if(null==i||null!=r(n-1))return null;for(var o=n;;){var s=r(o+1);if(null==s)break;++o}return{from:e.Pos(n,i+1),to:t.clipPos(e.Pos(o))}})})},{codemirror:void 0}],18:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(t,i,o,s){function a(e){var n=l(t,i);if(!n||n.to.line-n.from.line<u)return null;for(var r=t.findMarksAt(n.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==s){if(!e)return null;n.cleared=!0;r[o].clear()}return n}if(o&&o.call){var l=o;o=null}else var l=r(t,o,"rangeFinder");"number"==typeof i&&(i=e.Pos(i,0));var u=r(t,o,"minFoldSize"),p=a(!0);if(r(t,o,"scanUp"))for(;!p&&i.line>t.firstLine();){i=e.Pos(i.line-1,0);p=a(!1)}if(p&&!p.cleared&&"unfold"!==s){var c=n(t,o);e.on(c,"mousedown",function(t){d.clear();e.e_preventDefault(t)});var d=t.markText(p.from,p.to,{replacedWith:c,clearOnEnter:!0,__isFold:!0});d.on("clear",function(n,r){e.signal(t,"unfold",t,n,r)});e.signal(t,"fold",t,p.from,p.to)}}function n(e,t){var n=r(e,t,"widget");if("string"==typeof n){var i=document.createTextNode(n);n=document.createElement("span");n.appendChild(i);n.className="CodeMirror-foldmarker"}return n}function r(e,t,n){if(t&&void 0!==t[n])return t[n];var r=e.options.foldOptions;return r&&void 0!==r[n]?r[n]:i[n]}e.newFoldFunction=function(e,n){return function(r,i){t(r,i,{rangeFinder:e,widget:n})}};e.defineExtension("foldCode",function(e,n,r){t(this,e,n,r)});e.defineExtension("isFolded",function(e){for(var t=this.findMarksAt(e),n=0;n<t.length;++n)if(t[n].__isFold)return!0});e.commands.toggleFold=function(e){e.foldCode(e.getCursor())};e.commands.fold=function(e){e.foldCode(e.getCursor(),null,"fold")};e.commands.unfold=function(e){e.foldCode(e.getCursor(),null,"unfold")};e.commands.foldAll=function(t){t.operation(function(){for(var n=t.firstLine(),r=t.lastLine();r>=n;n++)t.foldCode(e.Pos(n,0),null,"fold")})};e.commands.unfoldAll=function(t){t.operation(function(){for(var n=t.firstLine(),r=t.lastLine();r>=n;n++)t.foldCode(e.Pos(n,0),null,"unfold")})};e.registerHelper("fold","combine",function(){var e=Array.prototype.slice.call(arguments,0);return function(t,n){for(var r=0;r<e.length;++r){var i=e[r](t,n);if(i)return i}}});e.registerHelper("fold","auto",function(e,t){for(var n=e.getHelpers(t,"fold"),r=0;r<n.length;r++){var i=n[r](e,t);if(i)return i}});var i={rangeFinder:e.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};e.defineOption("foldOptions",null);e.defineExtension("foldOption",function(e,t){return r(this,e,t)})})},{codemirror:void 0}],19:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}(),t("./foldcode")):"function"==typeof e&&e.amd?e(["../../lib/codemirror","./foldcode"],i):i(CodeMirror)})(function(e){"use strict";function t(e){this.options=e;this.from=this.to=0}function n(e){e===!0&&(e={});null==e.gutter&&(e.gutter="CodeMirror-foldgutter");null==e.indicatorOpen&&(e.indicatorOpen="CodeMirror-foldgutter-open");null==e.indicatorFolded&&(e.indicatorFolded="CodeMirror-foldgutter-folded");return e}function r(e,t){for(var n=e.findMarksAt(c(t)),r=0;r<n.length;++r)if(n[r].__isFold&&n[r].find().from.line==t)return!0}function i(e){if("string"==typeof e){var t=document.createElement("div");t.className=e+" CodeMirror-guttermarker-subtle";return t}return e.cloneNode(!0)}function o(e,t,n){var o=e.state.foldGutter.options,s=t,a=e.foldOption(o,"minFoldSize"),l=e.foldOption(o,"rangeFinder");e.eachLine(t,n,function(t){var n=null;if(r(e,s))n=i(o.indicatorFolded);else{var u=c(s,0),p=l&&l(e,u);p&&p.to.line-p.from.line>=a&&(n=i(o.indicatorOpen))}e.setGutterMarker(t,o.gutter,n);++s})}function s(e){var t=e.getViewport(),n=e.state.foldGutter;if(n){e.operation(function(){o(e,t.from,t.to)});n.from=t.from;n.to=t.to}}function a(e,t,n){var r=e.state.foldGutter.options;n==r.gutter&&e.foldCode(c(t,0),r.rangeFinder)}function l(e){var t=e.state.foldGutter,n=e.state.foldGutter.options;t.from=t.to=0;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){s(e)},n.foldOnChangeTimeSpan||600)}function u(e){var t=e.state.foldGutter,n=e.state.foldGutter.options;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){var n=e.getViewport();t.from==t.to||n.from-t.to>20||t.from-n.to>20?s(e):e.operation(function(){if(n.from<t.from){o(e,n.from,t.from);t.from=n.from}if(n.to>t.to){o(e,t.to,n.to);t.to=n.to}})},n.updateViewportTimeSpan||400)}function p(e,t){var n=e.state.foldGutter,r=t.line;r>=n.from&&r<n.to&&o(e,r,r+1)}e.defineOption("foldGutter",!1,function(r,i,o){if(o&&o!=e.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",a);r.off("change",l);r.off("viewportChange",u);r.off("fold",p);r.off("unfold",p);r.off("swapDoc",s)}if(i){r.state.foldGutter=new t(n(i));s(r);r.on("gutterClick",a);r.on("change",l);r.on("viewportChange",u);r.on("fold",p);r.on("unfold",p);r.on("swapDoc",s)}});var c=e.Pos})},{"./foldcode":18,codemirror:void 0}],20:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e,t){return e.line-t.line||e.ch-t.ch}function n(e,t,n,r){this.line=t;this.ch=n;this.cm=e;this.text=e.getLine(t);this.min=r?r.from:e.firstLine();this.max=r?r.to-1:e.lastLine()}function r(e,t){var n=e.cm.getTokenTypeAt(d(e.line,t));return n&&/\btag\b/.test(n)}function i(e){if(!(e.line>=e.max)){e.ch=0;e.text=e.cm.getLine(++e.line);return!0}}function o(e){if(!(e.line<=e.min)){e.text=e.cm.getLine(--e.line);e.ch=e.text.length;return!0}}function s(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(i(e))continue;return}if(r(e,t+1)){var n=e.text.lastIndexOf("/",t),o=n>-1&&!/\S/.test(e.text.slice(n+1,t));e.ch=t+1;return o?"selfClose":"regular"}e.ch=t+1}}function a(e){for(;;){var t=e.ch?e.text.lastIndexOf("<",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){g.lastIndex=t;e.ch=t;var n=g.exec(e.text);if(n&&n.index==t)return n}else e.ch=t}}function l(e){for(;;){g.lastIndex=e.ch;var t=g.exec(e.text);if(!t){if(i(e))continue;return}if(r(e,t.index+1)){e.ch=t.index+t[0].length;return t}e.ch=t.index+1}}function u(e){for(;;){var t=e.ch?e.text.lastIndexOf(">",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){var n=e.text.lastIndexOf("/",t),i=n>-1&&!/\S/.test(e.text.slice(n+1,t));e.ch=t+1;return i?"selfClose":"regular"}e.ch=t}}function p(e,t){for(var n=[];;){var r,i=l(e),o=e.line,a=e.ch-(i?i[0].length:0);if(!i||!(r=s(e)))return;if("selfClose"!=r)if(i[1]){for(var u=n.length-1;u>=0;--u)if(n[u]==i[2]){n.length=u;break}if(0>u&&(!t||t==i[2]))return{tag:i[2],from:d(o,a),to:d(e.line,e.ch)}}else n.push(i[2])}}function c(e,t){for(var n=[];;){var r=u(e);if(!r)return;if("selfClose"!=r){var i=e.line,o=e.ch,s=a(e);if(!s)return;if(s[1])n.push(s[2]);else{for(var l=n.length-1;l>=0;--l)if(n[l]==s[2]){n.length=l;break}if(0>l&&(!t||t==s[2]))return{tag:s[2],from:d(e.line,e.ch),to:d(i,o)}}}else a(e)}}var d=e.Pos,f="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",h=f+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",g=new RegExp("<(/?)(["+f+"]["+h+"]*)","g");e.registerHelper("fold","xml",function(e,t){for(var r=new n(e,t.line,0);;){var i,o=l(r);if(!o||r.line!=t.line||!(i=s(r)))return;if(!o[1]&&"selfClose"!=i){var t=d(r.line,r.ch),a=p(r,o[2]);return a&&{from:t,to:a.from}}}});e.findMatchingTag=function(e,r,i){var o=new n(e,r.line,r.ch,i);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=s(o),u=l&&d(o.line,o.ch),f=l&&a(o);if(l&&f&&!(t(o,r)>0)){var h={from:d(o.line,o.ch),to:u,tag:f[2]};if("selfClose"==l)return{open:h,close:null,at:"open"};if(f[1])return{open:c(o,f[2]),close:h,at:"close"};o=new n(e,u.line,u.ch,i);return{open:h,close:p(o,f[2]),at:"open"}}}};e.findEnclosingTag=function(e,t,r){for(var i=new n(e,t.line,t.ch,r);;){var o=c(i);if(!o)break;var s=new n(e,t.line,t.ch,r),a=p(s,o.tag);if(a)return{open:o,close:a}}};e.scanForClosingTag=function(e,t,r,i){var o=new n(e,t.line,t.ch,i?{from:0,to:i}:null);return p(o,r)}})},{codemirror:void 0}],21:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e,t){this.cm=e;this.options=this.buildOptions(t);this.widget=this.onClose=null}function n(e){return"string"==typeof e?e:e.text}function r(e,t){function n(e,n){var i;i="string"!=typeof n?function(e){return n(e,t)}:r.hasOwnProperty(n)?r[n]:n;o[e]=i}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},i=e.options.customKeys,o=i?{}:r;if(i)for(var s in i)i.hasOwnProperty(s)&&n(s,i[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&n(s,a[s]);return o}function i(e,t){for(;t&&t!=e;){if("LI"===t.nodeName.toUpperCase()&&t.parentNode==e)return t;t=t.parentNode}}function o(t,o){this.completion=t;this.data=o;var l=this,u=t.cm,p=this.hints=document.createElement("ul");p.className="CodeMirror-hints";this.selectedHint=o.selectedHint||0;for(var c=o.list,d=0;d<c.length;++d){var f=p.appendChild(document.createElement("li")),h=c[d],g=s+(d!=this.selectedHint?"":" "+a);null!=h.className&&(g=h.className+" "+g);f.className=g;h.render?h.render(f,o,h):f.appendChild(document.createTextNode(h.displayText||n(h)));f.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),E=m.left,v=m.bottom,x=!0;p.style.left=E+"px";p.style.top=v+"px";var y=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),N=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var I=p.getBoundingClientRect(),A=I.bottom-N;if(A>0){var T=I.bottom-I.top,L=m.top-(m.bottom-I.top);if(L-T>0){p.style.top=(v=m.top-T)+"px";x=!1}else if(T>N){p.style.height=N-5+"px";p.style.top=(v=m.bottom-I.top)+"px";var S=u.getCursor();if(o.from.ch!=S.ch){m=u.cursorCoords(S);p.style.left=(E=m.left)+"px";I=p.getBoundingClientRect()}}}var C=I.right-y;if(C>0){if(I.right-I.left>y){p.style.width=y-5+"px";C-=I.right-I.left-y}p.style.left=(E=m.left-C)+"px"}u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:c.length,close:function(){t.close()},pick:function(){l.pick()},data:o}));if(t.options.closeOnUnfocus){var b;u.on("blur",this.onBlur=function(){b=setTimeout(function(){t.close()},100)});u.on("focus",this.onFocus=function(){clearTimeout(b)})}var R=u.getScrollInfo();u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),n=u.getWrapperElement().getBoundingClientRect(),r=v+R.top-e.top,i=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);x||(i+=p.offsetHeight);if(i<=n.top||i>=n.bottom)return t.close();p.style.top=r+"px";p.style.left=E+R.left-e.left+"px"});e.on(p,"dblclick",function(e){var t=i(p,e.target||e.srcElement);if(t&&null!=t.hintId){l.changeActive(t.hintId);l.pick()}});e.on(p,"click",function(e){var n=i(p,e.target||e.srcElement);if(n&&null!=n.hintId){l.changeActive(n.hintId);t.options.completeOnSingleClick&&l.pick()}});e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)});e.signal(o,"select",c[0],p.firstChild);return!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,n){if(!t)return e.showHint(n);n&&n.async&&(t.async=!0);var r={hint:t};if(n)for(var i in n)r[i]=n[i];return e.showHint(r)};e.defineExtension("showHint",function(n){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,n),i=r.options.hint;if(i){e.signal(this,"startCompletion",this);if(!i.async)return r.showHints(i(this,r.options));i(this,function(e){r.showHints(e)},r.options);return void 0}}});t.prototype={close:function(){if(this.active()){this.cm.state.completionActive=null;this.widget&&this.widget.close();this.onClose&&this.onClose();e.signal(this.cm,"endCompletion",this.cm)}},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var i=t.list[r];i.hint?i.hint(this.cm,t,i):this.cm.replaceRange(n(i),i.from||t.from,i.to||t.to,"complete");e.signal(t,"pick",i);this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e);return void 0},showWidget:function(t){function n(){if(!l){l=!0;p.close();p.cm.off("cursorActivity",a);t&&e.signal(t,"close")}}function r(){if(!l){e.signal(t,"update");var n=p.options.hint;n.async?n(p.cm,i,p.options):i(n(p.cm,p.options))}}function i(e){t=e;if(!l){if(!t||!t.list.length)return n();p.widget&&p.widget.close();p.widget=new o(p,t)}}function s(){if(u){g(u);u=0}}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);if(e.line!=d.line||t.length-e.ch!=f-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1)))p.close();else{u=h(r);p.widget&&p.widget.close()}}this.widget=new o(this,t);e.signal(t,"shown");var l,u=0,p=this,c=this.options.closeCharacters,d=this.cm.getCursor(),f=this.cm.getLine(d.line).length,h=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},g=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a);this.onClose=n},buildOptions:function(e){var t=this.cm.options.hintOptions,n={};for(var r in l)n[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(n[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(n[r]=e[r]);return n}};o.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null;this.hints.parentNode.removeChild(this.hints);this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;if(this.completion.options.closeOnUnfocus){e.off("blur",this.onBlur);e.off("focus",this.onFocus)}e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,n){t>=this.data.list.length?t=n?this.data.list.length-1:0:0>t&&(t=n?0:this.data.list.length-1);if(this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,"");r=this.hints.childNodes[this.selectedHint=t];r.className+=" "+a;r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3);e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}};e.registerHelper("hint","auto",function(t,n){var r,i=t.getHelpers(t.getCursor(),"hint");if(i.length)for(var o=0;o<i.length;o++){var s=i[o](t,n);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,n)});e.registerHelper("hint","fromList",function(t,n){for(var r=t.getCursor(),i=t.getTokenAt(r),o=[],s=0;s<n.words.length;s++){var a=n.words[s];a.slice(0,i.string.length)==i.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,i.start),to:e.Pos(r.line,i.end)}:void 0});e.commands.autocomplete=e.showHint;var l={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{codemirror:void 0}],22:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.runMode=function(t,n,r,i){var o=e.getMode(e.defaults,n),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=i&&i.tabSize||e.defaults.tabSize,u=r,p=0;u.innerHTML="";r=function(e,t){if("\n"!=e){for(var n="",r=0;;){var i=e.indexOf(" ",r);if(-1==i){n+=e.slice(r);p+=e.length-r;break}p+=i-r;n+=e.slice(r,i);var o=l-p%l;p+=o;for(var s=0;o>s;++s)n+=" ";r=i+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-");c.appendChild(document.createTextNode(n))}else u.appendChild(document.createTextNode(n))}else{u.appendChild(document.createTextNode(a?"\r":e));p=0}}}for(var c=e.splitLines(t),d=i&&i.state||e.startState(o),f=0,h=c.length;h>f;++f){f&&r("\n");var g=new e.StringStream(c[f]);!g.string&&o.blankLine&&o.blankLine(d);for(;!g.eol();){var m=o.token(g,d);r(g.current(),m,f,g.start,d);g.start=g.pos}}}})},{codemirror:void 0}],23:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";function t(e,t,i,o){this.atOccurrence=!1;this.doc=e;null==o&&"string"==typeof t&&(o=!1);i=i?e.clipPos(i):r(0,0);this.pos={from:i,to:i};if("string"!=typeof t){t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g"));this.matches=function(n,i){if(n){t.lastIndex=0;for(var o,s,a=e.getLine(i.line).slice(0,i.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;o=u;s=o.index;l=o.index+(o[0].length||1);if(l==a.length)break}var p=o&&o[0].length||0;p||(0==s&&0==a.length?o=void 0:s!=e.getLine(i.line).length&&p++)}else{t.lastIndex=i.ch;var a=e.getLine(i.line),o=t.exec(a),p=o&&o[0].length||0,s=o&&o.index;s+p==a.length||p||(p=1)}return o&&p?{from:r(i.line,s),to:r(i.line,s+p),match:o}:void 0}}else{var s=t;o&&(t=t.toLowerCase());var a=o?function(e){return e.toLowerCase()}:function(e){return e},l=t.split("\n");if(1==l.length)this.matches=t.length?function(i,o){if(i){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),p=u.lastIndexOf(t);if(p>-1){p=n(l,u,p);return{from:r(o.line,p),to:r(o.line,p+s.length)}}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),p=u.indexOf(t);if(p>-1){p=n(l,u,p)+o.ch;return{from:r(o.line,p),to:r(o.line,p+s.length)}}}}:function(){};else{var u=s.split("\n");this.matches=function(t,n){var i=l.length-1;if(t){if(n.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(n.line).slice(0,u[i].length))!=l[l.length-1])return;for(var o=r(n.line,u[i].length),s=n.line-1,p=i-1;p>=1;--p,--s)if(l[p]!=a(e.getLine(s)))return;var c=e.getLine(s),d=c.length-u[0].length;if(a(c.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(n.line+(l.length-1)>e.lastLine())){var c=e.getLine(n.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var f=r(n.line,d),s=n.line+1,p=1;i>p;++p,++s)if(l[p]!=a(e.getLine(s)))return;if(a(e.getLine(s).slice(0,u[i].length))==l[i])return{from:f,to:r(s,u[i].length)}}}}}}}function n(e,t,n){if(e.length==t.length)return n;for(var r=Math.min(n,e.length);;){var i=e.slice(0,r).toLowerCase().length;if(n>i)++r;else{if(!(i>n))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);n.pos={from:t,to:t};n.atOccurrence=!1;return!1}for(var n=this,i=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,i)){this.atOccurrence=!0;return this.pos.match||!0}if(e){if(!i.line)return t(0);i=r(i.line-1,this.doc.getLine(i.line-1).length)}else{var o=this.doc.lineCount();if(i.line==o-1)return t(o);i=r(i.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(t){if(this.atOccurrence){var n=e.splitLines(t);this.doc.replaceRange(n,this.pos.from,this.pos.to);this.pos.to=r(this.pos.from.line+n.length-1,n[n.length-1].length+(1==n.length?this.pos.from.ch:0))}}};e.defineExtension("getSearchCursor",function(e,n,r){return new t(this.doc,e,n,r)});e.defineDocExtension("getSearchCursor",function(e,n,r){return new t(this,e,n,r)});e.defineExtension("selectMatches",function(t,n){for(var r,i=[],o=this.getSearchCursor(t,this.getCursor("from"),n);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)i.push({anchor:o.from(),head:o.to()});i.length&&this.setSelections(i,0)})})},{codemirror:void 0}],24:[function(e,t){t.exports=e(7)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/node_modules/store/store.js":7}],25:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.0",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],26:[function(e,t,n){arguments[4][9][0].apply(n,arguments)},{"../package.json":25,"./storage.js":27,"./svg.js":28,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/main.js":9}],27:[function(e,t){{var n=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,i){if(e&&t){"string"==typeof i&&(i=r[i]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));n.set(e,{val:t,exp:i,time:(new Date).getTime()})}},remove:function(e){e&&n.remove(e)},get:function(e){if(e){var t=n.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}return null}}}},{store:24}],28:[function(e,t){t.exports=e(11)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/svg.js":11}],29:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.3.0",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasqe.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasqe.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"}}}},{}],30:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("../utils.js"),i=e("yasgui-utils"),o=e("../../lib/trie.js");t.exports=function(e,t){var a={},l={},u={};t.on("cursorActivity",function(){d(!0)});t.on("change",function(){var e=[];for(var r in a)a[r].is(":visible")&&e.push(a[r]);if(e.length>0){var i=n(t.getWrapperElement()).find(".CodeMirror-vscrollbar"),o=0;i.is(":visible")&&(o=i.outerWidth());e.forEach(function(e){e.css("right",o)})}});var p=function(e,n){u[e.name]=new o;for(var s=0;s<n.length;s++)u[e.name].insert(n[s]);var a=r.getPersistencyId(t,e.persistent);a&&i.storage.set(a,n,"month")},c=function(e,n){var o=l[e]=new n(t,e);o.name=e;if(o.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&p(o,e)};if(o.get instanceof Array)s(o.get);else{var a=null,u=r.getPersistencyId(t,o.persistent);u&&(a=i.storage.get(u));a&&a.length>0?s(a):o.get instanceof Function&&(o.async?o.get(null,s):s(o.get()))}}},d=function(r){if(!t.somethingSelected()){var i=function(n){if(r&&(!n.autoShow||!n.bulk&&n.async))return!1;var i={closeCharacters:/(?=a)b/,completeSingle:!1};!n.bulk&&n.async&&(i.async=!0);{var o=function(e,t){return f(n,t)};e.showHint(t,o,i)}return!0};for(var o in l)if(-1!=n.inArray(o,t.options.autocompleters)){var s=l[o];
if(s.isValidCompletionPosition)if(s.isValidCompletionPosition()){if(!s.callbacks||!s.callbacks.validPosition||s.callbacks.validPosition(t,s)!==!1){var a=i(s);if(a)break}}else s.callbacks&&s.callbacks.invalidPosition&&s.callbacks.invalidPosition(t,s)}}},f=function(e,n){var r=function(t){var n=t.autocompletionString||t.string,r=[];if(u[e.name])r=u[e.name].autoComplete(n);else if("function"==typeof e.get&&0==e.async)r=e.get(n);else if("object"==typeof e.get)for(var i=n.length,o=0;o<e.get.length;o++){var s=e.get[o];s.slice(0,i)==n&&r.push(s)}return h(r,e,t)},i=t.getCompleteToken();e.preProcessToken&&(i=e.preProcessToken(i));if(i){if(e.bulk||!e.async)return r(i);var o=function(t){n(h(t,e,i))};e.get(i,o)}},h=function(e,n,r){for(var i=[],o=0;o<e.length;o++){var a=e[o];n.postProcessToken&&(a=n.postProcessToken(r,a));i.push({text:a,displayText:a,hint:s})}var l=t.getCursor(),u={completionToken:r.string,list:i,from:{line:l.line,ch:r.start},to:{line:l.line,ch:r.end}};if(n.callbacks)for(var p in n.callbacks)n.callbacks[p]&&t.on(u,p,n.callbacks[p]);return u};return{init:c,completers:l,notifications:{getEl:function(e){return n(a[e.name])},show:function(e,t){if(!t.autoshow){a[t.name]||(a[t.name]=n("<div class='completionNotification'></div>"));a[t.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(n(e.getWrapperElement()))}},hide:function(e,t){a[t.name]&&a[t.name].hide()}},autoComplete:d,getTrie:function(e){return"string"==typeof e?u[e]:u[e.name]}}};var s=function(e,t,n){n.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(n.text,t.from,t.to)}},{"../../lib/trie.js":14,"../utils.js":43,jquery:void 0,"yasgui-utils":26}],31:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})();t.exports=function(n,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(n)},get:function(t,r){return e("./utils").fetchFromLov(n,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(n,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(n,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:n.autocompleters.notifications.show,invalidPosition:n.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.indexOf("?"))return!1;var n=e.getCursor(),r=e.getPreviousNonWsToken(n.line,t);return"a"==r.string?!0:"rdf:type"==r.string?!0:"rdfs:domain"==r.string?!0:"rdfs:range"==r.string?!0:!1};t.exports.preProcessToken=function(t,n){return e("./utils.js").preprocessResourceTokenForCompletion(t,n)};t.exports.postProcessToken=function(t,n,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,n,r)}},{"./utils":34,"./utils.js":34,jquery:void 0}],32:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r={"string-2":"prefixed",atom:"var"};t.exports=function(e,r){e.on("change",function(){t.exports.appendPrefixIfNeeded(e,r)});return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(e)},get:function(e,t){n.get("http://prefix.cc/popular/all.file.json",function(e){var n=[];for(var r in e)if("bif"!=r){var i=r+": <"+e[r]+">";n.push(i)}n.sort();t(n)})},preProcessToken:function(n){return t.exports.preprocessPrefixTokenForCompletion(e,n)},async:!0,bulk:!0,autoShow:!0,persistent:r}};t.exports.isValidCompletionPosition=function(e){var t=e.getCursor(),r=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;"ws"!=r.type&&(r=e.getCompleteToken());if(0==!r.string.indexOf("a")&&-1==n.inArray("PNAME_NS",r.state.possibleCurrent))return!1;var i=e.getPreviousNonWsToken(t.line,r);return i&&"PREFIX"==i.string.toUpperCase()?!0:!1};t.exports.preprocessPrefixTokenForCompletion=function(e,t){var n=e.getPreviousNonWsToken(e.getCursor().line,t);n&&n.string&&":"==n.string.slice(-1)&&(t={start:n.start,end:t.end,string:n.string+" "+t.string,state:t.state});return t};t.exports.appendPrefixIfNeeded=function(e,t){if(e.autocompleters.getTrie(t)&&e.options.autocompleters&&-1!=e.options.autocompleters.indexOf(t)){var n=e.getCursor(),i=e.getTokenAt(n);if("prefixed"==r[i.type]){var o=i.string.indexOf(":");if(-1!==o){var s=e.getPreviousNonWsToken(n.line,i).string.toUpperCase(),a=e.getTokenAt({line:n.line,ch:i.start});if("PREFIX"!=s&&("ws"==a.type||null==a.type)){var l=i.string.substring(0,o+1),u=e.getPrefixesFromQuery();if(null==u[l.slice(0,-1)]){var p=e.autocompleters.getTrie(t).autoComplete(l);p.length>0&&e.addPrefixes(p[0])}}}}}}},{jquery:void 0}],33:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports=function(n,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(n)},get:function(t,r){return e("./utils").fetchFromLov(n,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(n,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(n,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:n.autocompleters.notifications.show,invalidPosition:n.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.length)return!1;if(0==t.string.indexOf("?"))return!1;if(n.inArray("a",t.state.possibleCurrent)>=0)return!0;var r=e.getCursor(),i=e.getPreviousNonWsToken(r.line,t);return"rdfs:subPropertyOf"==i.string?!0:!1};t.exports.preProcessToken=function(t,n){return e("./utils.js").preprocessResourceTokenForCompletion(t,n)};t.exports.postProcessToken=function(t,n,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,n,r)}},{"./utils":34,"./utils.js":34,jquery:void 0}],34:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=(e("./utils.js"),e("yasgui-utils")),i=function(e,t){var n=e.getPrefixesFromQuery();if(0==!t.string.indexOf("<")){t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1);null!=n[t.tokenPrefix.slice(0,-1)]&&(t.tokenPrefixUri=n[t.tokenPrefix.slice(0,-1)])}t.autocompletionString=t.string.trim();if(0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var r in n)if(0==t.string.indexOf(r)){t.autocompletionString=n[r];t.autocompletionString+=t.string.substring(r.length+1);break}0==t.autocompletionString.indexOf("<")&&(t.autocompletionString=t.autocompletionString.substring(1));-1!==t.autocompletionString.indexOf(">",t.length-1)&&(t.autocompletionString=t.autocompletionString.substring(0,t.autocompletionString.length-1));return t},o=function(e,t,n){n=t.tokenPrefix&&t.autocompletionString&&t.tokenPrefixUri?t.tokenPrefix+n.substring(t.tokenPrefixUri.length):"<"+n+">";return n},s=function(t,i,o,s){if(!o||!o.string||0==o.string.trim().length){t.autocompleters.notifications.getEl(i).empty().append("Nothing to autocomplete yet!");return!1}var a=50,l={q:o.autocompletionString,page:1};l.type="classes"==i.name?"class":"property";var u=[],p="",c=function(){p="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+n.param(l)};c();var d=function(){l.page++;c()},f=function(){n.get(p,function(e){for(var r=0;r<e.results.length;r++)u.push(n.isArray(e.results[r].uri)&&e.results[r].uri.length>0?e.results[r].uri[0]:e.results[r].uri);if(u.length<e.total_results&&u.length<a){d();f()}else{u.length>0?t.autocompleters.notifications.hide(t,i):t.autocompleters.notifications.getEl(i).text("0 matches found...");s(u)}}).fail(function(){t.autocompleters.notifications.getEl(i).empty().append("Failed fetching suggestions..")})};t.autocompleters.notifications.getEl(i).empty().append(n("<span>Fetchting autocompletions </span>")).append(n(r.svg.getElement(e("../imgs.js").loader)).addClass("notificationLoader"));f()};t.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:i,postprocessResourceTokenForCompletion:o}},{"../imgs.js":37,"./utils.js":34,jquery:void 0,"yasgui-utils":26}],35:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports=function(e){return{isValidCompletionPosition:function(){var t=e.getTokenAt(e.getCursor());if("ws"!=t.type){t=e.getCompleteToken(t);if(t&&0==t.string.indexOf("?"))return!0}return!1},get:function(t){if(0==t.trim().length)return[];var r={};n(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var i=n(this).next(),o=i.attr("class");o&&i.attr("class").indexOf("cm-atom")>=0&&(e+=i.text());if(e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;r[e]=!0}});var i=[];for(var o in r)i.push(o);i.sort();return i},async:!1,bulk:!1,autoShow:!0}}},{jquery:void 0}],36:[function(e,t){var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports={use:function(e){e.defaults=n.extend(!0,{},e.defaults,{mode:"sparql11",value:"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nSELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,lineWrapping:!0,foldGutter:{rangeFinder:e.fold.brace},gutters:["gutterErrorBar","CodeMirror-linenumbers","CodeMirror-foldgutter"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":e.autoComplete,"Cmd-Space":e.autoComplete,"Ctrl-D":e.deleteLine,"Ctrl-K":e.deleteLine,"Cmd-D":e.deleteLine,"Cmd-K":e.deleteLine,"Ctrl-/":e.commentLines,"Cmd-/":e.commentLines,"Ctrl-Alt-Down":e.copyLineDown,"Ctrl-Alt-Up":e.copyLineUp,"Cmd-Alt-Down":e.copyLineDown,"Cmd-Alt-Up":e.copyLineUp,"Shift-Ctrl-F":e.doAutoFormat,"Shift-Cmd-F":e.doAutoFormat,"Ctrl-]":e.indentMore,"Cmd-]":e.indentMore,"Ctrl-[":e.indentLess,"Cmd-[":e.indentLess,"Ctrl-S":e.storeQuery,"Cmd-S":e.storeQuery,"Ctrl-Enter":e.executeQuery,"Cmd-Enter":e.executeQuery,F11:function(e){e.setOption("fullScreen",!e.getOption("fullScreen"))},Esc:function(e){e.getOption("fullScreen")&&e.setOption("fullScreen",!1)}},cursorHeight:.9,createShareLink:e.createShareLink,consumeShareLink:e.consumeShareLink,persistent:function(e){return"yasqe_"+n(e.getWrapperElement()).closest("[id]").attr("id")+"_queryVal"},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"POST",acceptHeaderGraph:"text/turtle,*/*;q=0.9",acceptHeaderSelect:"application/sparql-results+json,*/*;q=0.9",acceptHeaderUpdate:"text/plain,*/*;q=0.9",namedGraphs:[],defaultGraphs:[],args:[],headers:{},callbacks:{beforeSend:null,complete:null,error:null,success:null},handlers:{}}})}}},{jquery:void 0}],37:[function(e,t){"use strict";t.exports={loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g ></g><g > <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" ><g transform="translate(-2.995,-2.411)" /><g transform="translate(-2.995,-2.411)"><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" inkscape:connector-curvature="0" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" ><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 88.184,81.468 c 1.167,1.167 1.167,3.075 0,4.242 l -2.475,2.475 c -1.167,1.167 -3.076,1.167 -4.242,0 l -69.65,-69.65 c -1.167,-1.167 -1.167,-3.076 0,-4.242 l 2.476,-2.476 c 1.167,-1.167 3.076,-1.167 4.242,0 l 69.649,69.651 z" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" ><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 18.532,88.184 c -1.167,1.166 -3.076,1.166 -4.242,0 l -2.475,-2.475 c -1.167,-1.166 -1.167,-3.076 0,-4.242 l 69.65,-69.651 c 1.167,-1.167 3.075,-1.167 4.242,0 l 2.476,2.476 c 1.166,1.167 1.166,3.076 0,4.242 l -69.651,69.65 z" /></g></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g ></g><g > <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',warning:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="0 0 66.399998 66.399998" enable-background="new 0 0 69.3 69.3" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" ><g transform="translate(-1.5,-1.5)" style="fill:#ff0000"><path d="M 34.7,1.5 C 16.4,1.5 1.5,16.4 1.5,34.7 1.5,53 16.4,67.9 34.7,67.9 53,67.9 67.9,53 67.9,34.7 67.9,16.4 53,1.5 34.7,1.5 z m 0,59.4 C 20.2,60.9 8.5,49.1 8.5,34.7 8.5,20.2 20.3,8.5 34.7,8.5 c 14.4,0 26.2,11.8 26.2,26.2 0,14.4 -11.8,26.2 -26.2,26.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.6,47.1 c -1.4,0 -2.5,0.5 -3.5,1.5 -0.9,1 -1.4,2.2 -1.4,3.6 0,1.6 0.5,2.8 1.5,3.8 1,0.9 2.1,1.3 3.4,1.3 1.3,0 2.4,-0.5 3.4,-1.4 1,-0.9 1.5,-2.2 1.5,-3.7 0,-1.4 -0.5,-2.6 -1.4,-3.6 -0.9,-1 -2.1,-1.5 -3.5,-1.5 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.8,13.9 c -1.5,0 -2.8,0.5 -3.7,1.6 -0.9,1 -1.4,2.4 -1.4,4.2 0,1.1 0.1,2.9 0.2,5.6 l 0.8,13.1 c 0.2,1.8 0.4,3.2 0.9,4.1 0.5,1.2 1.5,1.8 2.9,1.8 1.3,0 2.3,-0.7 2.9,-1.9 0.5,-1 0.7,-2.3 0.9,-4 L 39.4,25 c 0.1,-1.3 0.2,-2.5 0.2,-3.8 0,-2.2 -0.3,-3.9 -0.8,-5.1 -0.5,-1 -1.6,-2.2 -4,-2.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}},{}],38:[function(e,t){"use strict";window.console=window.console||{log:function(){}};var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=function(){try{return e("codemirror")}catch(t){return window.CodeMirror}}(),i=(e("./sparql.js"),e("./utils.js")),o=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.js");e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/hint/show-hint.js");e("codemirror/addon/search/searchcursor.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/addon/runmode/runmode.js");e("codemirror/addon/display/fullscreen.js");e("../lib/flint.js");var a=t.exports=function(e,t){var i=n("<div>",{"class":"yasqe"}).appendTo(n(e));t=l(t);var o=u(r(i[0],t));d(o);return o},l=function(e){var t=n.extend(!0,{},a.defaults,e);return t},u=function(t){t.autocompleters=e("./autocompleters/autocompleterBase.js")(a,t);t.options.autocompleters&&t.options.autocompleters.forEach(function(e){a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])});t.getCompleteToken=function(n,r){return e("./tokenUtils.js").getCompleteToken(t,n,r)};t.getPreviousNonWsToken=function(n,r){return e("./tokenUtils.js").getPreviousNonWsToken(t,n,r)};t.getNextNonWsToken=function(n,r){return e("./tokenUtils.js").getNextNonWsToken(t,n,r)};t.query=function(e){a.executeQuery(t,e)};t.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(t)};t.addPrefixes=function(n){return e("./prefixUtils.js").addPrefixes(t,n)};t.removePrefixes=function(n){return e("./prefixUtils.js").removePrefixes(t,n)};t.getQueryType=function(){return t.queryType};t.getQueryMode=function(){var e=t.getQueryType();return"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e?"update":"query"};t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e;h(t)};t.enableCompleter=function(e){p(t.options,e);a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])};t.disableCompleter=function(e){c(t.options,e)};return t},p=function(e,t){e.autocompleters||(e.autocompleters=[]);e.autocompleters.push(t)},c=function(e,t){if("object"==typeof e.autocompleters){var r=n.inArray(t,e.autocompleters);if(r>=0){e.autocompleters.splice(r,1);c(e,t)}}},d=function(e){var t=i.getPersistencyId(e,e.options.persistent);if(t){var r=o.storage.get(t);r&&e.setValue(r)}a.drawButtons(e);e.on("blur",function(e){a.storeQuery(e)});e.on("change",function(e){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("cursorActivity",function(e){f(e)});e.prevQueryValid=!1;h(e);a.positionButtons(e);if(e.options.consumeShareLink){var s=n.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},f=function(e){e.cursor=n(".CodeMirror-cursor");e.buttons&&e.buttons.is(":visible")&&e.cursor.length>0&&(i.elementsOverlap(e.cursor,e.buttons)?e.buttons.find("svg").attr("opacity","0.2"):e.buttons.find("svg").attr("opacity","1.0"))},h=function(t,r){t.queryValid=!0;t.clearGutter("gutterErrorBar");for(var i=null,a=0;a<t.lineCount();++a){var l=!1;t.prevQueryValid||(l=!0);var u=t.getTokenAt({line:a,ch:t.getLine(a).length},l),i=u.state;t.queryType=i.queryType;if(0==i.OK){if(!t.options.syntaxErrorCheck){n(t.getWrapperElement).find(".sp-error").css("color","black");return}var p=o.svg.getElement(s.warning);i.possibleCurrent&&i.possibleCurrent.length>0&&e("./tooltip")(t,p,function(){var e=[];i.possibleCurrent.forEach(function(t){e.push("<strong style='text-decoration:underline'>"+n("<div/>").text(t).html()+"</strong>")});return"This line is invalid. Expected: "+e.join(", ")});p.style.marginTop="2px";p.style.marginLeft="2px";p.className="parseErrorIcon";t.setGutterMarker(a,"gutterErrorBar",p);t.queryValid=!1;break}}t.prevQueryValid=t.queryValid;if(r&&null!=i&&void 0!=i.stack){var c=i.stack,d=i.stack.length;d>1?t.queryValid=!1:1==d&&"solutionModifier"!=c[0]&&"?limitOffsetClauses"!=c[0]&&"?offsetClause"!=c[0]&&(t.queryValid=!1)}};n.extend(a,r);a.Autocompleters={};a.registerAutocompleter=function(e,t){a.Autocompleters[e]=t;p(a.defaults,e)};a.autoComplete=function(e){e.autocompleters.autoComplete(!1)};a.registerAutocompleter("prefixes",e("./autocompleters/prefixes.js"));a.registerAutocompleter("properties",e("./autocompleters/properties.js"));a.registerAutocompleter("classes",e("./autocompleters/classes.js"));a.registerAutocompleter("variables",e("./autocompleters/variables.js"));a.positionButtons=function(e){var t=n(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),r=0;t.is(":visible")&&(r=t.outerWidth());e.buttons.is(":visible")&&e.buttons.css("right",r+6)};a.createShareLink=function(e){var t=n.deparam(window.location.search.substring(1));t.query=e.getValue();return t};a.consumeShareLink=function(e,t){t.query&&e.setValue(t.query)};a.drawButtons=function(e){e.buttons=n("<div class='yasqe_buttons'></div>").appendTo(n(e.getWrapperElement()));if(e.options.createShareLink){var t=n(o.svg.getElement(s.share));t.click(function(r){r.stopPropagation();var i=n("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);n("html").click(function(){i&&i.remove()});i.click(function(e){e.stopPropagation()});var o=n("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+n.param(e.options.createShareLink(e)));o.focus(function(){var e=n(this);e.select();e.mouseup(function(){e.unbind("mouseup");return!1})});i.empty().append(o);var s=t.position();i.css("top",s.top+t.outerHeight()+"px").css("left",s.left+t.outerWidth()-i.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(e.buttons)}var r=n("<div>",{"class":"fullscreenToggleBtns"}).append(n(o.svg.getElement(s.fullscreen)).addClass("yasqe_fullscreenBtn").attr("title","Set editor full screen").click(function(){e.setOption("fullScreen",!0)})).append(n(o.svg.getElement(s.smallscreen)).addClass("yasqe_smallscreenBtn").attr("title","Set editor to normale size").click(function(){e.setOption("fullScreen",!1)}));e.buttons.append(r);if(e.options.sparql.showQueryButton){n("<div>",{"class":"yasqe_queryButton"}).click(function(){if(n(this).hasClass("query_busy")){e.xhr&&e.xhr.abort();a.updateQueryButton(e)}else e.query()}).appendTo(e.buttons);a.updateQueryButton(e)}};var g={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,t){var r=n(e.getWrapperElement()).find(".yasqe_queryButton");if(0!=r.length){if(!t){t="valid";e.queryValid===!1&&(t="error")}if(t!=e.queryStatus&&("busy"==t||"valid"==t||"error"==t)){r.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+t);o.svg.draw(r,s[g[t]]);e.queryStatus=t}}};a.fromTextArea=function(e,t){t=l(t);var i=(n("<div>",{"class":"yasqe"}).insertBefore(n(e)).append(n(e)),u(r.fromTextArea(e,t)));d(i);return i};a.storeQuery=function(e){var t=i.getPersistencyId(e,e.options.persistent);t&&o.storage.set(t,e.getValue(),"month")};a.commentLines=function(e){for(var t=e.getCursor(!0).line,n=e.getCursor(!1).line,r=Math.min(t,n),i=Math.max(t,n),o=!0,s=r;i>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;i>=s;s++)o?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})};a.copyLineUp=function(e){var t=e.getCursor(),n=e.lineCount();e.replaceRange("\n",{line:n-1,ch:e.getLine(n-1).length});for(var r=n;r>t.line;r--){var i=e.getLine(r-1);e.replaceRange(i,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}};a.copyLineDown=function(e){a.copyLineUp(e);var t=e.getCursor();t.line++;e.setCursor(t)};a.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};m(e,e.getCursor(!0),t)}else{var n=e.lineCount(),r=e.getTextArea().value.length;m(e,{line:0,ch:0},{line:n,ch:r})}};var m=function(e,t,n){var r=e.indexFromPos(t),i=e.indexFromPos(n),o=E(e.getValue(),r,i);e.operation(function(){e.replaceRange(o,t,n);for(var i=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=i;s>=a;a++)e.indentLine(a,"smart")})},E=function(e,t,i){e=e.substring(t,i);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(c.valueOf().toString()==o[t].valueOf().toString())return 1;for(var t=0;t<s.length;t++)if(e==s[t])return 1;for(var t=0;t<a.length;t++)if(""!=n.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];r.runMode(e,"sparql11",function(e,t){c.push(t);var n=l(e,t);if(0!=n){if(1==n){u+=e+"\n";p=""}else{u+="\n"+e;p=e}c=[]}else{p+=e;u+=e}1==c.length&&"sp-ws"==c[0]&&(c=[])});return n.trim(u.replace(/\n\s*\n/g,"\n"))};e("./sparql.js").use(a);e("./defaults.js").use(a);a.version={CodeMirror:r.version,YASQE:e("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":o.version}},{"../lib/deparam.js":12,"../lib/flint.js":13,"../package.json":29,"./autocompleters/autocompleterBase.js":30,"./autocompleters/classes.js":31,"./autocompleters/prefixes.js":32,"./autocompleters/properties.js":33,"./autocompleters/variables.js":35,"./defaults.js":36,"./imgs.js":37,"./prefixUtils.js":39,"./sparql.js":40,"./tokenUtils.js":41,"./tooltip":42,"./utils.js":43,codemirror:void 0,"codemirror/addon/display/fullscreen.js":15,"codemirror/addon/edit/matchbrackets.js":16,"codemirror/addon/fold/brace-fold.js":17,"codemirror/addon/fold/foldcode.js":18,"codemirror/addon/fold/foldgutter.js":19,"codemirror/addon/fold/xml-fold.js":20,"codemirror/addon/hint/show-hint.js":21,"codemirror/addon/runmode/runmode.js":22,"codemirror/addon/search/searchcursor.js":23,jquery:void 0,"yasgui-utils":26}],39:[function(e,t){"use strict";
var n=function(e,t){var n=e.getPrefixesFromQuery();if("string"==typeof t)r(e,t);else for(var i in t)i in n||r(e,i+": <"+t[i]+">")},r=function(e,t){for(var n=null,r=0,i=e.lineCount(),o=0;i>o;o++){var a=e.getNextNonWsToken(o);if(null!=a&&("PREFIX"==a.string||"BASE"==a.string)){n=a;r=o}}if(null==n)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var l=s(e,r);e.replaceRange("\n"+l+"PREFIX "+t,{line:r})}},i=function(e,t){var n=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};for(var r in t)e.setValue(e.getValue().replace(new RegExp("PREFIX\\s*"+r+":\\s*"+n("<"+t[r]+">")+"\\s*","ig"),""))},o=function(e){for(var t={},n=!0,r=function(i,s){if(n){s||(s=1);var a=e.getNextNonWsToken(o,s);if(a){-1==a.state.possibleCurrent.indexOf("PREFIX")&&-1==a.state.possibleNext.indexOf("PREFIX")&&(n=!1);if("PREFIX"==a.string.toUpperCase()){var l=e.getNextNonWsToken(o,a.end+1);if(l){var u=e.getNextNonWsToken(o,l.end+1);if(u){var p=u.string;0==p.indexOf("<")&&(p=p.substring(1));">"==p.slice(-1)&&(p=p.substring(0,p.length-1));t[l.string.slice(0,-1)]=p;r(i,u.end+1)}else r(i,l.end+1)}else r(i,a.end+1)}else r(i,a.end+1)}}},i=e.lineCount(),o=0;i>o&&n;o++)r(o);return t},s=function(e,t,n){void 0==n&&(n=1);var r=e.getTokenAt({line:t,ch:n});return null==r||void 0==r||"ws"!=r.type?"":r.string+s(e,t,r.end+1)};t.exports={addPrefixes:n,getPrefixesFromQuery:o,removePrefixes:i}},{}],40:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports={use:function(e){e.executeQuery=function(t,i){var o="function"==typeof i?i:null,s="object"==typeof i?i:{},a=t.getQueryMode();t.options.sparql&&(s=n.extend({},t.options.sparql,s));s.handlers&&n.extend(!0,s.callbacks,s.handlers);if(s.endpoint&&0!=s.endpoint.length){var l={url:"function"==typeof s.endpoint?s.endpoint(t):s.endpoint,type:"function"==typeof s.requestMethod?s.requestMethod(t):s.requestMethod,data:[{name:a,value:t.getValue()}],headers:{Accept:r(t,s)}},u=!1;if(s.callbacks)for(var p in s.callbacks)if(s.callbacks[p]){u=!0;l[p]=s.callbacks[p]}if(u||o){o&&(l.complete=o);if(s.namedGraphs&&s.namedGraphs.length>0)for(var c="query"==a?"named-graph-uri":"using-named-graph-uri ",d=0;d<s.namedGraphs.length;d++)l.data.push({name:c,value:s.namedGraphs[d]});if(s.defaultGraphs&&s.defaultGraphs.length>0)for(var c="query"==a?"default-graph-uri":"using-graph-uri ",d=0;d<s.defaultGraphs.length;d++)l.data.push({name:c,value:s.defaultGraphs[d]});s.headers&&!n.isEmptyObject(s.headers)&&n.extend(l.headers,s.headers);s.args&&s.args.length>0&&n.merge(l.data,s.args);e.updateQueryButton(t,"busy");var f=function(){e.updateQueryButton(t)};l.complete=l.complete?[f,l.complete]:f;t.xhr=n.ajax(l)}}}}};var r=function(e,t){var n=null;if(!t.acceptHeader||t.acceptHeaderGraph||t.acceptHeaderSelect||t.acceptHeaderUpdate)if("update"==e.getQueryMode())n="function"==typeof t.acceptHeader?t.acceptHeaderUpdate(e):t.acceptHeaderUpdate;else{var r=e.getQueryType();n="DESCRIBE"==r||"CONSTRUCT"==r?"function"==typeof t.acceptHeaderGraph?t.acceptHeaderGraph(e):t.acceptHeaderGraph:"function"==typeof t.acceptHeaderSelect?t.acceptHeaderSelect(e):t.acceptHeaderSelect}else n="function"==typeof t.acceptHeader?t.acceptHeader(e):t.acceptHeader;return n}},{jquery:void 0}],41:[function(e,t){"use strict";var n=function(e,t,r){r||(r=e.getCursor());t||(t=e.getTokenAt(r));var i=e.getTokenAt({line:r.line,ch:t.start});if(null!=i.type&&"ws"!=i.type&&null!=t.type&&"ws"!=t.type){t.start=i.start;t.string=i.string+t.string;return n(e,t,{line:r.line,ch:i.start})}if(null!=t.type&&"ws"==t.type){t.start=t.start+1;t.string=t.string.substring(1);return t}return t},r=function(e,t,n){var i=e.getTokenAt({line:t,ch:n.start});null!=i&&"ws"==i.type&&(i=r(e,t,i));return i},i=function(e,t,n){void 0==n&&(n=1);var r=e.getTokenAt({line:t,ch:n});return null==r||void 0==r||r.end<n?null:"ws"==r.type?i(e,t,r.end+1):r};t.exports={getPreviousNonWsToken:r,getCompleteToken:n,getNextNonWsToken:i}},{}],42:[function(e,t){"use strict";{var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("./utils.js")}t.exports=function(e,t,r){var i,t=n(t);t.hover(function(){"function"==typeof r&&(r=r());i=n("<div>").addClass("yasqe_tooltip").html(r).appendTo(t);o()},function(){n(".yasqe_tooltip").remove()});var o=function(){if(n(e.getWrapperElement()).offset().top>=i.offset().top){i.css("bottom","auto");i.css("top","26px")}}}},{"./utils.js":43,jquery:void 0}],43:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=function(e,t){var n=!1;try{void 0!==e[t]&&(n=!0)}catch(r){}return n},i=function(e,t){var n=null;t&&(n="string"==typeof t?t:t(e));return n},o=function(){function e(e){var t,r,i;t=n(e).offset();r=n(e).width();i=n(e).height();return[[t.left,t.left+r],[t.top,t.top+i]]}function t(e,t){var n,r;n=e[0]<t[0]?e:t;r=e[0]<t[0]?t:e;return n[1]>r[0]||n[0]===r[0]}return function(n,r){var i=e(n),o=e(r);return t(i[0],o[0])&&t(i[1],o[1])}}();t.exports={keyExists:r,getPersistencyId:i,elementsOverlap:o}},{jquery:void 0}],44:[function(e){var t,n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=n(document),i=n("head"),o=null,s=[],a=0,l="id",u="px",p="JColResizer",c=parseInt,d=Math,f=navigator.userAgent.indexOf("Trident/4.0")>0;try{t=sessionStorage}catch(h){}i.append("<style type='text/css'> .JColResizer{table-layout:fixed;} .JColResizer td, .JColResizer th{overflow:hidden;padding-left:0!important; padding-right:0!important;} .JCLRgrips{ height:0px; position:relative;} .JCLRgrip{margin-left:-5px; position:absolute; z-index:5; } .JCLRgrip .JColResizer{position:absolute;background-color:red;filter:alpha(opacity=1);opacity:0;width:10px;height:100%;top:0px} .JCLRLastGrip{position:absolute; width:1px; } .JCLRgripDrag{ border-left:1px dotted black; }</style>");var g=function(e,t){var r=n(e);if(t.disable)return m(r);var i=r.id=r.attr(l)||p+a++;r.p=t.postbackSafe;if(r.is("table")&&!s[i]){r.addClass(p).attr(l,i).before('<div class="JCLRgrips"/>');r.opt=t;r.g=[];r.c=[];r.w=r.width();r.gc=r.prev();t.marginLeft&&r.gc.css("marginLeft",t.marginLeft);t.marginRight&&r.gc.css("marginRight",t.marginRight);r.cs=c(f?e.cellSpacing||e.currentStyle.borderSpacing:r.css("border-spacing"))||2;r.b=c(f?e.border||e.currentStyle.borderLeftWidth:r.css("border-left-width"))||1;s[i]=r;E(r)}},m=function(e){var t=e.attr(l),e=s[t];if(e&&e.is("table")){e.removeClass(p).gc.remove();delete s[t]}},E=function(e){var r=e.find(">thead>tr>th,>thead>tr>td");r.length||(r=e.find(">tbody>tr:first>th,>tr:first>th,>tbody>tr:first>td, >tr:first>td"));e.cg=e.find("col");e.ln=r.length;e.p&&t&&t[e.id]&&v(e,r);r.each(function(t){var r=n(this),i=n(e.gc.append('<div class="JCLRgrip"></div>')[0].lastChild);i.t=e;i.i=t;i.c=r;r.w=r.width();e.g.push(i);e.c.push(r);r.width(r.w).removeAttr("width");t<e.ln-1?i.bind("touchstart mousedown",A).append(e.opt.gripInnerHtml).append('<div class="'+p+'" style="cursor:'+e.opt.hoverCursor+'"></div>'):i.addClass("JCLRLastGrip").removeClass("JCLRgrip");i.data(p,{i:t,t:e.attr(l)})});e.cg.removeAttr("width");x(e);e.find("td, th").not(r).not("table th, table td").each(function(){n(this).removeAttr("width")})},v=function(e,n){var r,i=0,o=0,s=[];if(n){e.cg.removeAttr("width");if(e.opt.flush){t[e.id]="";return}r=t[e.id].split(";");for(;o<e.ln;o++){s.push(100*r[o]/r[e.ln]+"%");n.eq(o).css("width",s[o])}for(o=0;o<e.ln;o++)e.cg.eq(o).css("width",s[o])}else{t[e.id]="";for(;o<e.c.length;o++){r=e.c[o].width();t[e.id]+=r+";";i+=r}t[e.id]+=i}},x=function(e){e.gc.width(e.w);for(var t=0;t<e.ln;t++){var n=e.c[t];e.g[t].css({left:n.offset().left-e.offset().left+n.outerWidth(!1)+e.cs/2+u,height:e.opt.headerOnly?e.c[0].outerHeight(!1):e.outerHeight(!1)})}},y=function(e,t,n){var r=o.x-o.l,i=e.c[t],s=e.c[t+1],a=i.w+r,l=s.w-r;i.width(a+u);s.width(l+u);e.cg.eq(t).width(a+u);e.cg.eq(t+1).width(l+u);if(n){i.w=a;s.w=l}},N=function(e){if(o){var t=o.t;if(e.originalEvent.touches)var n=e.originalEvent.touches[0].pageX-o.ox+o.l;else var n=e.pageX-o.ox+o.l;var r=t.opt.minWidth,i=o.i,s=1.5*t.cs+r+t.b,a=i==t.ln-1?t.w-s:t.g[i+1].position().left-t.cs-r,l=i?t.g[i-1].position().left+t.cs+r:s;n=d.max(l,d.min(a,n));o.x=n;o.css("left",n+u);if(t.opt.liveDrag){y(t,i);x(t);var p=t.opt.onDrag;if(p){e.currentTarget=t[0];p(e)}}return!1}},I=function(e){r.unbind("touchend."+p+" mouseup."+p).unbind("touchmove."+p+" mousemove."+p);n("head :last-child").remove();if(o){o.removeClass(o.t.opt.draggingClass);var i=o.t,s=i.opt.onResize;if(o.x){y(i,o.i,!0);x(i);if(s){e.currentTarget=i[0];s(e)}}i.p&&t&&v(i);o=null}},A=function(e){var t=n(this).data(p),a=s[t.t],l=a.g[t.i];l.ox=e.originalEvent.touches?e.originalEvent.touches[0].pageX:e.pageX;l.l=l.position().left;r.bind("touchmove."+p+" mousemove."+p,N).bind("touchend."+p+" mouseup."+p,I);i.append("<style type='text/css'>*{cursor:"+a.opt.dragCursor+"!important}</style>");l.addClass(a.opt.draggingClass);o=l;if(a.c[t.i].l)for(var u,c=0;c<a.ln;c++){u=a.c[c];u.l=!1;u.w=u.width()}return!1},T=function(){for(t in s){var e,t=s[t],n=0;t.removeClass(p);if(t.w!=t.width()){t.w=t.width();for(e=0;e<t.ln;e++)n+=t.c[e].w;for(e=0;e<t.ln;e++)t.c[e].css("width",d.round(1e3*t.c[e].w/n)/10+"%").l=!0}x(t.addClass(p))}};n(window).bind("resize."+p,T);n.fn.extend({colResizable:function(e){var t={draggingClass:"JCLRgripDrag",gripInnerHtml:"",liveDrag:!1,minWidth:15,headerOnly:!1,hoverCursor:"e-resize",dragCursor:"e-resize",postbackSafe:!1,flush:!1,marginLeft:null,marginRight:null,disable:!1,onDrag:null,onResize:null},e=n.extend(t,e);return this.each(function(){g(this,e)})}})},{jquery:void 0}],45:[function(e){RegExp.escape=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.csv={defaults:{separator:",",delimiter:'"',headers:!0},hooks:{castToScalar:function(e){var t=/\./;if(isNaN(e))return e;if(t.test(e))return parseFloat(e);var n=parseInt(e);return isNaN(n)?null:n}},parsers:{parse:function(e,t){function n(){l=0;u="";if(t.start&&t.state.rowNum<t.start){a=[];t.state.rowNum++;t.state.colNum=1}else{if(void 0===t.onParseEntry)s.push(a);else{var e=t.onParseEntry(a,t.state);e!==!1&&s.push(e)}a=[];t.end&&t.state.rowNum>=t.end&&(p=!0);t.state.rowNum++;t.state.colNum=1}}function r(){if(void 0===t.onParseValue)a.push(u);else{var e=t.onParseValue(u,t.state);e!==!1&&a.push(e)}u="";l=0;t.state.colNum++}var i=t.separator,o=t.delimiter;t.state.rowNum||(t.state.rowNum=1);t.state.colNum||(t.state.colNum=1);var s=[],a=[],l=0,u="",p=!1,c=RegExp.escape(i),d=RegExp.escape(o),f=/(D|S|\n|\r|[^DS\r\n]+)/,h=f.source;h=h.replace(/S/g,c);h=h.replace(/D/g,d);f=RegExp(h,"gm");e.replace(f,function(e){if(!p)switch(l){case 0:if(e===i){u+="";r();break}if(e===o){l=1;break}if("\n"===e){r();n();break}if(/^\r$/.test(e))break;u+=e;l=3;break;case 1:if(e===o){l=2;break}u+=e;l=1;break;case 2:if(e===o){u+=e;l=1;break}if(e===i){r();break}if("\n"===e){r();n();break}if(/^\r$/.test(e))break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===i){r();break}if("\n"===e){r();n();break}if(/^\r$/.test(e))break;if(e===o)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}});if(0!==a.length){r();n()}return s},splitLines:function(e,t){function n(){s=0;if(t.start&&t.state.rowNum<t.start){a="";t.state.rowNum++}else{if(void 0===t.onParseEntry)o.push(a);else{var e=t.onParseEntry(a,t.state);e!==!1&&o.push(e)}a="";t.end&&t.state.rowNum>=t.end&&(l=!0);t.state.rowNum++}}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1);var o=[],s=0,a="",l=!1,u=RegExp.escape(r),p=RegExp.escape(i),c=/(D|S|\n|\r|[^DS\r\n]+)/,d=c.source;d=d.replace(/S/g,u);d=d.replace(/D/g,p);c=RegExp(d,"gm");e.replace(c,function(e){if(!l)switch(s){case 0:if(e===r){a+=e;s=0;break}if(e===i){a+=e;s=1;break}if("\n"===e){n();break}if(/^\r$/.test(e))break;a+=e;s=3;break;case 1:if(e===i){a+=e;s=2;break}a+=e;s=1;break;case 2:var o=a.substr(a.length-1);if(e===i&&o===i){a+=e;s=1;break}if(e===r){a+=e;s=0;break}if("\n"===e){n();break}if("\r"===e)break;throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");case 3:if(e===r){a+=e;s=0;break}if("\n"===e){n();break}if("\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal quote [Row:"+t.state.rowNum+"]");throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");default:throw new Error("CSVDataError: Unknown state [Row:"+t.state.rowNum+"]")}});""!==a&&n();return o},parseEntry:function(e,t){function n(){if(void 0===t.onParseValue)o.push(a);else{var e=t.onParseValue(a,t.state);e!==!1&&o.push(e)}a="";s=0;t.state.colNum++}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1);t.state.colNum||(t.state.colNum=1);var o=[],s=0,a="";if(!t.match){var l=RegExp.escape(r),u=RegExp.escape(i),p=/(D|S|\n|\r|[^DS\r\n]+)/,c=p.source;c=c.replace(/S/g,l);c=c.replace(/D/g,u);t.match=RegExp(c,"gm")}e.replace(t.match,function(e){switch(s){case 0:if(e===r){a+="";n();break}if(e===i){s=1;break}if("\n"===e||"\r"===e)break;a+=e;s=3;break;case 1:if(e===i){s=2;break}a+=e;s=1;break;case 2:if(e===i){a+=e;s=1;break}if(e===r){n();break}if("\n"===e||"\r"===e)break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===r){n();break}if("\n"===e||"\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}});n();return o}},toArray:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;var o=void 0!==n.state?n.state:{},n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,state:o},s=t.csv.parsers.parseEntry(e,n);if(!i.callback)return s;i.callback("",s);return void 0},toArrays:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;var o=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1}};o=t.csv.parsers.parse(e,n);if(!i.callback)return o;i.callback("",o);return void 0},toObjects:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;i.headers="headers"in n?n.headers:t.csv.defaults.headers;n.start="start"in n?n.start:1;i.headers&&n.start++;n.end&&i.headers&&n.end++;var o=[],s=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1},match:!1},a={delimiter:i.delimiter,separator:i.separator,start:1,end:1,state:{rowNum:1,colNum:1}},l=t.csv.parsers.splitLines(e,a),u=t.csv.toArray(l[0],n),o=t.csv.parsers.splitLines(e,n);n.state.colNum=1;n.state.rowNum=u?2:1;for(var p=0,c=o.length;c>p;p++){var d=t.csv.toArray(o[p],n),f={};for(var h in u)f[u[h]]=d[h];s.push(f);n.state.rowNum++}if(!i.callback)return s;i.callback("",s);return void 0},fromArrays:function(e,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:t.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;o.escaper="escaper"in n?n.escaper:t.csv.defaults.escaper;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var s=[];for(i in e)s.push(e[i]);if(!o.callback)return s;o.callback("",s);return void 0},fromObjects2CSV:function(e,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:t.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var s=[];for(i in e)s.push(arrays[i]);if(!o.callback)return s;o.callback("",s);return void 0}};t.csvEntry2Array=t.csv.toArray;t.csv2Array=t.csv.toArrays;t.csv2Dictionary=t.csv.toObjects},{jquery:void 0}],46:[function(e,t){t.exports=e(16)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/edit/matchbrackets.js":16,codemirror:void 0}],47:[function(e,t){t.exports=e(17)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/brace-fold.js":17,codemirror:void 0}],48:[function(e,t){t.exports=e(18)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/foldcode.js":18,codemirror:void 0}],49:[function(e,t){t.exports=e(19)},{"./foldcode":48,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/foldgutter.js":19,codemirror:void 0}],50:[function(e,t){t.exports=e(20)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/codemirror/addon/fold/xml-fold.js":20,codemirror:void 0}],51:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.defineMode("javascript",function(t,n){function r(e){for(var t,n=!1,r=!1;null!=(t=e.next());){if(!n){if("/"==t&&!r)return;"["==t?r=!0:r&&"]"==t&&(r=!1)}n=!n&&"\\"==t}}function i(e,t,n){gt=e;mt=n;return t}function o(e,t){var n=e.next();if('"'==n||"'"==n){t.tokenize=s(n);return t.tokenize(e,t)}if("."==n&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return i("number","number");if("."==n&&e.match(".."))return i("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return i(n);if("="==n&&e.eat(">"))return i("=>","operator");if("0"==n&&e.eat(/x/i)){e.eatWhile(/[\da-f]/i);return i("number","number")}if(/\d/.test(n)){e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);return i("number","number")}if("/"==n){if(e.eat("*")){t.tokenize=a;return a(e,t)}if(e.eat("/")){e.skipToEnd();return i("comment","comment")}if("operator"==t.lastType||"keyword c"==t.lastType||"sof"==t.lastType||/^[\[{}\(,;:]$/.test(t.lastType)){r(e);e.eatWhile(/[gimy]/);return i("regexp","string-2")}e.eatWhile(Tt);return i("operator","operator",e.current())}if("`"==n){t.tokenize=l;return l(e,t)}if("#"==n){e.skipToEnd();return i("error","error")}if(Tt.test(n)){e.eatWhile(Tt);return i("operator","operator",e.current())}if(It.test(n)){e.eatWhile(It);var o=e.current(),u=At.propertyIsEnumerable(o)&&At[o];return u&&"."!=t.lastType?i(u.type,u.style,o):i("variable","variable",o)}}function s(e){return function(t,n){var r,s=!1;if(xt&&"@"==t.peek()&&t.match(Lt)){n.tokenize=o;return i("jsonld-keyword","meta")}for(;null!=(r=t.next())&&(r!=e||s);)s=!s&&"\\"==r;s||(n.tokenize=o);return i("string","string")}}function a(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=o;break}r="*"==n}return i("comment","comment")}function l(e,t){for(var n,r=!1;null!=(n=e.next());){if(!r&&("`"==n||"$"==n&&e.eat("{"))){t.tokenize=o;break}r=!r&&"\\"==n}return i("quasi","string-2",e.current())}function u(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(!(0>n)){for(var r=0,i=!1,o=n-1;o>=0;--o){var s=e.string.charAt(o),a=St.indexOf(s);if(a>=0&&3>a){if(!r){++o;break}if(0==--r)break}else if(a>=3&&6>a)++r;else if(It.test(s))i=!0;else{if(/["'\/]/.test(s))return;if(i&&!r){++o;break}}}i&&!r&&(t.fatArrowAt=o)}}function p(e,t,n,r,i,o){this.indented=e;this.column=t;this.type=n;this.prev=i;this.info=o;null!=r&&(this.align=r)}function c(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var r=e.context;r;r=r.prev)for(var n=r.vars;n;n=n.next)if(n.name==t)return!0}function d(e,t,n,r,i){var o=e.cc;bt.state=e;bt.stream=i;bt.marked=null,bt.cc=o;bt.style=t;e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);for(;;){var s=o.length?o.pop():yt?I:N;if(s(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return bt.marked?bt.marked:"variable"==n&&c(e,r)?"variable-2":t}}}function f(){for(var e=arguments.length-1;e>=0;e--)bt.cc.push(arguments[e])}function h(){f.apply(null,arguments);return!0}function g(e){function t(t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}var r=bt.state;if(r.context){bt.marked="def";if(t(r.localVars))return;r.localVars={name:e,next:r.localVars}}else{if(t(r.globalVars))return;n.globalVars&&(r.globalVars={name:e,next:r.globalVars})}}function m(){bt.state.context={prev:bt.state.context,vars:bt.state.localVars};bt.state.localVars=Rt}function E(){bt.state.localVars=bt.state.context.vars;bt.state.context=bt.state.context.prev}function v(e,t){var n=function(){var n=bt.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new p(r,bt.stream.column(),e,null,n.lexical,t)};n.lex=!0;return n}function x(){var e=bt.state;if(e.lexical.prev){")"==e.lexical.type&&(e.indented=e.lexical.indented);e.lexical=e.lexical.prev}}function y(e){function t(n){return n==e?h():";"==e?f():h(t)}return t}function N(e,t){if("var"==e)return h(v("vardef",t.length),V,y(";"),x);if("keyword a"==e)return h(v("form"),I,N,x);if("keyword b"==e)return h(v("form"),N,x);if("{"==e)return h(v("}"),B,x);if(";"==e)return h();if("if"==e){"else"==bt.state.lexical.info&&bt.state.cc[bt.state.cc.length-1]==x&&bt.state.cc.pop()();return h(v("form"),I,N,x,Y)}return"function"==e?h(et):"for"==e?h(v("form"),K,N,x):"variable"==e?h(v("stat"),F):"switch"==e?h(v("form"),I,v("}","switch"),y("{"),B,x,x):"case"==e?h(I,y(":")):"default"==e?h(y(":")):"catch"==e?h(v("form"),m,y("("),tt,y(")"),N,x,E):"module"==e?h(v("form"),m,st,E,x):"class"==e?h(v("form"),nt,x):"export"==e?h(v("form"),at,x):"import"==e?h(v("form"),lt,x):f(v("stat"),I,y(";"),x)}function I(e){return T(e,!1)}function A(e){return T(e,!0)}function T(e,t){if(bt.state.fatArrowAt==bt.stream.start){var n=t?_:O;if("("==e)return h(m,v(")"),G(H,")"),x,y("=>"),n,E);if("variable"==e)return f(m,H,y("=>"),n,E)}var r=t?b:C;return Ct.hasOwnProperty(e)?h(r):"function"==e?h(et,r):"keyword c"==e?h(t?S:L):"("==e?h(v(")"),L,ft,y(")"),x,r):"operator"==e||"spread"==e?h(t?A:I):"["==e?h(v("]"),ct,x,r):"{"==e?U(M,"}",null,r):"quasi"==e?f(R,r):h()}function L(e){return e.match(/[;\}\)\],]/)?f():f(I)}function S(e){return e.match(/[;\}\)\],]/)?f():f(A)}function C(e,t){return","==e?h(I):b(e,t,!1)}function b(e,t,n){var r=0==n?C:b,i=0==n?I:A;return"=>"==e?h(m,n?_:O,E):"operator"==e?/\+\+|--/.test(t)?h(r):"?"==t?h(I,y(":"),i):h(i):"quasi"==e?f(R,r):";"!=e?"("==e?U(A,")","call",r):"."==e?h(P,r):"["==e?h(v("]"),L,y("]"),x,r):void 0:void 0}function R(e,t){return"quasi"!=e?f():"${"!=t.slice(t.length-2)?h(R):h(I,w)}function w(e){if("}"==e){bt.marked="string-2";bt.state.tokenize=l;return h(R)}}function O(e){u(bt.stream,bt.state);return f("{"==e?N:I)}function _(e){u(bt.stream,bt.state);return f("{"==e?N:A)}function F(e){return":"==e?h(x,N):f(C,y(";"),x)}function P(e){if("variable"==e){bt.marked="property";return h()}}function M(e,t){if("variable"==e||"keyword"==bt.style){bt.marked="property";return h("get"==t||"set"==t?k:D)}if("number"==e||"string"==e){bt.marked=xt?"property":bt.style+" property";return h(D)}return"jsonld-keyword"==e?h(D):"["==e?h(I,y("]"),D):void 0}function k(e){if("variable"!=e)return f(D);bt.marked="property";return h(et)}function D(e){return":"==e?h(A):"("==e?f(et):void 0}function G(e,t){function n(r){if(","==r){var i=bt.state.lexical;"call"==i.info&&(i.pos=(i.pos||0)+1);return h(e,n)}return r==t?h():h(y(t))}return function(r){return r==t?h():f(e,n)}}function U(e,t,n){for(var r=3;r<arguments.length;r++)bt.cc.push(arguments[r]);return h(v(t,n),G(e,t),x)}function B(e){return"}"==e?h():f(N,B)}function j(e){return Nt&&":"==e?h(q):void 0}function q(e){if("variable"==e){bt.marked="variable-3";return h()}}function V(){return f(H,j,W,$)}function H(e,t){if("variable"==e){g(t);return h()}return"["==e?U(H,"]"):"{"==e?U(z,"}"):void 0}function z(e,t){if("variable"==e&&!bt.stream.match(/^\s*:/,!1)){g(t);return h(W)}"variable"==e&&(bt.marked="property");return h(y(":"),H,W)}function W(e,t){return"="==t?h(A):void 0}function $(e){return","==e?h(V):void 0}function Y(e,t){return"keyword b"==e&&"else"==t?h(v("form","else"),N,x):void 0}function K(e){return"("==e?h(v(")"),Q,y(")"),x):void 0}function Q(e){return"var"==e?h(V,y(";"),Z):";"==e?h(Z):"variable"==e?h(X):f(I,y(";"),Z)}function X(e,t){if("in"==t||"of"==t){bt.marked="keyword";return h(I)}return h(C,Z)}function Z(e,t){if(";"==e)return h(J);if("in"==t||"of"==t){bt.marked="keyword";return h(I)}return f(I,y(";"),J)}function J(e){")"!=e&&h(I)}function et(e,t){if("*"==t){bt.marked="keyword";return h(et)}if("variable"==e){g(t);return h(et)}return"("==e?h(m,v(")"),G(tt,")"),x,N,E):void 0}function tt(e){return"spread"==e?h(tt):f(H,j)}function nt(e,t){if("variable"==e){g(t);return h(rt)}}function rt(e,t){return"extends"==t?h(I,rt):"{"==e?h(v("}"),it,x):void 0}function it(e,t){if("variable"==e||"keyword"==bt.style){bt.marked="property";return"get"==t||"set"==t?h(ot,et,it):h(et,it)}if("*"==t){bt.marked="keyword";return h(it)}return";"==e?h(it):"}"==e?h():void 0}function ot(e){if("variable"!=e)return f();bt.marked="property";return h()}function st(e,t){if("string"==e)return h(N);if("variable"==e){g(t);return h(pt)}}function at(e,t){if("*"==t){bt.marked="keyword";return h(pt,y(";"))}if("default"==t){bt.marked="keyword";return h(I,y(";"))}return f(N)}function lt(e){return"string"==e?h():f(ut,pt)}function ut(e,t){if("{"==e)return U(ut,"}");"variable"==e&&g(t);return h()}function pt(e,t){if("from"==t){bt.marked="keyword";return h(I)}}function ct(e){return"]"==e?h():f(A,dt)}function dt(e){return"for"==e?f(ft,y("]")):","==e?h(G(S,"]")):f(G(A,"]"))}function ft(e){return"for"==e?h(K,ft):"if"==e?h(I,ft):void 0}function ht(e,t){return"operator"==e.lastType||","==e.lastType||Tt.test(t.charAt(0))||/[,.]/.test(t.charAt(0))}var gt,mt,Et=t.indentUnit,vt=n.statementIndent,xt=n.jsonld,yt=n.json||xt,Nt=n.typescript,It=n.wordCharacters||/[\w$\xa1-\uffff]/,At=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),n=e("keyword b"),r=e("keyword c"),i=e("operator"),o={type:"atom",style:"atom"},s={"if":e("if"),"while":t,"with":t,"else":n,"do":n,"try":n,"finally":n,"return":r,"break":r,"continue":r,"new":r,"delete":r,"throw":r,"debugger":r,"var":e("var"),"const":e("var"),let:e("var"),"function":e("function"),"catch":e("catch"),"for":e("for"),"switch":e("switch"),"case":e("case"),"default":e("default"),"in":i,"typeof":i,"instanceof":i,"true":o,"false":o,"null":o,undefined:o,NaN:o,Infinity:o,"this":e("this"),module:e("module"),"class":e("class"),"super":e("atom"),"yield":r,"export":e("export"),"import":e("import"),"extends":r};if(Nt){var a={type:"variable",style:"variable-3"},l={"interface":e("interface"),"extends":e("extends"),constructor:e("constructor"),"public":e("public"),"private":e("private"),"protected":e("protected"),"static":e("static"),string:a,number:a,bool:a,any:a};for(var u in l)s[u]=l[u]}return s}(),Tt=/[+\-*&%=<>!?|~^]/,Lt=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,St="([{}])",Ct={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},bt={state:null,column:null,marked:null,cc:null},Rt={name:"this",next:{name:"arguments"}};x.lex=!0;return{startState:function(e){var t={tokenize:o,lastType:"sof",cc:[],lexical:new p((e||0)-Et,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:0};n.globalVars&&"object"==typeof n.globalVars&&(t.globalVars=n.globalVars);return t},token:function(e,t){if(e.sol()){t.lexical.hasOwnProperty("align")||(t.lexical.align=!1);t.indented=e.indentation();u(e,t)}if(t.tokenize!=a&&e.eatSpace())return null;var n=t.tokenize(e,t);if("comment"==gt)return n;t.lastType="operator"!=gt||"++"!=mt&&"--"!=mt?gt:"incdec";return d(t,n,gt,mt,e)},indent:function(t,r){if(t.tokenize==a)return e.Pass;if(t.tokenize!=o)return 0;var i=r&&r.charAt(0),s=t.lexical;if(!/^\s*else\b/.test(r))for(var l=t.cc.length-1;l>=0;--l){var u=t.cc[l];if(u==x)s=s.prev;else if(u!=Y)break}"stat"==s.type&&"}"==i&&(s=s.prev);vt&&")"==s.type&&"stat"==s.prev.type&&(s=s.prev);var p=s.type,c=i==p;return"vardef"==p?s.indented+("operator"==t.lastType||","==t.lastType?s.info+1:0):"form"==p&&"{"==i?s.indented:"form"==p?s.indented+Et:"stat"==p?s.indented+(ht(t,r)?vt||Et:0):"switch"!=s.info||c||0==n.doubleIndentSwitch?s.align?s.column+(c?0:1):s.indented+(c?0:Et):s.indented+(/^(?:case|default)\b/.test(r)?Et:2*Et)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:yt?null:"/*",blockCommentEnd:yt?null:"*/",lineComment:yt?null:"//",fold:"brace",helperType:yt?"json":"javascript",jsonldMode:xt,jsonMode:yt}});e.registerHelper("wordChars","javascript",/[\w$]/);e.defineMIME("text/javascript","javascript");e.defineMIME("text/ecmascript","javascript");e.defineMIME("application/javascript","javascript");e.defineMIME("application/x-javascript","javascript");e.defineMIME("application/ecmascript","javascript");e.defineMIME("application/json",{name:"javascript",json:!0});e.defineMIME("application/x-json",{name:"javascript",json:!0});e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});e.defineMIME("text/typescript",{name:"javascript",typescript:!0});e.defineMIME("application/typescript",{name:"javascript",typescript:!0})})},{codemirror:void 0}],52:[function(t,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)})(function(e){"use strict";e.defineMode("xml",function(t,n){function r(e,t){function n(n){t.tokenize=n;return n(e,t)}var r=e.next();if("<"==r){if(e.eat("!")){if(e.eat("["))return e.match("CDATA[")?n(s("atom","]]>")):null;if(e.match("--"))return n(s("comment","-->"));if(e.match("DOCTYPE",!0,!0)){e.eatWhile(/[\w\._\-]/);return n(a(1))}return null}if(e.eat("?")){e.eatWhile(/[\w\._\-]/);t.tokenize=s("meta","?>");return"meta"}A=e.eat("/")?"closeTag":"openTag";t.tokenize=i;return"tag bracket"}if("&"==r){var o;o=e.eat("#")?e.eat("x")?e.eatWhile(/[a-fA-F\d]/)&&e.eat(";"):e.eatWhile(/[\d]/)&&e.eat(";"):e.eatWhile(/[\w\.\-:]/)&&e.eat(";");return o?"atom":"error"}e.eatWhile(/[^&<]/);return null}function i(e,t){var n=e.next();if(">"==n||"/"==n&&e.eat(">")){t.tokenize=r;A=">"==n?"endTag":"selfcloseTag";return"tag bracket"}if("="==n){A="equals";return null}if("<"==n){t.tokenize=r;t.state=c;t.tagName=t.tagStart=null;var i=t.tokenize(e,t);return i?i+" tag error":"tag error"}if(/[\'\"]/.test(n)){t.tokenize=o(n);t.stringStartCol=e.column();return t.tokenize(e,t)}e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);return"word"}function o(e){var t=function(t,n){for(;!t.eol();)if(t.next()==e){n.tokenize=i;break}return"string"};t.isInAttribute=!0;return t}function s(e,t){return function(n,i){for(;!n.eol();){if(n.match(t)){i.tokenize=r;break}n.next()}return e}}function a(e){return function(t,n){for(var i;null!=(i=t.next());){if("<"==i){n.tokenize=a(e+1);return n.tokenize(t,n)}if(">"==i){if(1==e){n.tokenize=r;break}n.tokenize=a(e-1);return n.tokenize(t,n)}}return"meta"}}function l(e,t,n){this.prev=e.context;this.tagName=t;this.indent=e.indented;this.startOfLine=n;(L.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)&&(this.noIndent=!0)}function u(e){e.context&&(e.context=e.context.prev)}function p(e,t){for(var n;;){if(!e.context)return;n=e.context.tagName;
if(!L.contextGrabbers.hasOwnProperty(n)||!L.contextGrabbers[n].hasOwnProperty(t))return;u(e)}}function c(e,t,n){if("openTag"==e){n.tagStart=t.column();return d}return"closeTag"==e?f:c}function d(e,t,n){if("word"==e){n.tagName=t.current();T="tag";return m}T="error";return d}function f(e,t,n){if("word"==e){var r=t.current();n.context&&n.context.tagName!=r&&L.implicitlyClosed.hasOwnProperty(n.context.tagName)&&u(n);if(n.context&&n.context.tagName==r){T="tag";return h}T="tag error";return g}T="error";return g}function h(e,t,n){if("endTag"!=e){T="error";return h}u(n);return c}function g(e,t,n){T="error";return h(e,t,n)}function m(e,t,n){if("word"==e){T="attribute";return E}if("endTag"==e||"selfcloseTag"==e){var r=n.tagName,i=n.tagStart;n.tagName=n.tagStart=null;if("selfcloseTag"==e||L.autoSelfClosers.hasOwnProperty(r))p(n,r);else{p(n,r);n.context=new l(n,r,i==n.indented)}return c}T="error";return m}function E(e,t,n){if("equals"==e)return v;L.allowMissing||(T="error");return m(e,t,n)}function v(e,t,n){if("string"==e)return x;if("word"==e&&L.allowUnquoted){T="string";return m}T="error";return m(e,t,n)}function x(e,t,n){return"string"==e?x:m(e,t,n)}var y=t.indentUnit,N=n.multilineTagIndentFactor||1,I=n.multilineTagIndentPastTag;null==I&&(I=!0);var A,T,L=n.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},S=n.alignCDATA;return{startState:function(){return{tokenize:r,state:c,indented:0,tagName:null,tagStart:null,context:null}},token:function(e,t){!t.tagName&&e.sol()&&(t.indented=e.indentation());if(e.eatSpace())return null;A=null;var n=t.tokenize(e,t);if((n||A)&&"comment"!=n){T=null;t.state=t.state(A||n,e,t);T&&(n="error"==T?n+" error":T)}return n},indent:function(t,n,o){var s=t.context;if(t.tokenize.isInAttribute)return t.tagStart==t.indented?t.stringStartCol+1:t.indented+y;if(s&&s.noIndent)return e.Pass;if(t.tokenize!=i&&t.tokenize!=r)return o?o.match(/^(\s*)/)[0].length:0;if(t.tagName)return I?t.tagStart+t.tagName.length+2:t.tagStart+y*N;if(S&&/<!\[CDATA\[/.test(n))return 0;var a=n&&/^<(\/)?([\w_:\.-]*)/.exec(n);if(a&&a[1])for(;s;){if(s.tagName==a[2]){s=s.prev;break}if(!L.implicitlyClosed.hasOwnProperty(s.tagName))break;s=s.prev}else if(a)for(;s;){var l=L.contextGrabbers[s.tagName];if(!l||!l.hasOwnProperty(a[2]))break;s=s.prev}for(;s&&!s.startOfLine;)s=s.prev;return s?s.indent+y:0},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:n.htmlMode?"html":"xml",helperType:n.htmlMode?"html":"xml"}});e.defineMIME("text/xml","xml");e.defineMIME("application/xml","xml");e.mimeModes.hasOwnProperty("text/html")||e.defineMIME("text/html",{name:"xml",htmlMode:!0})})},{codemirror:void 0}],53:[function(t,n){!function(){function t(e,t){return t>e?-1:e>t?1:e>=t?0:0/0}function r(e){return null===e?0/0:+e}function i(e){return!isNaN(e)}function o(e){return{left:function(t,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=t.length);for(;i>r;){var o=r+i>>>1;e(t[o],n)<0?r=o+1:i=o}return r},right:function(t,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=t.length);for(;i>r;){var o=r+i>>>1;e(t[o],n)>0?i=o:r=o+1}return r}}}function s(e){return e.length}function a(e){for(var t=1;e*t%1;)t*=10;return t}function l(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function u(){this._=Object.create(null)}function p(e){return(e+="")===xa||e[0]===ya?ya+e:e}function c(e){return(e+="")[0]===ya?e.slice(1):e}function d(e){return p(e)in this._}function f(e){return(e=p(e))in this._&&delete this._[e]}function h(){var e=[];for(var t in this._)e.push(c(t));return e}function g(){var e=0;for(var t in this._)++e;return e}function m(){for(var e in this._)return!1;return!0}function E(){this._=Object.create(null)}function v(e,t,n){return function(){var r=n.apply(t,arguments);return r===t?e:r}}function x(e,t){if(t in e)return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var n=0,r=Na.length;r>n;++n){var i=Na[n]+t;if(i in e)return i}}function y(){}function N(){}function I(e){function t(){for(var t,r=n,i=-1,o=r.length;++i<o;)(t=r[i].on)&&t.apply(this,arguments);return e}var n=[],r=new u;t.on=function(t,i){var o,s=r.get(t);if(arguments.length<2)return s&&s.on;if(s){s.on=null;n=n.slice(0,o=n.indexOf(s)).concat(n.slice(o+1));r.remove(t)}i&&n.push(r.set(t,{on:i}));return e};return t}function A(){ia.event.preventDefault()}function T(){for(var e,t=ia.event;e=t.sourceEvent;)t=e;return t}function L(e){for(var t=new N,n=0,r=arguments.length;++n<r;)t[arguments[n]]=I(t);t.of=function(n,r){return function(i){try{var o=i.sourceEvent=ia.event;i.target=e;ia.event=i;t[i.type].apply(n,r)}finally{ia.event=o}}};return t}function S(e){Aa(e,ba);return e}function C(e){return"function"==typeof e?e:function(){return Ta(e,this)}}function b(e){return"function"==typeof e?e:function(){return La(e,this)}}function R(e,t){function n(){this.removeAttribute(e)}function r(){this.removeAttributeNS(e.space,e.local)}function i(){this.setAttribute(e,t)}function o(){this.setAttributeNS(e.space,e.local,t)}function s(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}function a(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}e=ia.ns.qualify(e);return null==t?e.local?r:n:"function"==typeof t?e.local?a:s:e.local?o:i}function w(e){return e.trim().replace(/\s+/g," ")}function O(e){return new RegExp("(?:^|\\s+)"+ia.requote(e)+"(?:\\s+|$)","g")}function _(e){return(e+"").trim().split(/^|\s+/)}function F(e,t){function n(){for(var n=-1;++n<i;)e[n](this,t)}function r(){for(var n=-1,r=t.apply(this,arguments);++n<i;)e[n](this,r)}e=_(e).map(P);var i=e.length;return"function"==typeof t?r:n}function P(e){var t=O(e);return function(n,r){if(i=n.classList)return r?i.add(e):i.remove(e);var i=n.getAttribute("class")||"";if(r){t.lastIndex=0;t.test(i)||n.setAttribute("class",w(i+" "+e))}else n.setAttribute("class",w(i.replace(t," ")))}}function M(e,t,n){function r(){this.style.removeProperty(e)}function i(){this.style.setProperty(e,t,n)}function o(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,n)}return null==t?r:"function"==typeof t?o:i}function k(e,t){function n(){delete this[e]}function r(){this[e]=t}function i(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}return null==t?n:"function"==typeof t?i:r}function D(e){return"function"==typeof e?e:(e=ia.ns.qualify(e)).local?function(){return this.ownerDocument.createElementNS(e.space,e.local)}:function(){return this.ownerDocument.createElementNS(this.namespaceURI,e)}}function G(){var e=this.parentNode;e&&e.removeChild(this)}function U(e){return{__data__:e}}function B(e){return function(){return Ca(this,e)}}function j(e){arguments.length||(e=t);return function(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}}function q(e,t){for(var n=0,r=e.length;r>n;n++)for(var i,o=e[n],s=0,a=o.length;a>s;s++)(i=o[s])&&t(i,s,n);return e}function V(e){Aa(e,wa);return e}function H(e){var t,n;return function(r,i,o){var s,a=e[o].update,l=a.length;o!=n&&(n=o,t=0);i>=t&&(t=i+1);for(;!(s=a[t])&&++t<l;);return s}}function z(e,t,n){function r(){var t=this[s];if(t){this.removeEventListener(e,t,t.$);delete this[s]}}function i(){var i=l(t,sa(arguments));r.call(this);this.addEventListener(e,this[s]=i,i.$=n);i._=t}function o(){var t,n=new RegExp("^__on([^.]+)"+ia.requote(e)+"$");for(var r in this)if(t=r.match(n)){var i=this[r];this.removeEventListener(t[1],i,i.$);delete this[r]}}var s="__on"+e,a=e.indexOf("."),l=W;a>0&&(e=e.slice(0,a));var u=_a.get(e);u&&(e=u,l=$);return a?t?i:r:t?y:o}function W(e,t){return function(n){var r=ia.event;ia.event=n;t[0]=this.__data__;try{e.apply(this,t)}finally{ia.event=r}}}function $(e,t){var n=W(e,t);return function(e){var t=this,r=e.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||n.call(t,e)}}function Y(){var e=".dragsuppress-"+ ++Pa,t="click"+e,n=ia.select(ua).on("touchmove"+e,A).on("dragstart"+e,A).on("selectstart"+e,A);if(Fa){var r=la.style,i=r[Fa];r[Fa]="none"}return function(o){n.on(e,null);Fa&&(r[Fa]=i);if(o){var s=function(){n.on(t,null)};n.on(t,function(){A();s()},!0);setTimeout(s,0)}}}function K(e,t){t.changedTouches&&(t=t.changedTouches[0]);var n=e.ownerSVGElement||e;if(n.createSVGPoint){var r=n.createSVGPoint();if(0>Ma&&(ua.scrollX||ua.scrollY)){n=ia.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var i=n[0][0].getScreenCTM();Ma=!(i.f||i.e);n.remove()}Ma?(r.x=t.pageX,r.y=t.pageY):(r.x=t.clientX,r.y=t.clientY);r=r.matrixTransform(e.getScreenCTM().inverse());return[r.x,r.y]}var o=e.getBoundingClientRect();return[t.clientX-o.left-e.clientLeft,t.clientY-o.top-e.clientTop]}function Q(){return ia.event.changedTouches[0].identifier}function X(){return ia.event.target}function Z(){return ua}function J(e){return e>0?1:0>e?-1:0}function et(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function tt(e){return e>1?0:-1>e?Ga:Math.acos(e)}function nt(e){return e>1?ja:-1>e?-ja:Math.asin(e)}function rt(e){return((e=Math.exp(e))-1/e)/2}function it(e){return((e=Math.exp(e))+1/e)/2}function ot(e){return((e=Math.exp(2*e))-1)/(e+1)}function st(e){return(e=Math.sin(e/2))*e}function at(){}function lt(e,t,n){return this instanceof lt?void(this.h=+e,this.s=+t,this.l=+n):arguments.length<2?e instanceof lt?new lt(e.h,e.s,e.l):It(""+e,At,lt):new lt(e,t,n)}function ut(e,t,n){function r(e){e>360?e-=360:0>e&&(e+=360);return 60>e?o+(s-o)*e/60:180>e?s:240>e?o+(s-o)*(240-e)/60:o}function i(e){return Math.round(255*r(e))}var o,s;e=isNaN(e)?0:(e%=360)<0?e+360:e;t=isNaN(t)?0:0>t?0:t>1?1:t;n=0>n?0:n>1?1:n;s=.5>=n?n*(1+t):n+t-n*t;o=2*n-s;return new vt(i(e+120),i(e),i(e-120))}function pt(e,t,n){return this instanceof pt?void(this.h=+e,this.c=+t,this.l=+n):arguments.length<2?e instanceof pt?new pt(e.h,e.c,e.l):e instanceof dt?ht(e.l,e.a,e.b):ht((e=Tt((e=ia.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new pt(e,t,n)}function ct(e,t,n){isNaN(e)&&(e=0);isNaN(t)&&(t=0);return new dt(n,Math.cos(e*=qa)*t,Math.sin(e)*t)}function dt(e,t,n){return this instanceof dt?void(this.l=+e,this.a=+t,this.b=+n):arguments.length<2?e instanceof dt?new dt(e.l,e.a,e.b):e instanceof pt?ct(e.h,e.c,e.l):Tt((e=vt(e)).r,e.g,e.b):new dt(e,t,n)}function ft(e,t,n){var r=(e+16)/116,i=r+t/500,o=r-n/200;i=gt(i)*Ja;r=gt(r)*el;o=gt(o)*tl;return new vt(Et(3.2404542*i-1.5371385*r-.4985314*o),Et(-.969266*i+1.8760108*r+.041556*o),Et(.0556434*i-.2040259*r+1.0572252*o))}function ht(e,t,n){return e>0?new pt(Math.atan2(n,t)*Va,Math.sqrt(t*t+n*n),e):new pt(0/0,0/0,e)}function gt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function mt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function Et(e){return Math.round(255*(.00304>=e?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function vt(e,t,n){return this instanceof vt?void(this.r=~~e,this.g=~~t,this.b=~~n):arguments.length<2?e instanceof vt?new vt(e.r,e.g,e.b):It(""+e,vt,ut):new vt(e,t,n)}function xt(e){return new vt(e>>16,e>>8&255,255&e)}function yt(e){return xt(e)+""}function Nt(e){return 16>e?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function It(e,t,n){var r,i,o,s=0,a=0,l=0;r=/([a-z]+)\((.*)\)/i.exec(e);if(r){i=r[2].split(",");switch(r[1]){case"hsl":return n(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return t(St(i[0]),St(i[1]),St(i[2]))}}if(o=il.get(e))return t(o.r,o.g,o.b);if(null!=e&&"#"===e.charAt(0)&&!isNaN(o=parseInt(e.slice(1),16)))if(4===e.length){s=(3840&o)>>4;s=s>>4|s;a=240&o;a=a>>4|a;l=15&o;l=l<<4|l}else if(7===e.length){s=(16711680&o)>>16;a=(65280&o)>>8;l=255&o}return t(s,a,l)}function At(e,t,n){var r,i,o=Math.min(e/=255,t/=255,n/=255),s=Math.max(e,t,n),a=s-o,l=(s+o)/2;if(a){i=.5>l?a/(s+o):a/(2-s-o);r=e==s?(t-n)/a+(n>t?6:0):t==s?(n-e)/a+2:(e-t)/a+4;r*=60}else{r=0/0;i=l>0&&1>l?0:r}return new lt(r,i,l)}function Tt(e,t,n){e=Lt(e);t=Lt(t);n=Lt(n);var r=mt((.4124564*e+.3575761*t+.1804375*n)/Ja),i=mt((.2126729*e+.7151522*t+.072175*n)/el),o=mt((.0193339*e+.119192*t+.9503041*n)/tl);return dt(116*i-16,500*(r-i),200*(i-o))}function Lt(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function St(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}function Ct(e){return"function"==typeof e?e:function(){return e}}function bt(e){return e}function Rt(e){return function(t,n,r){2===arguments.length&&"function"==typeof n&&(r=n,n=null);return wt(t,n,e,r)}}function wt(e,t,n,r){function i(){var e,t=l.status;if(!t&&_t(l)||t>=200&&300>t||304===t){try{e=n.call(o,l)}catch(r){s.error.call(o,r);return}s.load.call(o,e)}else s.error.call(o,l)}var o={},s=ia.dispatch("beforesend","progress","load","error"),a={},l=new XMLHttpRequest,u=null;!ua.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(e)||(l=new XDomainRequest);"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()};l.onprogress=function(e){var t=ia.event;ia.event=e;try{s.progress.call(o,l)}finally{ia.event=t}};o.header=function(e,t){e=(e+"").toLowerCase();if(arguments.length<2)return a[e];null==t?delete a[e]:a[e]=t+"";return o};o.mimeType=function(e){if(!arguments.length)return t;t=null==e?null:e+"";return o};o.responseType=function(e){if(!arguments.length)return u;u=e;return o};o.response=function(e){n=e;return o};["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(sa(arguments)))}});o.send=function(n,r,i){2===arguments.length&&"function"==typeof r&&(i=r,r=null);l.open(n,e,!0);null==t||"accept"in a||(a.accept=t+",*/*");if(l.setRequestHeader)for(var p in a)l.setRequestHeader(p,a[p]);null!=t&&l.overrideMimeType&&l.overrideMimeType(t);null!=u&&(l.responseType=u);null!=i&&o.on("error",i).on("load",function(e){i(null,e)});s.beforesend.call(o,l);l.send(null==r?null:r);return o};o.abort=function(){l.abort();return o};ia.rebind(o,s,"on");return null==r?o:o.get(Ot(r))}function Ot(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}function _t(e){var t=e.responseType;return t&&"text"!==t?e.response:e.responseText}function Ft(){var e=Pt(),t=Mt()-e;if(t>24){if(isFinite(t)){clearTimeout(ll);ll=setTimeout(Ft,t)}al=0}else{al=1;pl(Ft)}}function Pt(){var e=Date.now();ul=ol;for(;ul;){e>=ul.t&&(ul.f=ul.c(e-ul.t));ul=ul.n}return e}function Mt(){for(var e,t=ol,n=1/0;t;)if(t.f)t=e?e.n=t.n:ol=t.n;else{t.t<n&&(n=t.t);t=(e=t).n}sl=e;return n}function kt(e,t){return t-(e?Math.ceil(Math.log(e)/Math.LN10):1)}function Dt(e,t){var n=Math.pow(10,3*va(8-t));return{scale:t>8?function(e){return e/n}:function(e){return e*n},symbol:e}}function Gt(e){var t=e.decimal,n=e.thousands,r=e.grouping,i=e.currency,o=r&&n?function(e,t){for(var i=e.length,o=[],s=0,a=r[0],l=0;i>0&&a>0;){l+a+1>t&&(a=Math.max(1,t-l));o.push(e.substring(i-=a,i+a));if((l+=a+1)>t)break;a=r[s=(s+1)%r.length]}return o.reverse().join(n)}:bt;return function(e){var n=dl.exec(e),r=n[1]||" ",s=n[2]||">",a=n[3]||"-",l=n[4]||"",u=n[5],p=+n[6],c=n[7],d=n[8],f=n[9],h=1,g="",m="",E=!1,v=!0;d&&(d=+d.substring(1));if(u||"0"===r&&"="===s){u=r="0";s="="}switch(f){case"n":c=!0;f="g";break;case"%":h=100;m="%";f="f";break;case"p":h=100;m="%";f="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+f.toLowerCase());case"c":v=!1;case"d":E=!0;d=0;break;case"s":h=-1;f="r"}"$"===l&&(g=i[0],m=i[1]);"r"!=f||d||(f="g");null!=d&&("g"==f?d=Math.max(1,Math.min(21,d)):("e"==f||"f"==f)&&(d=Math.max(0,Math.min(20,d))));f=fl.get(f)||Ut;var x=u&&c;return function(e){var n=m;if(E&&e%1)return"";var i=0>e||0===e&&0>1/e?(e=-e,"-"):"-"===a?"":a;if(0>h){var l=ia.formatPrefix(e,d);e=l.scale(e);n=l.symbol+m}else e*=h;e=f(e,d);var y,N,I=e.lastIndexOf(".");if(0>I){var A=v?e.lastIndexOf("e"):-1;0>A?(y=e,N=""):(y=e.substring(0,A),N=e.substring(A))}else{y=e.substring(0,I);N=t+e.substring(I+1)}!u&&c&&(y=o(y,1/0));var T=g.length+y.length+N.length+(x?0:i.length),L=p>T?new Array(T=p-T+1).join(r):"";x&&(y=o(L+y,L.length?p-N.length:1/0));i+=g;e=y+N;return("<"===s?i+e+L:">"===s?L+i+e:"^"===s?L.substring(0,T>>=1)+i+e+L.substring(T):i+(x?e:L+e))+n}}}function Ut(e){return e+""}function Bt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function jt(e,t,n){function r(t){var n=e(t),r=o(n,1);return r-t>t-n?n:r}function i(n){t(n=e(new gl(n-1)),1);return n}function o(e,n){t(e=new gl(+e),n);return e}function s(e,r,o){var s=i(e),a=[];if(o>1)for(;r>s;){n(s)%o||a.push(new Date(+s));t(s,1)}else for(;r>s;)a.push(new Date(+s)),t(s,1);return a}function a(e,t,n){try{gl=Bt;var r=new Bt;r._=e;return s(r,t,n)}finally{gl=Date}}e.floor=e;e.round=r;e.ceil=i;e.offset=o;e.range=s;var l=e.utc=qt(e);l.floor=l;l.round=qt(r);l.ceil=qt(i);l.offset=qt(o);l.range=a;return e}function qt(e){return function(t,n){try{gl=Bt;var r=new Bt;r._=t;return e(r,n)._}finally{gl=Date}}}function Vt(e){function t(e){function t(t){for(var n,i,o,s=[],a=-1,l=0;++a<r;)if(37===e.charCodeAt(a)){s.push(e.slice(l,a));null!=(i=El[n=e.charAt(++a)])&&(n=e.charAt(++a));(o=b[n])&&(n=o(t,null==i?"e"===n?" ":"0":i));s.push(n);l=a+1}s.push(e.slice(l,a));return s.join("")}var r=e.length;t.parse=function(t){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},i=n(r,e,t,0);if(i!=t.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var o=null!=r.Z&&gl!==Bt,s=new(o?Bt:gl);if("j"in r)s.setFullYear(r.y,0,r.j);else if("w"in r&&("W"in r||"U"in r)){s.setFullYear(r.y,0,1);s.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(s.getDay()+5)%7:r.w+7*r.U-(s.getDay()+6)%7)}else s.setFullYear(r.y,r.m,r.d);s.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L);return o?s._:s};t.toString=function(){return e};return t}function n(e,t,n,r){for(var i,o,s,a=0,l=t.length,u=n.length;l>a;){if(r>=u)return-1;i=t.charCodeAt(a++);if(37===i){s=t.charAt(a++);o=R[s in El?t.charAt(a++):s];if(!o||(r=o(e,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}function r(e,t,n){I.lastIndex=0;var r=I.exec(t.slice(n));return r?(e.w=A.get(r[0].toLowerCase()),n+r[0].length):-1}function i(e,t,n){y.lastIndex=0;var r=y.exec(t.slice(n));return r?(e.w=N.get(r[0].toLowerCase()),n+r[0].length):-1}function o(e,t,n){S.lastIndex=0;var r=S.exec(t.slice(n));return r?(e.m=C.get(r[0].toLowerCase()),n+r[0].length):-1}function s(e,t,n){T.lastIndex=0;var r=T.exec(t.slice(n));return r?(e.m=L.get(r[0].toLowerCase()),n+r[0].length):-1}function a(e,t,r){return n(e,b.c.toString(),t,r)}function l(e,t,r){return n(e,b.x.toString(),t,r)}function u(e,t,r){return n(e,b.X.toString(),t,r)}function p(e,t,n){var r=x.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)}var c=e.dateTime,d=e.date,f=e.time,h=e.periods,g=e.days,m=e.shortDays,E=e.months,v=e.shortMonths;t.utc=function(e){function n(e){try{gl=Bt;var t=new gl;t._=e;return r(t)}finally{gl=Date}}var r=t(e);n.parse=function(e){try{gl=Bt;var t=r.parse(e);return t&&t._}finally{gl=Date}};n.toString=r.toString;return n};t.multi=t.utc.multi=pn;var x=ia.map(),y=zt(g),N=Wt(g),I=zt(m),A=Wt(m),T=zt(E),L=Wt(E),S=zt(v),C=Wt(v);h.forEach(function(e,t){x.set(e.toLowerCase(),t)});var b={a:function(e){return m[e.getDay()]},A:function(e){return g[e.getDay()]},b:function(e){return v[e.getMonth()]},B:function(e){return E[e.getMonth()]},c:t(c),d:function(e,t){return Ht(e.getDate(),t,2)},e:function(e,t){return Ht(e.getDate(),t,2)},H:function(e,t){return Ht(e.getHours(),t,2)},I:function(e,t){return Ht(e.getHours()%12||12,t,2)},j:function(e,t){return Ht(1+hl.dayOfYear(e),t,3)},L:function(e,t){return Ht(e.getMilliseconds(),t,3)},m:function(e,t){return Ht(e.getMonth()+1,t,2)},M:function(e,t){return Ht(e.getMinutes(),t,2)},p:function(e){return h[+(e.getHours()>=12)]},S:function(e,t){return Ht(e.getSeconds(),t,2)},U:function(e,t){return Ht(hl.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return Ht(hl.mondayOfYear(e),t,2)},x:t(d),X:t(f),y:function(e,t){return Ht(e.getFullYear()%100,t,2)},Y:function(e,t){return Ht(e.getFullYear()%1e4,t,4)},Z:ln,"%":function(){return"%"}},R={a:r,A:i,b:o,B:s,c:a,d:tn,e:tn,H:rn,I:rn,j:nn,L:an,m:en,M:on,p:p,S:sn,U:Yt,w:$t,W:Kt,x:l,X:u,y:Xt,Y:Qt,Z:Zt,"%":un};return t}function Ht(e,t,n){var r=0>e?"-":"",i=(r?-e:e)+"",o=i.length;return r+(n>o?new Array(n-o+1).join(t)+i:i)}function zt(e){return new RegExp("^(?:"+e.map(ia.requote).join("|")+")","i")}function Wt(e){for(var t=new u,n=-1,r=e.length;++n<r;)t.set(e[n].toLowerCase(),n);return t}function $t(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function Yt(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n));return r?(e.U=+r[0],n+r[0].length):-1}function Kt(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n));return r?(e.W=+r[0],n+r[0].length):-1}function Qt(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function Xt(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+2));return r?(e.y=Jt(+r[0]),n+r[0].length):-1}function Zt(e,t,n){return/^[+-]\d{4}$/.test(t=t.slice(n,n+5))?(e.Z=-t,n+5):-1}function Jt(e){return e+(e>68?1900:2e3)}function en(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function tn(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function nn(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function rn(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function on(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function sn(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function an(e,t,n){vl.lastIndex=0;var r=vl.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function ln(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=va(t)/60|0,i=va(t)%60;return n+Ht(r,"0",2)+Ht(i,"0",2)}function un(e,t,n){xl.lastIndex=0;var r=xl.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function pn(e){for(var t=e.length,n=-1;++n<t;)e[n][0]=this(e[n][0]);return function(t){for(var n=0,r=e[n];!r[1](t);)r=e[++n];return r[0](t)}}function cn(){}function dn(e,t,n){var r=n.s=e+t,i=r-e,o=r-i;n.t=e-o+(t-i)}function fn(e,t){e&&Al.hasOwnProperty(e.type)&&Al[e.type](e,t)}function hn(e,t,n){var r,i=-1,o=e.length-n;t.lineStart();for(;++i<o;)r=e[i],t.point(r[0],r[1],r[2]);t.lineEnd()}function gn(e,t){var n=-1,r=e.length;t.polygonStart();for(;++n<r;)hn(e[n],t,1);t.polygonEnd()}function mn(){function e(e,t){e*=qa;t=t*qa/2+Ga/4;var n=e-r,s=n>=0?1:-1,a=s*n,l=Math.cos(t),u=Math.sin(t),p=o*u,c=i*l+p*Math.cos(a),d=p*s*Math.sin(a);Ll.add(Math.atan2(d,c));r=e,i=l,o=u}var t,n,r,i,o;Sl.point=function(s,a){Sl.point=e;r=(t=s)*qa,i=Math.cos(a=(n=a)*qa/2+Ga/4),o=Math.sin(a)};Sl.lineEnd=function(){e(t,n)}}function En(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function vn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function xn(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function yn(e,t){e[0]+=t[0];e[1]+=t[1];e[2]+=t[2]}function Nn(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function In(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t;e[1]/=t;e[2]/=t}function An(e){return[Math.atan2(e[1],e[0]),nt(e[2])]}function Tn(e,t){return va(e[0]-t[0])<ka&&va(e[1]-t[1])<ka}function Ln(e,t){e*=qa;var n=Math.cos(t*=qa);Sn(n*Math.cos(e),n*Math.sin(e),Math.sin(t))}function Sn(e,t,n){++Cl;Rl+=(e-Rl)/Cl;wl+=(t-wl)/Cl;Ol+=(n-Ol)/Cl}function Cn(){function e(e,i){e*=qa;var o=Math.cos(i*=qa),s=o*Math.cos(e),a=o*Math.sin(e),l=Math.sin(i),u=Math.atan2(Math.sqrt((u=n*l-r*a)*u+(u=r*s-t*l)*u+(u=t*a-n*s)*u),t*s+n*a+r*l);bl+=u;_l+=u*(t+(t=s));Fl+=u*(n+(n=a));Pl+=u*(r+(r=l));Sn(t,n,r)}var t,n,r;Gl.point=function(i,o){i*=qa;var s=Math.cos(o*=qa);t=s*Math.cos(i);n=s*Math.sin(i);r=Math.sin(o);Gl.point=e;Sn(t,n,r)}}function bn(){Gl.point=Ln}function Rn(){function e(e,t){e*=qa;var n=Math.cos(t*=qa),s=n*Math.cos(e),a=n*Math.sin(e),l=Math.sin(t),u=i*l-o*a,p=o*s-r*l,c=r*a-i*s,d=Math.sqrt(u*u+p*p+c*c),f=r*s+i*a+o*l,h=d&&-tt(f)/d,g=Math.atan2(d,f);Ml+=h*u;kl+=h*p;Dl+=h*c;bl+=g;_l+=g*(r+(r=s));Fl+=g*(i+(i=a));Pl+=g*(o+(o=l));Sn(r,i,o)}var t,n,r,i,o;Gl.point=function(s,a){t=s,n=a;Gl.point=e;s*=qa;var l=Math.cos(a*=qa);r=l*Math.cos(s);i=l*Math.sin(s);o=Math.sin(a);Sn(r,i,o)};Gl.lineEnd=function(){e(t,n);Gl.lineEnd=bn;Gl.point=Ln}}function wn(e,t){function n(n,r){return n=e(n,r),t(n[0],n[1])}e.invert&&t.invert&&(n.invert=function(n,r){return n=t.invert(n,r),n&&e.invert(n[0],n[1])});return n}function On(){return!0}function _n(e,t,n,r,i){var o=[],s=[];e.forEach(function(e){if(!((t=e.length-1)<=0)){var t,n=e[0],r=e[t];if(Tn(n,r)){i.lineStart();for(var a=0;t>a;++a)i.point((n=e[a])[0],n[1]);i.lineEnd()}else{var l=new Pn(n,e,null,!0),u=new Pn(n,null,l,!1);l.o=u;o.push(l);s.push(u);l=new Pn(r,e,null,!1);u=new Pn(r,null,l,!0);l.o=u;o.push(l);s.push(u)}}});s.sort(t);Fn(o);Fn(s);if(o.length){for(var a=0,l=n,u=s.length;u>a;++a)s[a].e=l=!l;for(var p,c,d=o[0];;){for(var f=d,h=!0;f.v;)if((f=f.n)===d)return;p=f.z;i.lineStart();do{f.v=f.o.v=!0;if(f.e){if(h)for(var a=0,u=p.length;u>a;++a)i.point((c=p[a])[0],c[1]);else r(f.x,f.n.x,1,i);f=f.n}else{if(h){p=f.p.z;for(var a=p.length-1;a>=0;--a)i.point((c=p[a])[0],c[1])}else r(f.x,f.p.x,-1,i);f=f.p}f=f.o;p=f.z;h=!h}while(!f.v);i.lineEnd()}}}function Fn(e){if(t=e.length){for(var t,n,r=0,i=e[0];++r<t;){i.n=n=e[r];n.p=i;i=n}i.n=n=e[0];n.p=i}}function Pn(e,t,n,r){this.x=e;this.z=t;this.o=n;this.e=r;this.v=!1;this.n=this.p=null}function Mn(e,t,n,r){return function(i,o){function s(t,n){var r=i(t,n);e(t=r[0],n=r[1])&&o.point(t,n)}function a(e,t){var n=i(e,t);m.point(n[0],n[1])}function l(){v.point=a;m.lineStart()}function u(){v.point=s;m.lineEnd()}function p(e,t){g.push([e,t]);var n=i(e,t);y.point(n[0],n[1])}function c(){y.lineStart();g=[]}function d(){p(g[0][0],g[0][1]);y.lineEnd();var e,t=y.clean(),n=x.buffer(),r=n.length;g.pop();h.push(g);g=null;if(r)if(1&t){e=n[0];var i,r=e.length-1,s=-1;if(r>0){N||(o.polygonStart(),N=!0);o.lineStart();for(;++s<r;)o.point((i=e[s])[0],i[1]);o.lineEnd()}}else{r>1&&2&t&&n.push(n.pop().concat(n.shift()));f.push(n.filter(kn))}}var f,h,g,m=t(o),E=i.invert(r[0],r[1]),v={point:s,lineStart:l,lineEnd:u,polygonStart:function(){v.point=p;v.lineStart=c;v.lineEnd=d;f=[];h=[]},polygonEnd:function(){v.point=s;v.lineStart=l;v.lineEnd=u;f=ia.merge(f);var e=qn(E,h);if(f.length){N||(o.polygonStart(),N=!0);_n(f,Gn,e,n,o)}else if(e){N||(o.polygonStart(),N=!0);o.lineStart();n(null,null,1,o);o.lineEnd()}N&&(o.polygonEnd(),N=!1);f=h=null},sphere:function(){o.polygonStart();o.lineStart();n(null,null,1,o);o.lineEnd();o.polygonEnd()}},x=Dn(),y=t(x),N=!1;return v}}function kn(e){return e.length>1}function Dn(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:y,buffer:function(){var n=t;t=[];e=null;return n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Gn(e,t){return((e=e.x)[0]<0?e[1]-ja-ka:ja-e[1])-((t=t.x)[0]<0?t[1]-ja-ka:ja-t[1])}function Un(e){var t,n=0/0,r=0/0,i=0/0;return{lineStart:function(){e.lineStart();t=1},point:function(o,s){var a=o>0?Ga:-Ga,l=va(o-n);if(va(l-Ga)<ka){e.point(n,r=(r+s)/2>0?ja:-ja);e.point(i,r);e.lineEnd();e.lineStart();e.point(a,r);e.point(o,r);t=0}else if(i!==a&&l>=Ga){va(n-i)<ka&&(n-=i*ka);va(o-a)<ka&&(o-=a*ka);r=Bn(n,r,o,s);e.point(i,r);e.lineEnd();e.lineStart();e.point(a,r);t=0}e.point(n=o,r=s);i=a},lineEnd:function(){e.lineEnd();n=r=0/0},clean:function(){return 2-t}}}function Bn(e,t,n,r){var i,o,s=Math.sin(e-n);return va(s)>ka?Math.atan((Math.sin(t)*(o=Math.cos(r))*Math.sin(n)-Math.sin(r)*(i=Math.cos(t))*Math.sin(e))/(i*o*s)):(t+r)/2}function jn(e,t,n,r){var i;if(null==e){i=n*ja;r.point(-Ga,i);r.point(0,i);r.point(Ga,i);r.point(Ga,0);r.point(Ga,-i);r.point(0,-i);r.point(-Ga,-i);r.point(-Ga,0);r.point(-Ga,i)}else if(va(e[0]-t[0])>ka){var o=e[0]<t[0]?Ga:-Ga;i=n*o/2;r.point(-o,i);r.point(0,i);r.point(o,i)}else r.point(t[0],t[1])}function qn(e,t){var n=e[0],r=e[1],i=[Math.sin(n),-Math.cos(n),0],o=0,s=0;Ll.reset();for(var a=0,l=t.length;l>a;++a){var u=t[a],p=u.length;if(p)for(var c=u[0],d=c[0],f=c[1]/2+Ga/4,h=Math.sin(f),g=Math.cos(f),m=1;;){m===p&&(m=0);e=u[m];var E=e[0],v=e[1]/2+Ga/4,x=Math.sin(v),y=Math.cos(v),N=E-d,I=N>=0?1:-1,A=I*N,T=A>Ga,L=h*x;Ll.add(Math.atan2(L*I*Math.sin(A),g*y+L*Math.cos(A)));o+=T?N+I*Ua:N;if(T^d>=n^E>=n){var S=xn(En(c),En(e));In(S);var C=xn(i,S);In(C);var b=(T^N>=0?-1:1)*nt(C[2]);(r>b||r===b&&(S[0]||S[1]))&&(s+=T^N>=0?1:-1)}if(!m++)break;d=E,h=x,g=y,c=e}}return(-ka>o||ka>o&&0>Ll)^1&s}function Vn(e){function t(e,t){return Math.cos(e)*Math.cos(t)>o}function n(e){var n,o,l,u,p;return{lineStart:function(){u=l=!1;p=1},point:function(c,d){var f,h=[c,d],g=t(c,d),m=s?g?0:i(c,d):g?i(c+(0>c?Ga:-Ga),d):0;!n&&(u=l=g)&&e.lineStart();if(g!==l){f=r(n,h);if(Tn(n,f)||Tn(h,f)){h[0]+=ka;h[1]+=ka;g=t(h[0],h[1])}}if(g!==l){p=0;if(g){e.lineStart();f=r(h,n);e.point(f[0],f[1])}else{f=r(n,h);e.point(f[0],f[1]);e.lineEnd()}n=f}else if(a&&n&&s^g){var E;if(!(m&o)&&(E=r(h,n,!0))){p=0;if(s){e.lineStart();e.point(E[0][0],E[0][1]);e.point(E[1][0],E[1][1]);e.lineEnd()}else{e.point(E[1][0],E[1][1]);e.lineEnd();e.lineStart();e.point(E[0][0],E[0][1])}}}!g||n&&Tn(n,h)||e.point(h[0],h[1]);n=h,l=g,o=m},lineEnd:function(){l&&e.lineEnd();n=null},clean:function(){return p|(u&&l)<<1}}}function r(e,t,n){var r=En(e),i=En(t),s=[1,0,0],a=xn(r,i),l=vn(a,a),u=a[0],p=l-u*u;if(!p)return!n&&e;var c=o*l/p,d=-o*u/p,f=xn(s,a),h=Nn(s,c),g=Nn(a,d);yn(h,g);var m=f,E=vn(h,m),v=vn(m,m),x=E*E-v*(vn(h,h)-1);if(!(0>x)){var y=Math.sqrt(x),N=Nn(m,(-E-y)/v);yn(N,h);N=An(N);if(!n)return N;var I,A=e[0],T=t[0],L=e[1],S=t[1];A>T&&(I=A,A=T,T=I);var C=T-A,b=va(C-Ga)<ka,R=b||ka>C;!b&&L>S&&(I=L,L=S,S=I);if(R?b?L+S>0^N[1]<(va(N[0]-A)<ka?L:S):L<=N[1]&&N[1]<=S:C>Ga^(A<=N[0]&&N[0]<=T)){var w=Nn(m,(-E+y)/v);yn(w,h);return[N,An(w)]}}}function i(t,n){var r=s?e:Ga-e,i=0;-r>t?i|=1:t>r&&(i|=2);-r>n?i|=4:n>r&&(i|=8);return i}var o=Math.cos(e),s=o>0,a=va(o)>ka,l=mr(e,6*qa);return Mn(t,n,l,s?[0,-e]:[-Ga,e-Ga])}function Hn(e,t,n,r){return function(i){var o,s=i.a,a=i.b,l=s.x,u=s.y,p=a.x,c=a.y,d=0,f=1,h=p-l,g=c-u;o=e-l;if(h||!(o>0)){o/=h;if(0>h){if(d>o)return;f>o&&(f=o)}else if(h>0){if(o>f)return;o>d&&(d=o)}o=n-l;if(h||!(0>o)){o/=h;if(0>h){if(o>f)return;o>d&&(d=o)}else if(h>0){if(d>o)return;f>o&&(f=o)}o=t-u;if(g||!(o>0)){o/=g;if(0>g){if(d>o)return;f>o&&(f=o)}else if(g>0){if(o>f)return;o>d&&(d=o)}o=r-u;if(g||!(0>o)){o/=g;if(0>g){if(o>f)return;o>d&&(d=o)}else if(g>0){if(d>o)return;f>o&&(f=o)}d>0&&(i.a={x:l+d*h,y:u+d*g});1>f&&(i.b={x:l+f*h,y:u+f*g});return i}}}}}}function zn(e,t,n,r){function i(r,i){return va(r[0]-e)<ka?i>0?0:3:va(r[0]-n)<ka?i>0?2:1:va(r[1]-t)<ka?i>0?1:0:i>0?3:2}function o(e,t){return s(e.x,t.x)}function s(e,t){var n=i(e,1),r=i(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}return function(a){function l(e){for(var t=0,n=m.length,r=e[1],i=0;n>i;++i)for(var o,s=1,a=m[i],l=a.length,u=a[0];l>s;++s){o=a[s];u[1]<=r?o[1]>r&&et(u,o,e)>0&&++t:o[1]<=r&&et(u,o,e)<0&&--t;u=o}return 0!==t}function u(o,a,l,u){var p=0,c=0;if(null==o||(p=i(o,l))!==(c=i(a,l))||s(o,a)<0^l>0){do u.point(0===p||3===p?e:n,p>1?r:t);while((p=(p+l+4)%4)!==c)}else u.point(a[0],a[1])}function p(i,o){return i>=e&&n>=i&&o>=t&&r>=o}function c(e,t){p(e,t)&&a.point(e,t)}function d(){R.point=h;
m&&m.push(E=[]);T=!0;A=!1;N=I=0/0}function f(){if(g){h(v,x);y&&A&&C.rejoin();g.push(C.buffer())}R.point=c;A&&a.lineEnd()}function h(e,t){e=Math.max(-Bl,Math.min(Bl,e));t=Math.max(-Bl,Math.min(Bl,t));var n=p(e,t);m&&E.push([e,t]);if(T){v=e,x=t,y=n;T=!1;if(n){a.lineStart();a.point(e,t)}}else if(n&&A)a.point(e,t);else{var r={a:{x:N,y:I},b:{x:e,y:t}};if(b(r)){if(!A){a.lineStart();a.point(r.a.x,r.a.y)}a.point(r.b.x,r.b.y);n||a.lineEnd();L=!1}else if(n){a.lineStart();a.point(e,t);L=!1}}N=e,I=t,A=n}var g,m,E,v,x,y,N,I,A,T,L,S=a,C=Dn(),b=Hn(e,t,n,r),R={point:c,lineStart:d,lineEnd:f,polygonStart:function(){a=C;g=[];m=[];L=!0},polygonEnd:function(){a=S;g=ia.merge(g);var t=l([e,r]),n=L&&t,i=g.length;if(n||i){a.polygonStart();if(n){a.lineStart();u(null,null,1,a);a.lineEnd()}i&&_n(g,o,t,u,a);a.polygonEnd()}g=m=E=null}};return R}}function Wn(e){var t=0,n=Ga/3,r=lr(e),i=r(t,n);i.parallels=function(e){return arguments.length?r(t=e[0]*Ga/180,n=e[1]*Ga/180):[t/Ga*180,n/Ga*180]};return i}function $n(e,t){function n(e,t){var n=Math.sqrt(o-2*i*Math.sin(t))/i;return[n*Math.sin(e*=i),s-n*Math.cos(e)]}var r=Math.sin(e),i=(r+Math.sin(t))/2,o=1+r*(2*i-r),s=Math.sqrt(o)/i;n.invert=function(e,t){var n=s-t;return[Math.atan2(e,n)/i,nt((o-(e*e+n*n)*i*i)/(2*i))]};return n}function Yn(){function e(e,t){ql+=i*e-r*t;r=e,i=t}var t,n,r,i;$l.point=function(o,s){$l.point=e;t=r=o,n=i=s};$l.lineEnd=function(){e(t,n)}}function Kn(e,t){Vl>e&&(Vl=e);e>zl&&(zl=e);Hl>t&&(Hl=t);t>Wl&&(Wl=t)}function Qn(){function e(e,t){s.push("M",e,",",t,o)}function t(e,t){s.push("M",e,",",t);a.point=n}function n(e,t){s.push("L",e,",",t)}function r(){a.point=e}function i(){s.push("Z")}var o=Xn(4.5),s=[],a={point:e,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=r;a.point=e},pointRadius:function(e){o=Xn(e);return a},result:function(){if(s.length){var e=s.join("");s=[];return e}}};return a}function Xn(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}function Zn(e,t){Rl+=e;wl+=t;++Ol}function Jn(){function e(e,r){var i=e-t,o=r-n,s=Math.sqrt(i*i+o*o);_l+=s*(t+e)/2;Fl+=s*(n+r)/2;Pl+=s;Zn(t=e,n=r)}var t,n;Kl.point=function(r,i){Kl.point=e;Zn(t=r,n=i)}}function er(){Kl.point=Zn}function tr(){function e(e,t){var n=e-r,o=t-i,s=Math.sqrt(n*n+o*o);_l+=s*(r+e)/2;Fl+=s*(i+t)/2;Pl+=s;s=i*e-r*t;Ml+=s*(r+e);kl+=s*(i+t);Dl+=3*s;Zn(r=e,i=t)}var t,n,r,i;Kl.point=function(o,s){Kl.point=e;Zn(t=r=o,n=i=s)};Kl.lineEnd=function(){e(t,n)}}function nr(e){function t(t,n){e.moveTo(t+s,n);e.arc(t,n,s,0,Ua)}function n(t,n){e.moveTo(t,n);a.point=r}function r(t,n){e.lineTo(t,n)}function i(){a.point=t}function o(){e.closePath()}var s=4.5,a={point:t,lineStart:function(){a.point=n},lineEnd:i,polygonStart:function(){a.lineEnd=o},polygonEnd:function(){a.lineEnd=i;a.point=t},pointRadius:function(e){s=e;return a},result:y};return a}function rr(e){function t(e){return(a?r:n)(e)}function n(t){return sr(t,function(n,r){n=e(n,r);t.point(n[0],n[1])})}function r(t){function n(n,r){n=e(n,r);t.point(n[0],n[1])}function r(){x=0/0;T.point=o;t.lineStart()}function o(n,r){var o=En([n,r]),s=e(n,r);i(x,y,v,N,I,A,x=s[0],y=s[1],v=n,N=o[0],I=o[1],A=o[2],a,t);t.point(x,y)}function s(){T.point=n;t.lineEnd()}function l(){r();T.point=u;T.lineEnd=p}function u(e,t){o(c=e,d=t),f=x,h=y,g=N,m=I,E=A;T.point=o}function p(){i(x,y,v,N,I,A,f,h,c,g,m,E,a,t);T.lineEnd=s;s()}var c,d,f,h,g,m,E,v,x,y,N,I,A,T={point:n,lineStart:r,lineEnd:s,polygonStart:function(){t.polygonStart();T.lineStart=l},polygonEnd:function(){t.polygonEnd();T.lineStart=r}};return T}function i(t,n,r,a,l,u,p,c,d,f,h,g,m,E){var v=p-t,x=c-n,y=v*v+x*x;if(y>4*o&&m--){var N=a+f,I=l+h,A=u+g,T=Math.sqrt(N*N+I*I+A*A),L=Math.asin(A/=T),S=va(va(A)-1)<ka||va(r-d)<ka?(r+d)/2:Math.atan2(I,N),C=e(S,L),b=C[0],R=C[1],w=b-t,O=R-n,_=x*w-v*O;if(_*_/y>o||va((v*w+x*O)/y-.5)>.3||s>a*f+l*h+u*g){i(t,n,r,a,l,u,b,R,S,N/=T,I/=T,A,m,E);E.point(b,R);i(b,R,S,N,I,A,p,c,d,f,h,g,m,E)}}}var o=.5,s=Math.cos(30*qa),a=16;t.precision=function(e){if(!arguments.length)return Math.sqrt(o);a=(o=e*e)>0&&16;return t};return t}function ir(e){var t=rr(function(t,n){return e([t*Va,n*Va])});return function(e){return ur(t(e))}}function or(e){this.stream=e}function sr(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function ar(e){return lr(function(){return e})()}function lr(e){function t(e){e=a(e[0]*qa,e[1]*qa);return[e[0]*d+l,u-e[1]*d]}function n(e){e=a.invert((e[0]-l)/d,(u-e[1])/d);return e&&[e[0]*Va,e[1]*Va]}function r(){a=wn(s=dr(E,v,x),o);var e=o(g,m);l=f-e[0]*d;u=h+e[1]*d;return i()}function i(){p&&(p.valid=!1,p=null);return t}var o,s,a,l,u,p,c=rr(function(e,t){e=o(e,t);return[e[0]*d+l,u-e[1]*d]}),d=150,f=480,h=250,g=0,m=0,E=0,v=0,x=0,y=Ul,N=bt,I=null,A=null;t.stream=function(e){p&&(p.valid=!1);p=ur(y(s,c(N(e))));p.valid=!0;return p};t.clipAngle=function(e){if(!arguments.length)return I;y=null==e?(I=e,Ul):Vn((I=+e)*qa);return i()};t.clipExtent=function(e){if(!arguments.length)return A;A=e;N=e?zn(e[0][0],e[0][1],e[1][0],e[1][1]):bt;return i()};t.scale=function(e){if(!arguments.length)return d;d=+e;return r()};t.translate=function(e){if(!arguments.length)return[f,h];f=+e[0];h=+e[1];return r()};t.center=function(e){if(!arguments.length)return[g*Va,m*Va];g=e[0]%360*qa;m=e[1]%360*qa;return r()};t.rotate=function(e){if(!arguments.length)return[E*Va,v*Va,x*Va];E=e[0]%360*qa;v=e[1]%360*qa;x=e.length>2?e[2]%360*qa:0;return r()};ia.rebind(t,c,"precision");return function(){o=e.apply(this,arguments);t.invert=o.invert&&n;return r()}}function ur(e){return sr(e,function(t,n){e.point(t*qa,n*qa)})}function pr(e,t){return[e,t]}function cr(e,t){return[e>Ga?e-Ua:-Ga>e?e+Ua:e,t]}function dr(e,t,n){return e?t||n?wn(hr(e),gr(t,n)):hr(e):t||n?gr(t,n):cr}function fr(e){return function(t,n){return t+=e,[t>Ga?t-Ua:-Ga>t?t+Ua:t,n]}}function hr(e){var t=fr(e);t.invert=fr(-e);return t}function gr(e,t){function n(e,t){var n=Math.cos(t),a=Math.cos(e)*n,l=Math.sin(e)*n,u=Math.sin(t),p=u*r+a*i;return[Math.atan2(l*o-p*s,a*r-u*i),nt(p*o+l*s)]}var r=Math.cos(e),i=Math.sin(e),o=Math.cos(t),s=Math.sin(t);n.invert=function(e,t){var n=Math.cos(t),a=Math.cos(e)*n,l=Math.sin(e)*n,u=Math.sin(t),p=u*o-l*s;return[Math.atan2(l*o+u*s,a*r+p*i),nt(p*r-a*i)]};return n}function mr(e,t){var n=Math.cos(e),r=Math.sin(e);return function(i,o,s,a){var l=s*t;if(null!=i){i=Er(n,i);o=Er(n,o);(s>0?o>i:i>o)&&(i+=s*Ua)}else{i=e+s*Ua;o=e-.5*l}for(var u,p=i;s>0?p>o:o>p;p-=l)a.point((u=An([n,-r*Math.cos(p),-r*Math.sin(p)]))[0],u[1])}}function Er(e,t){var n=En(t);n[0]-=e;In(n);var r=tt(-n[1]);return((-n[2]<0?-r:r)+2*Math.PI-ka)%(2*Math.PI)}function vr(e,t,n){var r=ia.range(e,t-ka,n).concat(t);return function(e){return r.map(function(t){return[e,t]})}}function xr(e,t,n){var r=ia.range(e,t-ka,n).concat(t);return function(e){return r.map(function(t){return[t,e]})}}function yr(e){return e.source}function Nr(e){return e.target}function Ir(e,t,n,r){var i=Math.cos(t),o=Math.sin(t),s=Math.cos(r),a=Math.sin(r),l=i*Math.cos(e),u=i*Math.sin(e),p=s*Math.cos(n),c=s*Math.sin(n),d=2*Math.asin(Math.sqrt(st(r-t)+i*s*st(n-e))),f=1/Math.sin(d),h=d?function(e){var t=Math.sin(e*=d)*f,n=Math.sin(d-e)*f,r=n*l+t*p,i=n*u+t*c,s=n*o+t*a;return[Math.atan2(i,r)*Va,Math.atan2(s,Math.sqrt(r*r+i*i))*Va]}:function(){return[e*Va,t*Va]};h.distance=d;return h}function Ar(){function e(e,i){var o=Math.sin(i*=qa),s=Math.cos(i),a=va((e*=qa)-t),l=Math.cos(a);Ql+=Math.atan2(Math.sqrt((a=s*Math.sin(a))*a+(a=r*o-n*s*l)*a),n*o+r*s*l);t=e,n=o,r=s}var t,n,r;Xl.point=function(i,o){t=i*qa,n=Math.sin(o*=qa),r=Math.cos(o);Xl.point=e};Xl.lineEnd=function(){Xl.point=Xl.lineEnd=y}}function Tr(e,t){function n(t,n){var r=Math.cos(t),i=Math.cos(n),o=e(r*i);return[o*i*Math.sin(t),o*Math.sin(n)]}n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),i=t(r),o=Math.sin(i),s=Math.cos(i);return[Math.atan2(e*o,r*s),Math.asin(r&&n*o/r)]};return n}function Lr(e,t){function n(e,t){s>0?-ja+ka>t&&(t=-ja+ka):t>ja-ka&&(t=ja-ka);var n=s/Math.pow(i(t),o);return[n*Math.sin(o*e),s-n*Math.cos(o*e)]}var r=Math.cos(e),i=function(e){return Math.tan(Ga/4+e/2)},o=e===t?Math.sin(e):Math.log(r/Math.cos(t))/Math.log(i(t)/i(e)),s=r*Math.pow(i(e),o)/o;if(!o)return Cr;n.invert=function(e,t){var n=s-t,r=J(o)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/o,2*Math.atan(Math.pow(s/r,1/o))-ja]};return n}function Sr(e,t){function n(e,t){var n=o-t;return[n*Math.sin(i*e),o-n*Math.cos(i*e)]}var r=Math.cos(e),i=e===t?Math.sin(e):(r-Math.cos(t))/(t-e),o=r/i+e;if(va(i)<ka)return pr;n.invert=function(e,t){var n=o-t;return[Math.atan2(e,n)/i,o-J(i)*Math.sqrt(e*e+n*n)]};return n}function Cr(e,t){return[e,Math.log(Math.tan(Ga/4+t/2))]}function br(e){var t,n=ar(e),r=n.scale,i=n.translate,o=n.clipExtent;n.scale=function(){var e=r.apply(n,arguments);return e===n?t?n.clipExtent(null):n:e};n.translate=function(){var e=i.apply(n,arguments);return e===n?t?n.clipExtent(null):n:e};n.clipExtent=function(e){var s=o.apply(n,arguments);if(s===n){if(t=null==e){var a=Ga*r(),l=i();o([[l[0]-a,l[1]-a],[l[0]+a,l[1]+a]])}}else t&&(s=null);return s};return n.clipExtent(null)}function Rr(e,t){return[Math.log(Math.tan(Ga/4+t/2)),-e]}function wr(e){return e[0]}function Or(e){return e[1]}function _r(e){for(var t=e.length,n=[0,1],r=2,i=2;t>i;i++){for(;r>1&&et(e[n[r-2]],e[n[r-1]],e[i])<=0;)--r;n[r++]=i}return n.slice(0,r)}function Fr(e,t){return e[0]-t[0]||e[1]-t[1]}function Pr(e,t,n){return(n[0]-t[0])*(e[1]-t[1])<(n[1]-t[1])*(e[0]-t[0])}function Mr(e,t,n,r){var i=e[0],o=n[0],s=t[0]-i,a=r[0]-o,l=e[1],u=n[1],p=t[1]-l,c=r[1]-u,d=(a*(l-u)-c*(i-o))/(c*s-a*p);return[i+d*s,l+d*p]}function kr(e){var t=e[0],n=e[e.length-1];return!(t[0]-n[0]||t[1]-n[1])}function Dr(){ii(this);this.edge=this.site=this.circle=null}function Gr(e){var t=uu.pop()||new Dr;t.site=e;return t}function Ur(e){Kr(e);su.remove(e);uu.push(e);ii(e)}function Br(e){var t=e.circle,n=t.x,r=t.cy,i={x:n,y:r},o=e.P,s=e.N,a=[e];Ur(e);for(var l=o;l.circle&&va(n-l.circle.x)<ka&&va(r-l.circle.cy)<ka;){o=l.P;a.unshift(l);Ur(l);l=o}a.unshift(l);Kr(l);for(var u=s;u.circle&&va(n-u.circle.x)<ka&&va(r-u.circle.cy)<ka;){s=u.N;a.push(u);Ur(u);u=s}a.push(u);Kr(u);var p,c=a.length;for(p=1;c>p;++p){u=a[p];l=a[p-1];ti(u.edge,l.site,u.site,i)}l=a[0];u=a[c-1];u.edge=Jr(l.site,u.site,null,i);Yr(l);Yr(u)}function jr(e){for(var t,n,r,i,o=e.x,s=e.y,a=su._;a;){r=qr(a,s)-o;if(r>ka)a=a.L;else{i=o-Vr(a,s);if(!(i>ka)){if(r>-ka){t=a.P;n=a}else if(i>-ka){t=a;n=a.N}else t=n=a;break}if(!a.R){t=a;break}a=a.R}}var l=Gr(e);su.insert(t,l);if(t||n)if(t!==n)if(n){Kr(t);Kr(n);var u=t.site,p=u.x,c=u.y,d=e.x-p,f=e.y-c,h=n.site,g=h.x-p,m=h.y-c,E=2*(d*m-f*g),v=d*d+f*f,x=g*g+m*m,y={x:(m*v-f*x)/E+p,y:(d*x-g*v)/E+c};ti(n.edge,u,h,y);l.edge=Jr(u,e,null,y);n.edge=Jr(e,h,null,y);Yr(t);Yr(n)}else l.edge=Jr(t.site,l.site);else{Kr(t);n=Gr(t.site);su.insert(l,n);l.edge=n.edge=Jr(t.site,l.site);Yr(t);Yr(n)}}function qr(e,t){var n=e.site,r=n.x,i=n.y,o=i-t;if(!o)return r;var s=e.P;if(!s)return-1/0;n=s.site;var a=n.x,l=n.y,u=l-t;if(!u)return a;var p=a-r,c=1/o-1/u,d=p/u;return c?(-d+Math.sqrt(d*d-2*c*(p*p/(-2*u)-l+u/2+i-o/2)))/c+r:(r+a)/2}function Vr(e,t){var n=e.N;if(n)return qr(n,t);var r=e.site;return r.y===t?r.x:1/0}function Hr(e){this.site=e;this.edges=[]}function zr(e){for(var t,n,r,i,o,s,a,l,u,p,c=e[0][0],d=e[1][0],f=e[0][1],h=e[1][1],g=ou,m=g.length;m--;){o=g[m];if(o&&o.prepare()){a=o.edges;l=a.length;s=0;for(;l>s;){p=a[s].end(),r=p.x,i=p.y;u=a[++s%l].start(),t=u.x,n=u.y;if(va(r-t)>ka||va(i-n)>ka){a.splice(s,0,new ni(ei(o.site,p,va(r-c)<ka&&h-i>ka?{x:c,y:va(t-c)<ka?n:h}:va(i-h)<ka&&d-r>ka?{x:va(n-h)<ka?t:d,y:h}:va(r-d)<ka&&i-f>ka?{x:d,y:va(t-d)<ka?n:f}:va(i-f)<ka&&r-c>ka?{x:va(n-f)<ka?t:c,y:f}:null),o.site,null));++l}}}}}function Wr(e,t){return t.angle-e.angle}function $r(){ii(this);this.x=this.y=this.arc=this.site=this.cy=null}function Yr(e){var t=e.P,n=e.N;if(t&&n){var r=t.site,i=e.site,o=n.site;if(r!==o){var s=i.x,a=i.y,l=r.x-s,u=r.y-a,p=o.x-s,c=o.y-a,d=2*(l*c-u*p);if(!(d>=-Da)){var f=l*l+u*u,h=p*p+c*c,g=(c*f-u*h)/d,m=(l*h-p*f)/d,c=m+a,E=pu.pop()||new $r;E.arc=e;E.site=i;E.x=g+s;E.y=c+Math.sqrt(g*g+m*m);E.cy=c;e.circle=E;for(var v=null,x=lu._;x;)if(E.y<x.y||E.y===x.y&&E.x<=x.x){if(!x.L){v=x.P;break}x=x.L}else{if(!x.R){v=x;break}x=x.R}lu.insert(v,E);v||(au=E)}}}}function Kr(e){var t=e.circle;if(t){t.P||(au=t.N);lu.remove(t);pu.push(t);ii(t);e.circle=null}}function Qr(e){for(var t,n=iu,r=Hn(e[0][0],e[0][1],e[1][0],e[1][1]),i=n.length;i--;){t=n[i];if(!Xr(t,e)||!r(t)||va(t.a.x-t.b.x)<ka&&va(t.a.y-t.b.y)<ka){t.a=t.b=null;n.splice(i,1)}}}function Xr(e,t){var n=e.b;if(n)return!0;var r,i,o=e.a,s=t[0][0],a=t[1][0],l=t[0][1],u=t[1][1],p=e.l,c=e.r,d=p.x,f=p.y,h=c.x,g=c.y,m=(d+h)/2,E=(f+g)/2;if(g===f){if(s>m||m>=a)return;if(d>h){if(o){if(o.y>=u)return}else o={x:m,y:l};n={x:m,y:u}}else{if(o){if(o.y<l)return}else o={x:m,y:u};n={x:m,y:l}}}else{r=(d-h)/(g-f);i=E-r*m;if(-1>r||r>1)if(d>h){if(o){if(o.y>=u)return}else o={x:(l-i)/r,y:l};n={x:(u-i)/r,y:u}}else{if(o){if(o.y<l)return}else o={x:(u-i)/r,y:u};n={x:(l-i)/r,y:l}}else if(g>f){if(o){if(o.x>=a)return}else o={x:s,y:r*s+i};n={x:a,y:r*a+i}}else{if(o){if(o.x<s)return}else o={x:a,y:r*a+i};n={x:s,y:r*s+i}}}e.a=o;e.b=n;return!0}function Zr(e,t){this.l=e;this.r=t;this.a=this.b=null}function Jr(e,t,n,r){var i=new Zr(e,t);iu.push(i);n&&ti(i,e,t,n);r&&ti(i,t,e,r);ou[e.i].edges.push(new ni(i,e,t));ou[t.i].edges.push(new ni(i,t,e));return i}function ei(e,t,n){var r=new Zr(e,null);r.a=t;r.b=n;iu.push(r);return r}function ti(e,t,n,r){if(e.a||e.b)e.l===n?e.b=r:e.a=r;else{e.a=r;e.l=t;e.r=n}}function ni(e,t,n){var r=e.a,i=e.b;this.edge=e;this.site=t;this.angle=n?Math.atan2(n.y-t.y,n.x-t.x):e.l===t?Math.atan2(i.x-r.x,r.y-i.y):Math.atan2(r.x-i.x,i.y-r.y)}function ri(){this._=null}function ii(e){e.U=e.C=e.L=e.R=e.P=e.N=null}function oi(e,t){var n=t,r=t.R,i=n.U;i?i.L===n?i.L=r:i.R=r:e._=r;r.U=i;n.U=r;n.R=r.L;n.R&&(n.R.U=n);r.L=n}function si(e,t){var n=t,r=t.L,i=n.U;i?i.L===n?i.L=r:i.R=r:e._=r;r.U=i;n.U=r;n.L=r.R;n.L&&(n.L.U=n);r.R=n}function ai(e){for(;e.L;)e=e.L;return e}function li(e,t){var n,r,i,o=e.sort(ui).pop();iu=[];ou=new Array(e.length);su=new ri;lu=new ri;for(;;){i=au;if(o&&(!i||o.y<i.y||o.y===i.y&&o.x<i.x)){if(o.x!==n||o.y!==r){ou[o.i]=new Hr(o);jr(o);n=o.x,r=o.y}o=e.pop()}else{if(!i)break;Br(i.arc)}}t&&(Qr(t),zr(t));var s={cells:ou,edges:iu};su=lu=iu=ou=null;return s}function ui(e,t){return t.y-e.y||t.x-e.x}function pi(e,t,n){return(e.x-n.x)*(t.y-e.y)-(e.x-t.x)*(n.y-e.y)}function ci(e){return e.x}function di(e){return e.y}function fi(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function hi(e,t,n,r,i,o){if(!e(t,n,r,i,o)){var s=.5*(n+i),a=.5*(r+o),l=t.nodes;l[0]&&hi(e,l[0],n,r,s,a);l[1]&&hi(e,l[1],s,r,i,a);l[2]&&hi(e,l[2],n,a,s,o);l[3]&&hi(e,l[3],s,a,i,o)}}function gi(e,t,n,r,i,o,s){var a,l=1/0;(function u(e,p,c,d,f){if(!(p>o||c>s||r>d||i>f)){if(h=e.point){var h,g=t-h[0],m=n-h[1],E=g*g+m*m;if(l>E){var v=Math.sqrt(l=E);r=t-v,i=n-v;o=t+v,s=n+v;a=h}}for(var x=e.nodes,y=.5*(p+d),N=.5*(c+f),I=t>=y,A=n>=N,T=A<<1|I,L=T+4;L>T;++T)if(e=x[3&T])switch(3&T){case 0:u(e,p,c,y,N);break;case 1:u(e,y,c,d,N);break;case 2:u(e,p,N,y,f);break;case 3:u(e,y,N,d,f)}}})(e,r,i,o,s);return a}function mi(e,t){e=ia.rgb(e);t=ia.rgb(t);var n=e.r,r=e.g,i=e.b,o=t.r-n,s=t.g-r,a=t.b-i;return function(e){return"#"+Nt(Math.round(n+o*e))+Nt(Math.round(r+s*e))+Nt(Math.round(i+a*e))}}function Ei(e,t){var n,r={},i={};for(n in e)n in t?r[n]=yi(e[n],t[n]):i[n]=e[n];for(n in t)n in e||(i[n]=t[n]);return function(e){for(n in r)i[n]=r[n](e);return i}}function vi(e,t){e=+e,t=+t;return function(n){return e*(1-n)+t*n}}function xi(e,t){var n,r,i,o=du.lastIndex=fu.lastIndex=0,s=-1,a=[],l=[];e+="",t+="";for(;(n=du.exec(e))&&(r=fu.exec(t));){if((i=r.index)>o){i=t.slice(o,i);a[s]?a[s]+=i:a[++s]=i}if((n=n[0])===(r=r[0]))a[s]?a[s]+=r:a[++s]=r;else{a[++s]=null;l.push({i:s,x:vi(n,r)})}o=fu.lastIndex}if(o<t.length){i=t.slice(o);a[s]?a[s]+=i:a[++s]=i}return a.length<2?l[0]?(t=l[0].x,function(e){return t(e)+""}):function(){return t}:(t=l.length,function(e){for(var n,r=0;t>r;++r)a[(n=l[r]).i]=n.x(e);return a.join("")})}function yi(e,t){for(var n,r=ia.interpolators.length;--r>=0&&!(n=ia.interpolators[r](e,t)););return n}function Ni(e,t){var n,r=[],i=[],o=e.length,s=t.length,a=Math.min(e.length,t.length);for(n=0;a>n;++n)r.push(yi(e[n],t[n]));for(;o>n;++n)i[n]=e[n];for(;s>n;++n)i[n]=t[n];return function(e){for(n=0;a>n;++n)i[n]=r[n](e);return i}}function Ii(e){return function(t){return 0>=t?0:t>=1?1:e(t)}}function Ai(e){return function(t){return 1-e(1-t)}}function Ti(e){return function(t){return.5*(.5>t?e(2*t):2-e(2-2*t))}}function Li(e){return e*e}function Si(e){return e*e*e}function Ci(e){if(0>=e)return 0;if(e>=1)return 1;var t=e*e,n=t*e;return 4*(.5>e?n:3*(e-t)+n-.75)}function bi(e){return function(t){return Math.pow(t,e)}}function Ri(e){return 1-Math.cos(e*ja)}function wi(e){return Math.pow(2,10*(e-1))}function Oi(e){return 1-Math.sqrt(1-e*e)}function _i(e,t){var n;arguments.length<2&&(t=.45);arguments.length?n=t/Ua*Math.asin(1/e):(e=1,n=t/4);return function(r){return 1+e*Math.pow(2,-10*r)*Math.sin((r-n)*Ua/t)}}function Fi(e){e||(e=1.70158);return function(t){return t*t*((e+1)*t-e)}}function Pi(e){return 1/2.75>e?7.5625*e*e:2/2.75>e?7.5625*(e-=1.5/2.75)*e+.75:2.5/2.75>e?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function Mi(e,t){e=ia.hcl(e);t=ia.hcl(t);var n=e.h,r=e.c,i=e.l,o=t.h-n,s=t.c-r,a=t.l-i;isNaN(s)&&(s=0,r=isNaN(r)?t.c:r);isNaN(o)?(o=0,n=isNaN(n)?t.h:n):o>180?o-=360:-180>o&&(o+=360);return function(e){return ct(n+o*e,r+s*e,i+a*e)+""}}function ki(e,t){e=ia.hsl(e);t=ia.hsl(t);var n=e.h,r=e.s,i=e.l,o=t.h-n,s=t.s-r,a=t.l-i;isNaN(s)&&(s=0,r=isNaN(r)?t.s:r);isNaN(o)?(o=0,n=isNaN(n)?t.h:n):o>180?o-=360:-180>o&&(o+=360);return function(e){return ut(n+o*e,r+s*e,i+a*e)+""}}function Di(e,t){e=ia.lab(e);t=ia.lab(t);var n=e.l,r=e.a,i=e.b,o=t.l-n,s=t.a-r,a=t.b-i;return function(e){return ft(n+o*e,r+s*e,i+a*e)+""}}function Gi(e,t){t-=e;return function(n){return Math.round(e+t*n)}}function Ui(e){var t=[e.a,e.b],n=[e.c,e.d],r=ji(t),i=Bi(t,n),o=ji(qi(n,t,-i))||0;if(t[0]*n[1]<n[0]*t[1]){t[0]*=-1;t[1]*=-1;r*=-1;i*=-1}this.rotate=(r?Math.atan2(t[1],t[0]):Math.atan2(-n[0],n[1]))*Va;this.translate=[e.e,e.f];this.scale=[r,o];this.skew=o?Math.atan2(i,o)*Va:0}function Bi(e,t){return e[0]*t[0]+e[1]*t[1]}function ji(e){var t=Math.sqrt(Bi(e,e));if(t){e[0]/=t;e[1]/=t}return t}function qi(e,t,n){e[0]+=n*t[0];e[1]+=n*t[1];return e}function Vi(e,t){var n,r=[],i=[],o=ia.transform(e),s=ia.transform(t),a=o.translate,l=s.translate,u=o.rotate,p=s.rotate,c=o.skew,d=s.skew,f=o.scale,h=s.scale;if(a[0]!=l[0]||a[1]!=l[1]){r.push("translate(",null,",",null,")");i.push({i:1,x:vi(a[0],l[0])},{i:3,x:vi(a[1],l[1])})}else r.push(l[0]||l[1]?"translate("+l+")":"");if(u!=p){u-p>180?p+=360:p-u>180&&(u+=360);i.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:vi(u,p)})}else p&&r.push(r.pop()+"rotate("+p+")");c!=d?i.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:vi(c,d)}):d&&r.push(r.pop()+"skewX("+d+")");if(f[0]!=h[0]||f[1]!=h[1]){n=r.push(r.pop()+"scale(",null,",",null,")");i.push({i:n-4,x:vi(f[0],h[0])},{i:n-2,x:vi(f[1],h[1])})}else(1!=h[0]||1!=h[1])&&r.push(r.pop()+"scale("+h+")");n=i.length;return function(e){for(var t,o=-1;++o<n;)r[(t=i[o]).i]=t.x(e);return r.join("")}}function Hi(e,t){t=(t-=e=+e)||1/t;return function(n){return(n-e)/t}}function zi(e,t){t=(t-=e=+e)||1/t;return function(n){return Math.max(0,Math.min(1,(n-e)/t))}}function Wi(e){for(var t=e.source,n=e.target,r=Yi(t,n),i=[t];t!==r;){t=t.parent;i.push(t)}for(var o=i.length;n!==r;){i.splice(o,0,n);n=n.parent}return i}function $i(e){for(var t=[],n=e.parent;null!=n;){t.push(e);e=n;n=n.parent}t.push(e);return t}function Yi(e,t){if(e===t)return e;for(var n=$i(e),r=$i(t),i=n.pop(),o=r.pop(),s=null;i===o;){s=i;i=n.pop();o=r.pop()}return s}function Ki(e){e.fixed|=2}function Qi(e){e.fixed&=-7}function Xi(e){e.fixed|=4;e.px=e.x,e.py=e.y}function Zi(e){e.fixed&=-5}function Ji(e,t,n){var r=0,i=0;e.charge=0;if(!e.leaf)for(var o,s=e.nodes,a=s.length,l=-1;++l<a;){o=s[l];if(null!=o){Ji(o,t,n);e.charge+=o.charge;r+=o.charge*o.cx;i+=o.charge*o.cy}}if(e.point){if(!e.leaf){e.point.x+=Math.random()-.5;e.point.y+=Math.random()-.5}var u=t*n[e.point.index];e.charge+=e.pointCharge=u;r+=u*e.point.x;i+=u*e.point.y}e.cx=r/e.charge;e.cy=i/e.charge}function eo(e,t){ia.rebind(e,t,"sort","children","value");e.nodes=e;e.links=so;return e}function to(e,t){for(var n=[e];null!=(e=n.pop());){t(e);if((i=e.children)&&(r=i.length))for(var r,i;--r>=0;)n.push(i[r])}}function no(e,t){for(var n=[e],r=[];null!=(e=n.pop());){r.push(e);if((o=e.children)&&(i=o.length))for(var i,o,s=-1;++s<i;)n.push(o[s])}for(;null!=(e=r.pop());)t(e)}function ro(e){return e.children}function io(e){return e.value}function oo(e,t){return t.value-e.value}function so(e){return ia.merge(e.map(function(e){return(e.children||[]).map(function(t){return{source:e,target:t}})}))}function ao(e){return e.x}function lo(e){return e.y}function uo(e,t,n){e.y0=t;e.y=n}function po(e){return ia.range(e.length)}function co(e){for(var t=-1,n=e[0].length,r=[];++t<n;)r[t]=0;return r}function fo(e){for(var t,n=1,r=0,i=e[0][1],o=e.length;o>n;++n)if((t=e[n][1])>i){r=n;i=t}return r}function ho(e){return e.reduce(go,0)}function go(e,t){return e+t[1]}function mo(e,t){return Eo(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function Eo(e,t){for(var n=-1,r=+e[0],i=(e[1]-r)/t,o=[];++n<=t;)o[n]=i*n+r;return o}function vo(e){return[ia.min(e),ia.max(e)]}function xo(e,t){return e.value-t.value}function yo(e,t){var n=e._pack_next;e._pack_next=t;t._pack_prev=e;t._pack_next=n;n._pack_prev=t}function No(e,t){e._pack_next=t;t._pack_prev=e}function Io(e,t){var n=t.x-e.x,r=t.y-e.y,i=e.r+t.r;return.999*i*i>n*n+r*r}function Ao(e){function t(e){p=Math.min(e.x-e.r,p);c=Math.max(e.x+e.r,c);d=Math.min(e.y-e.r,d);f=Math.max(e.y+e.r,f)}if((n=e.children)&&(u=n.length)){var n,r,i,o,s,a,l,u,p=1/0,c=-1/0,d=1/0,f=-1/0;n.forEach(To);r=n[0];r.x=-r.r;r.y=0;t(r);if(u>1){i=n[1];i.x=i.r;i.y=0;t(i);if(u>2){o=n[2];Co(r,i,o);t(o);yo(r,o);r._pack_prev=o;yo(o,i);i=r._pack_next;for(s=3;u>s;s++){Co(r,i,o=n[s]);var h=0,g=1,m=1;for(a=i._pack_next;a!==i;a=a._pack_next,g++)if(Io(a,o)){h=1;break}if(1==h)for(l=r._pack_prev;l!==a._pack_prev&&!Io(l,o);l=l._pack_prev,m++);if(h){m>g||g==m&&i.r<r.r?No(r,i=a):No(r=l,i);s--}else{yo(r,o);i=o;t(o)}}}}var E=(p+c)/2,v=(d+f)/2,x=0;for(s=0;u>s;s++){o=n[s];o.x-=E;o.y-=v;x=Math.max(x,o.r+Math.sqrt(o.x*o.x+o.y*o.y))}e.r=x;n.forEach(Lo)}}function To(e){e._pack_next=e._pack_prev=e}function Lo(e){delete e._pack_next;delete e._pack_prev}function So(e,t,n,r){var i=e.children;e.x=t+=r*e.x;e.y=n+=r*e.y;e.r*=r;if(i)for(var o=-1,s=i.length;++o<s;)So(i[o],t,n,r)}function Co(e,t,n){var r=e.r+n.r,i=t.x-e.x,o=t.y-e.y;if(r&&(i||o)){var s=t.r+n.r,a=i*i+o*o;s*=s;r*=r;var l=.5+(r-s)/(2*a),u=Math.sqrt(Math.max(0,2*s*(r+a)-(r-=a)*r-s*s))/(2*a);n.x=e.x+l*i+u*o;n.y=e.y+l*o-u*i}else{n.x=e.x+r;n.y=e.y}}function bo(e,t){return e.parent==t.parent?1:2}function Ro(e){var t=e.children;return t.length?t[0]:e.t}function wo(e){var t,n=e.children;return(t=n.length)?n[t-1]:e.t}function Oo(e,t,n){var r=n/(t.i-e.i);t.c-=r;t.s+=n;e.c+=r;t.z+=n;t.m+=n}function _o(e){for(var t,n=0,r=0,i=e.children,o=i.length;--o>=0;){t=i[o];t.z+=n;t.m+=n;n+=t.s+(r+=t.c)}}function Fo(e,t,n){return e.a.parent===t.parent?e.a:n}function Po(e){return 1+ia.max(e,function(e){return e.y})}function Mo(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}function ko(e){var t=e.children;return t&&t.length?ko(t[0]):e}function Do(e){var t,n=e.children;return n&&(t=n.length)?Do(n[t-1]):e}function Go(e){return{x:e.x,y:e.y,dx:e.dx,dy:e.dy}}function Uo(e,t){var n=e.x+t[3],r=e.y+t[0],i=e.dx-t[1]-t[3],o=e.dy-t[0]-t[2];if(0>i){n+=i/2;i=0}if(0>o){r+=o/2;o=0}return{x:n,y:r,dx:i,dy:o}}function Bo(e){var t=e[0],n=e[e.length-1];return n>t?[t,n]:[n,t]}function jo(e){return e.rangeExtent?e.rangeExtent():Bo(e.range())}function qo(e,t,n,r){var i=n(e[0],e[1]),o=r(t[0],t[1]);return function(e){return o(i(e))}}function Vo(e,t){var n,r=0,i=e.length-1,o=e[r],s=e[i];if(o>s){n=r,r=i,i=n;n=o,o=s,s=n}e[r]=t.floor(o);e[i]=t.ceil(s);return e}function Ho(e){return e?{floor:function(t){return Math.floor(t/e)*e},ceil:function(t){return Math.ceil(t/e)*e}}:Tu}function zo(e,t,n,r){var i=[],o=[],s=0,a=Math.min(e.length,t.length)-1;if(e[a]<e[0]){e=e.slice().reverse();t=t.slice().reverse()}for(;++s<=a;){i.push(n(e[s-1],e[s]));o.push(r(t[s-1],t[s]))}return function(t){var n=ia.bisect(e,t,1,a)-1;return o[n](i[n](t))}}function Wo(e,t,n,r){function i(){var i=Math.min(e.length,t.length)>2?zo:qo,l=r?zi:Hi;s=i(e,t,l,n);a=i(t,e,l,yi);return o}function o(e){return s(e)}var s,a;o.invert=function(e){return a(e)};o.domain=function(t){if(!arguments.length)return e;e=t.map(Number);return i()};o.range=function(e){if(!arguments.length)return t;t=e;return i()};o.rangeRound=function(e){return o.range(e).interpolate(Gi)};o.clamp=function(e){if(!arguments.length)return r;r=e;return i()};o.interpolate=function(e){if(!arguments.length)return n;n=e;return i()};o.ticks=function(t){return Qo(e,t)};o.tickFormat=function(t,n){return Xo(e,t,n)};o.nice=function(t){Yo(e,t);return i()};o.copy=function(){return Wo(e,t,n,r)};return i()}function $o(e,t){return ia.rebind(e,t,"range","rangeRound","interpolate","clamp")}function Yo(e,t){return Vo(e,Ho(Ko(e,t)[2]))}function Ko(e,t){null==t&&(t=10);var n=Bo(e),r=n[1]-n[0],i=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),o=t/r*i;.15>=o?i*=10:.35>=o?i*=5:.75>=o&&(i*=2);n[0]=Math.ceil(n[0]/i)*i;n[1]=Math.floor(n[1]/i)*i+.5*i;n[2]=i;return n}function Qo(e,t){return ia.range.apply(ia,Ko(e,t))}function Xo(e,t,n){var r=Ko(e,t);if(n){var i=dl.exec(n);i.shift();if("s"===i[8]){var o=ia.formatPrefix(Math.max(va(r[0]),va(r[1])));i[7]||(i[7]="."+Zo(o.scale(r[2])));i[8]="f";n=ia.format(i.join(""));return function(e){return n(o.scale(e))+o.symbol}}i[7]||(i[7]="."+Jo(i[8],r));n=i.join("")}else n=",."+Zo(r[2])+"f";return ia.format(n)}function Zo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}function Jo(e,t){var n=Zo(t[2]);return e in Lu?Math.abs(n-Zo(Math.max(va(t[0]),va(t[1]))))+ +("e"!==e):n-2*("%"===e)}function es(e,t,n,r){function i(e){return(n?Math.log(0>e?0:e):-Math.log(e>0?0:-e))/Math.log(t)}function o(e){return n?Math.pow(t,e):-Math.pow(t,-e)}function s(t){return e(i(t))}s.invert=function(t){return o(e.invert(t))};s.domain=function(t){if(!arguments.length)return r;n=t[0]>=0;e.domain((r=t.map(Number)).map(i));return s};s.base=function(n){if(!arguments.length)return t;t=+n;e.domain(r.map(i));return s};s.nice=function(){var t=Vo(r.map(i),n?Math:Cu);e.domain(t);r=t.map(o);return s};s.ticks=function(){var e=Bo(r),s=[],a=e[0],l=e[1],u=Math.floor(i(a)),p=Math.ceil(i(l)),c=t%1?2:t;if(isFinite(p-u)){if(n){for(;p>u;u++)for(var d=1;c>d;d++)s.push(o(u)*d);s.push(o(u))}else{s.push(o(u));for(;u++<p;)for(var d=c-1;d>0;d--)s.push(o(u)*d)}for(u=0;s[u]<a;u++);for(p=s.length;s[p-1]>l;p--);s=s.slice(u,p)}return s};s.tickFormat=function(e,t){if(!arguments.length)return Su;arguments.length<2?t=Su:"function"!=typeof t&&(t=ia.format(t));var r,a=Math.max(.1,e/s.ticks().length),l=n?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(e){return e/o(l(i(e)+r))<=a?t(e):""}};s.copy=function(){return es(e.copy(),t,n,r)};return $o(s,e)}function ts(e,t,n){function r(t){return e(i(t))}var i=ns(t),o=ns(1/t);r.invert=function(t){return o(e.invert(t))};r.domain=function(t){if(!arguments.length)return n;e.domain((n=t.map(Number)).map(i));return r};r.ticks=function(e){return Qo(n,e)};r.tickFormat=function(e,t){return Xo(n,e,t)};r.nice=function(e){return r.domain(Yo(n,e))};r.exponent=function(s){if(!arguments.length)return t;i=ns(t=s);o=ns(1/t);e.domain(n.map(i));return r};r.copy=function(){return ts(e.copy(),t,n)};return $o(r,e)}function ns(e){return function(t){return 0>t?-Math.pow(-t,e):Math.pow(t,e)}}function rs(e,t){function n(n){return o[((i.get(n)||("range"===t.t?i.set(n,e.push(n)):0/0))-1)%o.length]}function r(t,n){return ia.range(e.length).map(function(e){return t+n*e})}var i,o,s;n.domain=function(r){if(!arguments.length)return e;e=[];i=new u;for(var o,s=-1,a=r.length;++s<a;)i.has(o=r[s])||i.set(o,e.push(o));return n[t.t].apply(n,t.a)};n.range=function(e){if(!arguments.length)return o;o=e;s=0;t={t:"range",a:arguments};return n};n.rangePoints=function(i,a){arguments.length<2&&(a=0);var l=i[0],u=i[1],p=e.length<2?(l=(l+u)/2,0):(u-l)/(e.length-1+a);o=r(l+p*a/2,p);s=0;t={t:"rangePoints",a:arguments};return n};n.rangeRoundPoints=function(i,a){arguments.length<2&&(a=0);var l=i[0],u=i[1],p=e.length<2?(l=u=Math.round((l+u)/2),0):(u-l)/(e.length-1+a)|0;o=r(l+Math.round(p*a/2+(u-l-(e.length-1+a)*p)/2),p);s=0;t={t:"rangeRoundPoints",a:arguments};return n};n.rangeBands=function(i,a,l){arguments.length<2&&(a=0);arguments.length<3&&(l=a);var u=i[1]<i[0],p=i[u-0],c=i[1-u],d=(c-p)/(e.length-a+2*l);o=r(p+d*l,d);u&&o.reverse();s=d*(1-a);t={t:"rangeBands",a:arguments};return n};n.rangeRoundBands=function(i,a,l){arguments.length<2&&(a=0);arguments.length<3&&(l=a);var u=i[1]<i[0],p=i[u-0],c=i[1-u],d=Math.floor((c-p)/(e.length-a+2*l));o=r(p+Math.round((c-p-(e.length-a)*d)/2),d);u&&o.reverse();s=Math.round(d*(1-a));t={t:"rangeRoundBands",a:arguments};return n};n.rangeBand=function(){return s};n.rangeExtent=function(){return Bo(t.a[0])};n.copy=function(){return rs(e,t)};return n.domain(e)}function is(e,n){function o(){var t=0,r=n.length;a=[];for(;++t<r;)a[t-1]=ia.quantile(e,t/r);return s}function s(e){return isNaN(e=+e)?void 0:n[ia.bisect(a,e)]}var a;s.domain=function(n){if(!arguments.length)return e;e=n.map(r).filter(i).sort(t);return o()};s.range=function(e){if(!arguments.length)return n;n=e;return o()};s.quantiles=function(){return a};s.invertExtent=function(t){t=n.indexOf(t);return 0>t?[0/0,0/0]:[t>0?a[t-1]:e[0],t<a.length?a[t]:e[e.length-1]]};s.copy=function(){return is(e,n)};return o()}function os(e,t,n){function r(t){return n[Math.max(0,Math.min(s,Math.floor(o*(t-e))))]}function i(){o=n.length/(t-e);s=n.length-1;return r}var o,s;r.domain=function(n){if(!arguments.length)return[e,t];e=+n[0];t=+n[n.length-1];return i()};r.range=function(e){if(!arguments.length)return n;n=e;return i()};r.invertExtent=function(t){t=n.indexOf(t);t=0>t?0/0:t/o+e;return[t,t+1/o]};r.copy=function(){return os(e,t,n)};return i()}function ss(e,t){function n(n){return n>=n?t[ia.bisect(e,n)]:void 0}n.domain=function(t){if(!arguments.length)return e;e=t;return n};n.range=function(e){if(!arguments.length)return t;t=e;return n};n.invertExtent=function(n){n=t.indexOf(n);return[e[n-1],e[n]]};n.copy=function(){return ss(e,t)};return n}function as(e){function t(e){return+e}t.invert=t;t.domain=t.range=function(n){if(!arguments.length)return e;e=n.map(t);return t};t.ticks=function(t){return Qo(e,t)};t.tickFormat=function(t,n){return Xo(e,t,n)};t.copy=function(){return as(e)};return t}function ls(){return 0}function us(e){return e.innerRadius}function ps(e){return e.outerRadius}function cs(e){return e.startAngle}function ds(e){return e.endAngle}function fs(e){return e&&e.padAngle}function hs(e,t,n,r){return(e-n)*t-(t-r)*e>0?0:1}function gs(e,t,n,r,i){var o=e[0]-t[0],s=e[1]-t[1],a=(i?r:-r)/Math.sqrt(o*o+s*s),l=a*s,u=-a*o,p=e[0]+l,c=e[1]+u,d=t[0]+l,f=t[1]+u,h=(p+d)/2,g=(c+f)/2,m=d-p,E=f-c,v=m*m+E*E,x=n-r,y=p*f-d*c,N=(0>E?-1:1)*Math.sqrt(x*x*v-y*y),I=(y*E-m*N)/v,A=(-y*m-E*N)/v,T=(y*E+m*N)/v,L=(-y*m+E*N)/v,S=I-h,C=A-g,b=T-h,R=L-g;S*S+C*C>b*b+R*R&&(I=T,A=L);return[[I-l,A-u],[I*n/x,A*n/x]]}function ms(e){function t(t){function s(){u.push("M",o(e(p),a))}for(var l,u=[],p=[],c=-1,d=t.length,f=Ct(n),h=Ct(r);++c<d;)if(i.call(this,l=t[c],c))p.push([+f.call(this,l,c),+h.call(this,l,c)]);else if(p.length){s();p=[]}p.length&&s();return u.length?u.join(""):null}var n=wr,r=Or,i=On,o=Es,s=o.key,a=.7;t.x=function(e){if(!arguments.length)return n;n=e;return t};t.y=function(e){if(!arguments.length)return r;r=e;return t};t.defined=function(e){if(!arguments.length)return i;i=e;return t};t.interpolate=function(e){if(!arguments.length)return s;
s="function"==typeof e?o=e:(o=Fu.get(e)||Es).key;return t};t.tension=function(e){if(!arguments.length)return a;a=e;return t};return t}function Es(e){return e.join("L")}function vs(e){return Es(e)+"Z"}function xs(e){for(var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];++t<n;)i.push("H",(r[0]+(r=e[t])[0])/2,"V",r[1]);n>1&&i.push("H",r[0]);return i.join("")}function ys(e){for(var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];++t<n;)i.push("V",(r=e[t])[1],"H",r[0]);return i.join("")}function Ns(e){for(var t=0,n=e.length,r=e[0],i=[r[0],",",r[1]];++t<n;)i.push("H",(r=e[t])[0],"V",r[1]);return i.join("")}function Is(e,t){return e.length<4?Es(e):e[1]+Ls(e.slice(1,-1),Ss(e,t))}function As(e,t){return e.length<3?Es(e):e[0]+Ls((e.push(e[0]),e),Ss([e[e.length-2]].concat(e,[e[1]]),t))}function Ts(e,t){return e.length<3?Es(e):e[0]+Ls(e,Ss(e,t))}function Ls(e,t){if(t.length<1||e.length!=t.length&&e.length!=t.length+2)return Es(e);var n=e.length!=t.length,r="",i=e[0],o=e[1],s=t[0],a=s,l=1;if(n){r+="Q"+(o[0]-2*s[0]/3)+","+(o[1]-2*s[1]/3)+","+o[0]+","+o[1];i=e[1];l=2}if(t.length>1){a=t[1];o=e[l];l++;r+="C"+(i[0]+s[0])+","+(i[1]+s[1])+","+(o[0]-a[0])+","+(o[1]-a[1])+","+o[0]+","+o[1];for(var u=2;u<t.length;u++,l++){o=e[l];a=t[u];r+="S"+(o[0]-a[0])+","+(o[1]-a[1])+","+o[0]+","+o[1]}}if(n){var p=e[l];r+="Q"+(o[0]+2*a[0]/3)+","+(o[1]+2*a[1]/3)+","+p[0]+","+p[1]}return r}function Ss(e,t){for(var n,r=[],i=(1-t)/2,o=e[0],s=e[1],a=1,l=e.length;++a<l;){n=o;o=s;s=e[a];r.push([i*(s[0]-n[0]),i*(s[1]-n[1])])}return r}function Cs(e){if(e.length<3)return Es(e);var t=1,n=e.length,r=e[0],i=r[0],o=r[1],s=[i,i,i,(r=e[1])[0]],a=[o,o,o,r[1]],l=[i,",",o,"L",Os(ku,s),",",Os(ku,a)];e.push(e[n-1]);for(;++t<=n;){r=e[t];s.shift();s.push(r[0]);a.shift();a.push(r[1]);_s(l,s,a)}e.pop();l.push("L",r);return l.join("")}function bs(e){if(e.length<4)return Es(e);for(var t,n=[],r=-1,i=e.length,o=[0],s=[0];++r<3;){t=e[r];o.push(t[0]);s.push(t[1])}n.push(Os(ku,o)+","+Os(ku,s));--r;for(;++r<i;){t=e[r];o.shift();o.push(t[0]);s.shift();s.push(t[1]);_s(n,o,s)}return n.join("")}function Rs(e){for(var t,n,r=-1,i=e.length,o=i+4,s=[],a=[];++r<4;){n=e[r%i];s.push(n[0]);a.push(n[1])}t=[Os(ku,s),",",Os(ku,a)];--r;for(;++r<o;){n=e[r%i];s.shift();s.push(n[0]);a.shift();a.push(n[1]);_s(t,s,a)}return t.join("")}function ws(e,t){var n=e.length-1;if(n)for(var r,i,o=e[0][0],s=e[0][1],a=e[n][0]-o,l=e[n][1]-s,u=-1;++u<=n;){r=e[u];i=u/n;r[0]=t*r[0]+(1-t)*(o+i*a);r[1]=t*r[1]+(1-t)*(s+i*l)}return Cs(e)}function Os(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}function _s(e,t,n){e.push("C",Os(Pu,t),",",Os(Pu,n),",",Os(Mu,t),",",Os(Mu,n),",",Os(ku,t),",",Os(ku,n))}function Fs(e,t){return(t[1]-e[1])/(t[0]-e[0])}function Ps(e){for(var t=0,n=e.length-1,r=[],i=e[0],o=e[1],s=r[0]=Fs(i,o);++t<n;)r[t]=(s+(s=Fs(i=o,o=e[t+1])))/2;r[t]=s;return r}function Ms(e){for(var t,n,r,i,o=[],s=Ps(e),a=-1,l=e.length-1;++a<l;){t=Fs(e[a],e[a+1]);if(va(t)<ka)s[a]=s[a+1]=0;else{n=s[a]/t;r=s[a+1]/t;i=n*n+r*r;if(i>9){i=3*t/Math.sqrt(i);s[a]=i*n;s[a+1]=i*r}}}a=-1;for(;++a<=l;){i=(e[Math.min(l,a+1)][0]-e[Math.max(0,a-1)][0])/(6*(1+s[a]*s[a]));o.push([i||0,s[a]*i||0])}return o}function ks(e){return e.length<3?Es(e):e[0]+Ls(e,Ms(e))}function Ds(e){for(var t,n,r,i=-1,o=e.length;++i<o;){t=e[i];n=t[0];r=t[1]-ja;t[0]=n*Math.cos(r);t[1]=n*Math.sin(r)}return e}function Gs(e){function t(t){function l(){g.push("M",a(e(E),c),p,u(e(m.reverse()),c),"Z")}for(var d,f,h,g=[],m=[],E=[],v=-1,x=t.length,y=Ct(n),N=Ct(i),I=n===r?function(){return f}:Ct(r),A=i===o?function(){return h}:Ct(o);++v<x;)if(s.call(this,d=t[v],v)){m.push([f=+y.call(this,d,v),h=+N.call(this,d,v)]);E.push([+I.call(this,d,v),+A.call(this,d,v)])}else if(m.length){l();m=[];E=[]}m.length&&l();return g.length?g.join(""):null}var n=wr,r=wr,i=0,o=Or,s=On,a=Es,l=a.key,u=a,p="L",c=.7;t.x=function(e){if(!arguments.length)return r;n=r=e;return t};t.x0=function(e){if(!arguments.length)return n;n=e;return t};t.x1=function(e){if(!arguments.length)return r;r=e;return t};t.y=function(e){if(!arguments.length)return o;i=o=e;return t};t.y0=function(e){if(!arguments.length)return i;i=e;return t};t.y1=function(e){if(!arguments.length)return o;o=e;return t};t.defined=function(e){if(!arguments.length)return s;s=e;return t};t.interpolate=function(e){if(!arguments.length)return l;l="function"==typeof e?a=e:(a=Fu.get(e)||Es).key;u=a.reverse||a;p=a.closed?"M":"L";return t};t.tension=function(e){if(!arguments.length)return c;c=e;return t};return t}function Us(e){return e.radius}function Bs(e){return[e.x,e.y]}function js(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]-ja;return[n*Math.cos(r),n*Math.sin(r)]}}function qs(){return 64}function Vs(){return"circle"}function Hs(e){var t=Math.sqrt(e/Ga);return"M0,"+t+"A"+t+","+t+" 0 1,1 0,"+-t+"A"+t+","+t+" 0 1,1 0,"+t+"Z"}function zs(e){return function(){var t,n;if((t=this[e])&&(n=t[t.active])){--t.count?delete t[t.active]:delete this[e];t.active+=.5;n.event&&n.event.interrupt.call(this,this.__data__,n.index)}}}function Ws(e,t,n){Aa(e,Vu);e.namespace=t;e.id=n;return e}function $s(e,t,n,r){var i=e.id,o=e.namespace;return q(e,"function"==typeof n?function(e,s,a){e[o][i].tween.set(t,r(n.call(e,e.__data__,s,a)))}:(n=r(n),function(e){e[o][i].tween.set(t,n)}))}function Ys(e){null==e&&(e="");return function(){this.textContent=e}}function Ks(e){return null==e?"__transition__":"__transition_"+e+"__"}function Qs(e,t,n,r,i){var o=e[n]||(e[n]={active:0,count:0}),s=o[r];if(!s){var a=i.time;s=o[r]={tween:new u,time:a,delay:i.delay,duration:i.duration,ease:i.ease,index:t};i=null;++o.count;ia.timer(function(i){function l(n){if(o.active>r)return p();var i=o[o.active];if(i){--o.count;delete o[o.active];i.event&&i.event.interrupt.call(e,e.__data__,i.index)}o.active=r;s.event&&s.event.start.call(e,e.__data__,t);s.tween.forEach(function(n,r){(r=r.call(e,e.__data__,t))&&g.push(r)});d=s.ease;c=s.duration;ia.timer(function(){h.c=u(n||1)?On:u;return 1},0,a)}function u(n){if(o.active!==r)return 1;for(var i=n/c,a=d(i),l=g.length;l>0;)g[--l].call(e,a);if(i>=1){s.event&&s.event.end.call(e,e.__data__,t);return p()}}function p(){--o.count?delete o[r]:delete e[n];return 1}var c,d,f=s.delay,h=ul,g=[];h.t=f+a;if(i>=f)return l(i-f);h.c=l;return void 0},0,a)}}function Xs(e,t,n){e.attr("transform",function(e){var r=t(e);return"translate("+(isFinite(r)?r:n(e))+",0)"})}function Zs(e,t,n){e.attr("transform",function(e){var r=t(e);return"translate(0,"+(isFinite(r)?r:n(e))+")"})}function Js(e){return e.toISOString()}function ea(e,t,n){function r(t){return e(t)}function i(e,n){var r=e[1]-e[0],i=r/n,o=ia.bisect(Zu,i);return o==Zu.length?[t.year,Ko(e.map(function(e){return e/31536e6}),n)[2]]:o?t[i/Zu[o-1]<Zu[o]/i?o-1:o]:[tp,Ko(e,n)[2]]}r.invert=function(t){return ta(e.invert(t))};r.domain=function(t){if(!arguments.length)return e.domain().map(ta);e.domain(t);return r};r.nice=function(e,t){function n(n){return!isNaN(n)&&!e.range(n,ta(+n+1),t).length}var o=r.domain(),s=Bo(o),a=null==e?i(s,10):"number"==typeof e&&i(s,e);a&&(e=a[0],t=a[1]);return r.domain(Vo(o,t>1?{floor:function(t){for(;n(t=e.floor(t));)t=ta(t-1);return t},ceil:function(t){for(;n(t=e.ceil(t));)t=ta(+t+1);return t}}:e))};r.ticks=function(e,t){var n=Bo(r.domain()),o=null==e?i(n,10):"number"==typeof e?i(n,e):!e.range&&[{range:e},t];o&&(e=o[0],t=o[1]);return e.range(n[0],ta(+n[1]+1),1>t?1:t)};r.tickFormat=function(){return n};r.copy=function(){return ea(e.copy(),t,n)};return $o(r,e)}function ta(e){return new Date(e)}function na(e){return JSON.parse(e.responseText)}function ra(e){var t=aa.createRange();t.selectNode(aa.body);return t.createContextualFragment(e.responseText)}var ia={version:"3.5.3"};Date.now||(Date.now=function(){return+new Date});var oa=[].slice,sa=function(e){return oa.call(e)},aa=document,la=aa.documentElement,ua=window;try{sa(la.childNodes)[0].nodeType}catch(pa){sa=function(e){for(var t=e.length,n=new Array(t);t--;)n[t]=e[t];return n}}try{aa.createElement("div").style.setProperty("opacity",0,"")}catch(ca){var da=ua.Element.prototype,fa=da.setAttribute,ha=da.setAttributeNS,ga=ua.CSSStyleDeclaration.prototype,ma=ga.setProperty;da.setAttribute=function(e,t){fa.call(this,e,t+"")};da.setAttributeNS=function(e,t,n){ha.call(this,e,t,n+"")};ga.setProperty=function(e,t,n){ma.call(this,e,t+"",n)}}ia.ascending=t;ia.descending=function(e,t){return e>t?-1:t>e?1:t>=e?0:0/0};ia.min=function(e,t){var n,r,i=-1,o=e.length;if(1===arguments.length){for(;++i<o;)if(null!=(r=e[i])&&r>=r){n=r;break}for(;++i<o;)null!=(r=e[i])&&n>r&&(n=r)}else{for(;++i<o;)if(null!=(r=t.call(e,e[i],i))&&r>=r){n=r;break}for(;++i<o;)null!=(r=t.call(e,e[i],i))&&n>r&&(n=r)}return n};ia.max=function(e,t){var n,r,i=-1,o=e.length;if(1===arguments.length){for(;++i<o;)if(null!=(r=e[i])&&r>=r){n=r;break}for(;++i<o;)null!=(r=e[i])&&r>n&&(n=r)}else{for(;++i<o;)if(null!=(r=t.call(e,e[i],i))&&r>=r){n=r;break}for(;++i<o;)null!=(r=t.call(e,e[i],i))&&r>n&&(n=r)}return n};ia.extent=function(e,t){var n,r,i,o=-1,s=e.length;if(1===arguments.length){for(;++o<s;)if(null!=(r=e[o])&&r>=r){n=i=r;break}for(;++o<s;)if(null!=(r=e[o])){n>r&&(n=r);r>i&&(i=r)}}else{for(;++o<s;)if(null!=(r=t.call(e,e[o],o))&&r>=r){n=i=r;break}for(;++o<s;)if(null!=(r=t.call(e,e[o],o))){n>r&&(n=r);r>i&&(i=r)}}return[n,i]};ia.sum=function(e,t){var n,r=0,o=e.length,s=-1;if(1===arguments.length)for(;++s<o;)i(n=+e[s])&&(r+=n);else for(;++s<o;)i(n=+t.call(e,e[s],s))&&(r+=n);return r};ia.mean=function(e,t){var n,o=0,s=e.length,a=-1,l=s;if(1===arguments.length)for(;++a<s;)i(n=r(e[a]))?o+=n:--l;else for(;++a<s;)i(n=r(t.call(e,e[a],a)))?o+=n:--l;return l?o/l:void 0};ia.quantile=function(e,t){var n=(e.length-1)*t+1,r=Math.floor(n),i=+e[r-1],o=n-r;return o?i+o*(e[r]-i):i};ia.median=function(e,n){var o,s=[],a=e.length,l=-1;if(1===arguments.length)for(;++l<a;)i(o=r(e[l]))&&s.push(o);else for(;++l<a;)i(o=r(n.call(e,e[l],l)))&&s.push(o);return s.length?ia.quantile(s.sort(t),.5):void 0};ia.variance=function(e,t){var n,o,s=e.length,a=0,l=0,u=-1,p=0;if(1===arguments.length){for(;++u<s;)if(i(n=r(e[u]))){o=n-a;a+=o/++p;l+=o*(n-a)}}else for(;++u<s;)if(i(n=r(t.call(e,e[u],u)))){o=n-a;a+=o/++p;l+=o*(n-a)}return p>1?l/(p-1):void 0};ia.deviation=function(){var e=ia.variance.apply(this,arguments);return e?Math.sqrt(e):e};var Ea=o(t);ia.bisectLeft=Ea.left;ia.bisect=ia.bisectRight=Ea.right;ia.bisector=function(e){return o(1===e.length?function(n,r){return t(e(n),r)}:e)};ia.shuffle=function(e,t,n){if((o=arguments.length)<3){n=e.length;2>o&&(t=0)}for(var r,i,o=n-t;o;){i=Math.random()*o--|0;r=e[o+t],e[o+t]=e[i+t],e[i+t]=r}return e};ia.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r};ia.pairs=function(e){for(var t,n=0,r=e.length-1,i=e[0],o=new Array(0>r?0:r);r>n;)o[n]=[t=i,i=e[++n]];return o};ia.zip=function(){if(!(r=arguments.length))return[];for(var e=-1,t=ia.min(arguments,s),n=new Array(t);++e<t;)for(var r,i=-1,o=n[e]=new Array(r);++i<r;)o[i]=arguments[i][e];return n};ia.transpose=function(e){return ia.zip.apply(ia,e)};ia.keys=function(e){var t=[];for(var n in e)t.push(n);return t};ia.values=function(e){var t=[];for(var n in e)t.push(e[n]);return t};ia.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t};ia.merge=function(e){for(var t,n,r,i=e.length,o=-1,s=0;++o<i;)s+=e[o].length;n=new Array(s);for(;--i>=0;){r=e[i];t=r.length;for(;--t>=0;)n[--s]=r[t]}return n};var va=Math.abs;ia.range=function(e,t,n){if(arguments.length<3){n=1;if(arguments.length<2){t=e;e=0}}if((t-e)/n===1/0)throw new Error("infinite range");var r,i=[],o=a(va(n)),s=-1;e*=o,t*=o,n*=o;if(0>n)for(;(r=e+n*++s)>t;)i.push(r/o);else for(;(r=e+n*++s)<t;)i.push(r/o);return i};ia.map=function(e,t){var n=new u;if(e instanceof u)e.forEach(function(e,t){n.set(e,t)});else if(Array.isArray(e)){var r,i=-1,o=e.length;if(1===arguments.length)for(;++i<o;)n.set(i,e[i]);else for(;++i<o;)n.set(t.call(e,r=e[i],i),r)}else for(var s in e)n.set(s,e[s]);return n};var xa="__proto__",ya="\x00";l(u,{has:d,get:function(e){return this._[p(e)]},set:function(e,t){return this._[p(e)]=t},remove:f,keys:h,values:function(){var e=[];for(var t in this._)e.push(this._[t]);return e},entries:function(){var e=[];for(var t in this._)e.push({key:c(t),value:this._[t]});return e},size:g,empty:m,forEach:function(e){for(var t in this._)e.call(this,c(t),this._[t])}});ia.nest=function(){function e(t,s,a){if(a>=o.length)return r?r.call(i,s):n?s.sort(n):s;for(var l,p,c,d,f=-1,h=s.length,g=o[a++],m=new u;++f<h;)(d=m.get(l=g(p=s[f])))?d.push(p):m.set(l,[p]);if(t){p=t();c=function(n,r){p.set(n,e(t,r,a))}}else{p={};c=function(n,r){p[n]=e(t,r,a)}}m.forEach(c);return p}function t(e,n){if(n>=o.length)return e;var r=[],i=s[n++];e.forEach(function(e,i){r.push({key:e,values:t(i,n)})});return i?r.sort(function(e,t){return i(e.key,t.key)}):r}var n,r,i={},o=[],s=[];i.map=function(t,n){return e(n,t,0)};i.entries=function(n){return t(e(ia.map,n,0),0)};i.key=function(e){o.push(e);return i};i.sortKeys=function(e){s[o.length-1]=e;return i};i.sortValues=function(e){n=e;return i};i.rollup=function(e){r=e;return i};return i};ia.set=function(e){var t=new E;if(e)for(var n=0,r=e.length;r>n;++n)t.add(e[n]);return t};l(E,{has:d,add:function(e){this._[p(e+="")]=!0;return e},remove:f,values:h,size:g,empty:m,forEach:function(e){for(var t in this._)e.call(this,c(t))}});ia.behavior={};ia.rebind=function(e,t){for(var n,r=1,i=arguments.length;++r<i;)e[n=arguments[r]]=v(e,t,t[n]);return e};var Na=["webkit","ms","moz","Moz","o","O"];ia.dispatch=function(){for(var e=new N,t=-1,n=arguments.length;++t<n;)e[arguments[t]]=I(e);return e};N.prototype.on=function(e,t){var n=e.indexOf("."),r="";if(n>=0){r=e.slice(n+1);e=e.slice(0,n)}if(e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}};ia.event=null;ia.requote=function(e){return e.replace(Ia,"\\$&")};var Ia=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,Aa={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]},Ta=function(e,t){return t.querySelector(e)},La=function(e,t){return t.querySelectorAll(e)},Sa=la.matches||la[x(la,"matchesSelector")],Ca=function(e,t){return Sa.call(e,t)};if("function"==typeof Sizzle){Ta=function(e,t){return Sizzle(e,t)[0]||null};La=Sizzle;Ca=Sizzle.matchesSelector}ia.selection=function(){return Oa};var ba=ia.selection.prototype=[];ba.select=function(e){var t,n,r,i,o=[];e=C(e);for(var s=-1,a=this.length;++s<a;){o.push(t=[]);t.parentNode=(r=this[s]).parentNode;for(var l=-1,u=r.length;++l<u;)if(i=r[l]){t.push(n=e.call(i,i.__data__,l,s));n&&"__data__"in i&&(n.__data__=i.__data__)}else t.push(null)}return S(o)};ba.selectAll=function(e){var t,n,r=[];e=b(e);for(var i=-1,o=this.length;++i<o;)for(var s=this[i],a=-1,l=s.length;++a<l;)if(n=s[a]){r.push(t=sa(e.call(n,n.__data__,a,i)));t.parentNode=n}return S(r)};var Ra={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};ia.ns={prefix:Ra,qualify:function(e){var t=e.indexOf(":"),n=e;if(t>=0){n=e.slice(0,t);e=e.slice(t+1)}return Ra.hasOwnProperty(n)?{space:Ra[n],local:e}:e}};ba.attr=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node();e=ia.ns.qualify(e);return e.local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(t in e)this.each(R(t,e[t]));return this}return this.each(R(e,t))};ba.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=_(e)).length,i=-1;if(t=n.classList){for(;++i<r;)if(!t.contains(e[i]))return!1}else{t=n.getAttribute("class");for(;++i<r;)if(!O(e[i]).test(t))return!1}return!0}for(t in e)this.each(F(t,e[t]));return this}return this.each(F(e,t))};ba.style=function(e,t,n){var r=arguments.length;if(3>r){if("string"!=typeof e){2>r&&(t="");for(n in e)this.each(M(n,e[n],t));return this}if(2>r)return ua.getComputedStyle(this.node(),null).getPropertyValue(e);n=""}return this.each(M(e,t,n))};ba.property=function(e,t){if(arguments.length<2){if("string"==typeof e)return this.node()[e];for(t in e)this.each(k(t,e[t]));return this}return this.each(k(e,t))};ba.text=function(e){return arguments.length?this.each("function"==typeof e?function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}:null==e?function(){this.textContent=""}:function(){this.textContent=e}):this.node().textContent};ba.html=function(e){return arguments.length?this.each("function"==typeof e?function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}:null==e?function(){this.innerHTML=""}:function(){this.innerHTML=e}):this.node().innerHTML};ba.append=function(e){e=D(e);return this.select(function(){return this.appendChild(e.apply(this,arguments))})};ba.insert=function(e,t){e=D(e);t=C(t);return this.select(function(){return this.insertBefore(e.apply(this,arguments),t.apply(this,arguments)||null)})};ba.remove=function(){return this.each(G)};ba.data=function(e,t){function n(e,n){var r,i,o,s=e.length,c=n.length,d=Math.min(s,c),f=new Array(c),h=new Array(c),g=new Array(s);if(t){var m,E=new u,v=new Array(s);for(r=-1;++r<s;){E.has(m=t.call(i=e[r],i.__data__,r))?g[r]=i:E.set(m,i);v[r]=m}for(r=-1;++r<c;){if(i=E.get(m=t.call(n,o=n[r],r))){if(i!==!0){f[r]=i;i.__data__=o}}else h[r]=U(o);E.set(m,!0)}for(r=-1;++r<s;)E.get(v[r])!==!0&&(g[r]=e[r])}else{for(r=-1;++r<d;){i=e[r];o=n[r];if(i){i.__data__=o;f[r]=i}else h[r]=U(o)}for(;c>r;++r)h[r]=U(n[r]);for(;s>r;++r)g[r]=e[r]}h.update=f;h.parentNode=f.parentNode=g.parentNode=e.parentNode;a.push(h);l.push(f);p.push(g)}var r,i,o=-1,s=this.length;if(!arguments.length){e=new Array(s=(r=this[0]).length);for(;++o<s;)(i=r[o])&&(e[o]=i.__data__);return e}var a=V([]),l=S([]),p=S([]);if("function"==typeof e)for(;++o<s;)n(r=this[o],e.call(r,r.parentNode.__data__,o));else for(;++o<s;)n(r=this[o],e);l.enter=function(){return a};l.exit=function(){return p};return l};ba.datum=function(e){return arguments.length?this.property("__data__",e):this.property("__data__")};ba.filter=function(e){var t,n,r,i=[];"function"!=typeof e&&(e=B(e));for(var o=0,s=this.length;s>o;o++){i.push(t=[]);t.parentNode=(n=this[o]).parentNode;for(var a=0,l=n.length;l>a;a++)(r=n[a])&&e.call(r,r.__data__,a,o)&&t.push(r)}return S(i)};ba.order=function(){for(var e=-1,t=this.length;++e<t;)for(var n,r=this[e],i=r.length-1,o=r[i];--i>=0;)if(n=r[i]){o&&o!==n.nextSibling&&o.parentNode.insertBefore(n,o);o=n}return this};ba.sort=function(e){e=j.apply(this,arguments);for(var t=-1,n=this.length;++t<n;)this[t].sort(e);return this.order()};ba.each=function(e){return q(this,function(t,n,r){e.call(t,t.__data__,n,r)})};ba.call=function(e){var t=sa(arguments);e.apply(t[0]=this,t);return this};ba.empty=function(){return!this.node()};ba.node=function(){for(var e=0,t=this.length;t>e;e++)for(var n=this[e],r=0,i=n.length;i>r;r++){var o=n[r];if(o)return o}return null};ba.size=function(){var e=0;q(this,function(){++e});return e};var wa=[];ia.selection.enter=V;ia.selection.enter.prototype=wa;wa.append=ba.append;wa.empty=ba.empty;wa.node=ba.node;wa.call=ba.call;wa.size=ba.size;wa.select=function(e){for(var t,n,r,i,o,s=[],a=-1,l=this.length;++a<l;){r=(i=this[a]).update;s.push(t=[]);t.parentNode=i.parentNode;for(var u=-1,p=i.length;++u<p;)if(o=i[u]){t.push(r[u]=n=e.call(i.parentNode,o.__data__,u,a));n.__data__=o.__data__}else t.push(null)}return S(s)};wa.insert=function(e,t){arguments.length<2&&(t=H(this));return ba.insert.call(this,e,t)};ia.select=function(e){var t=["string"==typeof e?Ta(e,aa):e];t.parentNode=la;return S([t])};ia.selectAll=function(e){var t=sa("string"==typeof e?La(e,aa):e);t.parentNode=la;return S([t])};var Oa=ia.select(la);ba.on=function(e,t,n){var r=arguments.length;if(3>r){if("string"!=typeof e){2>r&&(t=!1);for(n in e)this.each(z(n,e[n],t));return this}if(2>r)return(r=this.node()["__on"+e])&&r._;n=!1}return this.each(z(e,t,n))};var _a=ia.map({mouseenter:"mouseover",mouseleave:"mouseout"});_a.forEach(function(e){"on"+e in aa&&_a.remove(e)});var Fa="onselectstart"in aa?null:x(la.style,"userSelect"),Pa=0;ia.mouse=function(e){return K(e,T())};var Ma=/WebKit/.test(ua.navigator.userAgent)?-1:0;ia.touch=function(e,t,n){arguments.length<3&&(n=t,t=T().changedTouches);if(t)for(var r,i=0,o=t.length;o>i;++i)if((r=t[i]).identifier===n)return K(e,r)};ia.behavior.drag=function(){function e(){this.on("mousedown.drag",i).on("touchstart.drag",o)}function t(e,t,i,o,s){return function(){function a(){var e,n,r=t(d,g);if(r){e=r[0]-x[0];n=r[1]-x[1];h|=e|n;x=r;f({type:"drag",x:r[0]+u[0],y:r[1]+u[1],dx:e,dy:n})}}function l(){if(t(d,g)){E.on(o+m,null).on(s+m,null);v(h&&ia.event.target===c);f({type:"dragend"})}}var u,p=this,c=ia.event.target,d=p.parentNode,f=n.of(p,arguments),h=0,g=e(),m=".drag"+(null==g?"":"-"+g),E=ia.select(i()).on(o+m,a).on(s+m,l),v=Y(),x=t(d,g);if(r){u=r.apply(p,arguments);u=[u.x-x[0],u.y-x[1]]}else u=[0,0];f({type:"dragstart"})}}var n=L(e,"drag","dragstart","dragend"),r=null,i=t(y,ia.mouse,Z,"mousemove","mouseup"),o=t(Q,ia.touch,X,"touchmove","touchend");e.origin=function(t){if(!arguments.length)return r;r=t;return e};return ia.rebind(e,n,"on")};ia.touches=function(e,t){arguments.length<2&&(t=T().touches);return t?sa(t).map(function(t){var n=K(e,t);n.identifier=t.identifier;return n}):[]};var ka=1e-6,Da=ka*ka,Ga=Math.PI,Ua=2*Ga,Ba=Ua-ka,ja=Ga/2,qa=Ga/180,Va=180/Ga,Ha=Math.SQRT2,za=2,Wa=4;ia.interpolateZoom=function(e,t){function n(e){var t=e*v;if(E){var n=it(g),s=o/(za*d)*(n*ot(Ha*t+g)-rt(g));return[r+s*u,i+s*p,o*n/it(Ha*t+g)]}return[r+e*u,i+e*p,o*Math.exp(Ha*t)]}var r=e[0],i=e[1],o=e[2],s=t[0],a=t[1],l=t[2],u=s-r,p=a-i,c=u*u+p*p,d=Math.sqrt(c),f=(l*l-o*o+Wa*c)/(2*o*za*d),h=(l*l-o*o-Wa*c)/(2*l*za*d),g=Math.log(Math.sqrt(f*f+1)-f),m=Math.log(Math.sqrt(h*h+1)-h),E=m-g,v=(E||Math.log(l/o))/Ha;n.duration=1e3*v;return n};ia.behavior.zoom=function(){function e(e){e.on(w,p).on(Ka+".zoom",d).on("dblclick.zoom",f).on(F,c)}function t(e){return[(e[0]-T.x)/T.k,(e[1]-T.y)/T.k]}function n(e){return[e[0]*T.k+T.x,e[1]*T.k+T.y]}function r(e){T.k=Math.max(C[0],Math.min(C[1],e))}function i(e,t){t=n(t);T.x+=e[0]-t[0];T.y+=e[1]-t[1]}function o(t,n,o,s){t.__chart__={x:T.x,y:T.y,k:T.k};r(Math.pow(2,s));i(g=n,o);t=ia.select(t);b>0&&(t=t.transition().duration(b));t.call(e.event)}function s(){y&&y.domain(x.range().map(function(e){return(e-T.x)/T.k}).map(x.invert));I&&I.domain(N.range().map(function(e){return(e-T.y)/T.k}).map(N.invert))}function a(e){R++||e({type:"zoomstart"})}function l(e){s();e({type:"zoom",scale:T.k,translate:[T.x,T.y]})}function u(e){--R||e({type:"zoomend"});g=null}function p(){function e(){p=1;i(ia.mouse(r),d);l(s)}function n(){c.on(O,null).on(_,null);f(p&&ia.event.target===o);u(s)}var r=this,o=ia.event.target,s=P.of(r,arguments),p=0,c=ia.select(ua).on(O,e).on(_,n),d=t(ia.mouse(r)),f=Y();qu.call(r);a(s)}function c(){function e(){var e=ia.touches(h);f=T.k;e.forEach(function(e){e.identifier in m&&(m[e.identifier]=t(e))});return e}function n(){var t=ia.event.target;ia.select(t).on(y,s).on(N,d);I.push(t);for(var n=ia.event.changedTouches,r=0,i=n.length;i>r;++r)m[n[r].identifier]=null;var a=e(),l=Date.now();if(1===a.length){if(500>l-v){var u=a[0];o(h,u,m[u.identifier],Math.floor(Math.log(T.k)/Math.LN2)+1);A()}v=l}else if(a.length>1){var u=a[0],p=a[1],c=u[0]-p[0],f=u[1]-p[1];E=c*c+f*f}}function s(){var e,t,n,o,s=ia.touches(h);qu.call(h);for(var a=0,u=s.length;u>a;++a,o=null){n=s[a];if(o=m[n.identifier]){if(t)break;e=n,t=o}}if(o){var p=(p=n[0]-e[0])*p+(p=n[1]-e[1])*p,c=E&&Math.sqrt(p/E);e=[(e[0]+n[0])/2,(e[1]+n[1])/2];t=[(t[0]+o[0])/2,(t[1]+o[1])/2];r(c*f)}v=null;i(e,t);l(g)}function d(){if(ia.event.touches.length){for(var t=ia.event.changedTouches,n=0,r=t.length;r>n;++n)delete m[t[n].identifier];for(var i in m)return void e()}ia.selectAll(I).on(x,null);L.on(w,p).on(F,c);S();u(g)}var f,h=this,g=P.of(h,arguments),m={},E=0,x=".zoom-"+ia.event.changedTouches[0].identifier,y="touchmove"+x,N="touchend"+x,I=[],L=ia.select(h),S=Y();n();a(g);L.on(w,null).on(F,n)}function d(){var e=P.of(this,arguments);E?clearTimeout(E):(h=t(g=m||ia.mouse(this)),qu.call(this),a(e));E=setTimeout(function(){E=null;u(e)},50);A();r(Math.pow(2,.002*$a())*T.k);i(g,h);l(e)}function f(){var e=ia.mouse(this),n=Math.log(T.k)/Math.LN2;o(this,e,t(e),ia.event.shiftKey?Math.ceil(n)-1:Math.floor(n)+1)}var h,g,m,E,v,x,y,N,I,T={x:0,y:0,k:1},S=[960,500],C=Ya,b=250,R=0,w="mousedown.zoom",O="mousemove.zoom",_="mouseup.zoom",F="touchstart.zoom",P=L(e,"zoomstart","zoom","zoomend");e.event=function(e){e.each(function(){var e=P.of(this,arguments),t=T;if(Bu)ia.select(this).transition().each("start.zoom",function(){T=this.__chart__||{x:0,y:0,k:1};a(e)}).tween("zoom:zoom",function(){var n=S[0],r=S[1],i=g?g[0]:n/2,o=g?g[1]:r/2,s=ia.interpolateZoom([(i-T.x)/T.k,(o-T.y)/T.k,n/T.k],[(i-t.x)/t.k,(o-t.y)/t.k,n/t.k]);return function(t){var r=s(t),a=n/r[2];this.__chart__=T={x:i-r[0]*a,y:o-r[1]*a,k:a};l(e)}}).each("interrupt.zoom",function(){u(e)}).each("end.zoom",function(){u(e)});else{this.__chart__=T;a(e);l(e);u(e)}})};e.translate=function(t){if(!arguments.length)return[T.x,T.y];T={x:+t[0],y:+t[1],k:T.k};s();return e};e.scale=function(t){if(!arguments.length)return T.k;T={x:T.x,y:T.y,k:+t};s();return e};e.scaleExtent=function(t){if(!arguments.length)return C;C=null==t?Ya:[+t[0],+t[1]];return e};e.center=function(t){if(!arguments.length)return m;m=t&&[+t[0],+t[1]];return e};e.size=function(t){if(!arguments.length)return S;S=t&&[+t[0],+t[1]];return e};e.duration=function(t){if(!arguments.length)return b;b=+t;return e};e.x=function(t){if(!arguments.length)return y;y=t;x=t.copy();T={x:0,y:0,k:1};return e};e.y=function(t){if(!arguments.length)return I;I=t;N=t.copy();T={x:0,y:0,k:1};return e};return ia.rebind(e,P,"on")};var $a,Ya=[0,1/0],Ka="onwheel"in aa?($a=function(){return-ia.event.deltaY*(ia.event.deltaMode?120:1)},"wheel"):"onmousewheel"in aa?($a=function(){return ia.event.wheelDelta},"mousewheel"):($a=function(){return-ia.event.detail},"MozMousePixelScroll");ia.color=at;at.prototype.toString=function(){return this.rgb()+""};ia.hsl=lt;var Qa=lt.prototype=new at;Qa.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);return new lt(this.h,this.s,this.l/e)};Qa.darker=function(e){e=Math.pow(.7,arguments.length?e:1);return new lt(this.h,this.s,e*this.l)};Qa.rgb=function(){return ut(this.h,this.s,this.l)};ia.hcl=pt;var Xa=pt.prototype=new at;Xa.brighter=function(e){return new pt(this.h,this.c,Math.min(100,this.l+Za*(arguments.length?e:1)))};Xa.darker=function(e){return new pt(this.h,this.c,Math.max(0,this.l-Za*(arguments.length?e:1)))};Xa.rgb=function(){return ct(this.h,this.c,this.l).rgb()};ia.lab=dt;var Za=18,Ja=.95047,el=1,tl=1.08883,nl=dt.prototype=new at;nl.brighter=function(e){return new dt(Math.min(100,this.l+Za*(arguments.length?e:1)),this.a,this.b)};nl.darker=function(e){return new dt(Math.max(0,this.l-Za*(arguments.length?e:1)),this.a,this.b)};nl.rgb=function(){return ft(this.l,this.a,this.b)};ia.rgb=vt;var rl=vt.prototype=new at;rl.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,i=30;if(!t&&!n&&!r)return new vt(i,i,i);t&&i>t&&(t=i);n&&i>n&&(n=i);r&&i>r&&(r=i);return new vt(Math.min(255,t/e),Math.min(255,n/e),Math.min(255,r/e))};rl.darker=function(e){e=Math.pow(.7,arguments.length?e:1);return new vt(e*this.r,e*this.g,e*this.b)};rl.hsl=function(){return At(this.r,this.g,this.b)};rl.toString=function(){return"#"+Nt(this.r)+Nt(this.g)+Nt(this.b)};var il=ia.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});il.forEach(function(e,t){il.set(e,xt(t))});ia.functor=Ct;ia.xhr=Rt(bt);ia.dsv=function(e,t){function n(e,n,o){arguments.length<3&&(o=n,n=null);var s=wt(e,t,null==n?r:i(n),o);s.row=function(e){return arguments.length?s.response(null==(n=e)?r:i(e)):n};return s}function r(e){return n.parse(e.responseText)}function i(e){return function(t){return n.parse(t.responseText,e)}}function o(t){return t.map(s).join(e)}function s(e){return a.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}var a=new RegExp('["'+e+"\n]"),l=e.charCodeAt(0);n.parse=function(e,t){var r;return n.parseRows(e,function(e,n){if(r)return r(e,n-1);var i=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");r=t?function(e,n){return t(i(e),n)}:i})};n.parseRows=function(e,t){function n(){if(p>=u)return s;if(i)return i=!1,o;var t=p;if(34===e.charCodeAt(t)){for(var n=t;n++<u;)if(34===e.charCodeAt(n)){if(34!==e.charCodeAt(n+1))break;++n}p=n+2;var r=e.charCodeAt(n+1);if(13===r){i=!0;10===e.charCodeAt(n+2)&&++p}else 10===r&&(i=!0);return e.slice(t+1,n).replace(/""/g,'"')}for(;u>p;){var r=e.charCodeAt(p++),a=1;if(10===r)i=!0;else if(13===r){i=!0;10===e.charCodeAt(p)&&(++p,++a)}else if(r!==l)continue;return e.slice(t,p-a)}return e.slice(t)}for(var r,i,o={},s={},a=[],u=e.length,p=0,c=0;(r=n())!==s;){for(var d=[];r!==o&&r!==s;){d.push(r);r=n()}t&&null==(d=t(d,c++))||a.push(d)}return a};n.format=function(t){if(Array.isArray(t[0]))return n.formatRows(t);var r=new E,i=[];t.forEach(function(e){for(var t in e)r.has(t)||i.push(r.add(t))});return[i.map(s).join(e)].concat(t.map(function(t){return i.map(function(e){return s(t[e])}).join(e)})).join("\n")};n.formatRows=function(e){return e.map(o).join("\n")};return n};ia.csv=ia.dsv(",","text/csv");ia.tsv=ia.dsv(" ","text/tab-separated-values");var ol,sl,al,ll,ul,pl=ua[x(ua,"requestAnimationFrame")]||function(e){setTimeout(e,17)};ia.timer=function(e,t,n){var r=arguments.length;2>r&&(t=0);
3>r&&(n=Date.now());var i=n+t,o={c:e,t:i,f:!1,n:null};sl?sl.n=o:ol=o;sl=o;if(!al){ll=clearTimeout(ll);al=1;pl(Ft)}};ia.timer.flush=function(){Pt();Mt()};ia.round=function(e,t){return t?Math.round(e*(t=Math.pow(10,t)))/t:Math.round(e)};var cl=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"].map(Dt);ia.formatPrefix=function(e,t){var n=0;if(e){0>e&&(e*=-1);t&&(e=ia.round(e,kt(e,t)));n=1+Math.floor(1e-12+Math.log(e)/Math.LN10);n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))}return cl[8+n/3]};var dl=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,fl=ia.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,t){return(e=ia.round(e,kt(e,t))).toFixed(Math.max(0,Math.min(20,kt(e*(1+1e-15),t))))}}),hl=ia.time={},gl=Date;Bt.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ml.setUTCDate.apply(this._,arguments)},setDay:function(){ml.setUTCDay.apply(this._,arguments)},setFullYear:function(){ml.setUTCFullYear.apply(this._,arguments)},setHours:function(){ml.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ml.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ml.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ml.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ml.setUTCSeconds.apply(this._,arguments)},setTime:function(){ml.setTime.apply(this._,arguments)}};var ml=Date.prototype;hl.year=jt(function(e){e=hl.day(e);e.setMonth(0,1);return e},function(e,t){e.setFullYear(e.getFullYear()+t)},function(e){return e.getFullYear()});hl.years=hl.year.range;hl.years.utc=hl.year.utc.range;hl.day=jt(function(e){var t=new gl(2e3,0);t.setFullYear(e.getFullYear(),e.getMonth(),e.getDate());return t},function(e,t){e.setDate(e.getDate()+t)},function(e){return e.getDate()-1});hl.days=hl.day.range;hl.days.utc=hl.day.utc.range;hl.dayOfYear=function(e){var t=hl.year(e);return Math.floor((e-t-6e4*(e.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)};["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(e,t){t=7-t;var n=hl[e]=jt(function(e){(e=hl.day(e)).setDate(e.getDate()-(e.getDay()+t)%7);return e},function(e,t){e.setDate(e.getDate()+7*Math.floor(t))},function(e){var n=hl.year(e).getDay();return Math.floor((hl.dayOfYear(e)+(n+t)%7)/7)-(n!==t)});hl[e+"s"]=n.range;hl[e+"s"].utc=n.utc.range;hl[e+"OfYear"]=function(e){var n=hl.year(e).getDay();return Math.floor((hl.dayOfYear(e)+(n+t)%7)/7)}});hl.week=hl.sunday;hl.weeks=hl.sunday.range;hl.weeks.utc=hl.sunday.utc.range;hl.weekOfYear=hl.sundayOfYear;var El={"-":"",_:" ",0:"0"},vl=/^\s*\d+/,xl=/^%/;ia.locale=function(e){return{numberFormat:Gt(e),timeFormat:Vt(e)}};var yl=ia.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});ia.format=yl.numberFormat;ia.geo={};cn.prototype={s:0,t:0,add:function(e){dn(e,this.t,Nl);dn(Nl.s,this.s,this);this.s?this.t+=Nl.t:this.s=Nl.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var Nl=new cn;ia.geo.stream=function(e,t){e&&Il.hasOwnProperty(e.type)?Il[e.type](e,t):fn(e,t)};var Il={Feature:function(e,t){fn(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,i=n.length;++r<i;)fn(n[r].geometry,t)}},Al={Sphere:function(e,t){t.sphere()},Point:function(e,t){e=e.coordinates;t.point(e[0],e[1],e[2])},MultiPoint:function(e,t){for(var n=e.coordinates,r=-1,i=n.length;++r<i;)e=n[r],t.point(e[0],e[1],e[2])},LineString:function(e,t){hn(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,i=n.length;++r<i;)hn(n[r],t,0)},Polygon:function(e,t){gn(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,i=n.length;++r<i;)gn(n[r],t)},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,i=n.length;++r<i;)fn(n[r],t)}};ia.geo.area=function(e){Tl=0;ia.geo.stream(e,Sl);return Tl};var Tl,Ll=new cn,Sl={sphere:function(){Tl+=4*Ga},point:y,lineStart:y,lineEnd:y,polygonStart:function(){Ll.reset();Sl.lineStart=mn},polygonEnd:function(){var e=2*Ll;Tl+=0>e?4*Ga+e:e;Sl.lineStart=Sl.lineEnd=Sl.point=y}};ia.geo.bounds=function(){function e(e,t){x.push(y=[p=e,d=e]);c>t&&(c=t);t>f&&(f=t)}function t(t,n){var r=En([t*qa,n*qa]);if(E){var i=xn(E,r),o=[i[1],-i[0],0],s=xn(o,i);In(s);s=An(s);var l=t-h,u=l>0?1:-1,g=s[0]*Va*u,m=va(l)>180;if(m^(g>u*h&&u*t>g)){var v=s[1]*Va;v>f&&(f=v)}else if(g=(g+360)%360-180,m^(g>u*h&&u*t>g)){var v=-s[1]*Va;c>v&&(c=v)}else{c>n&&(c=n);n>f&&(f=n)}if(m)h>t?a(p,t)>a(p,d)&&(d=t):a(t,d)>a(p,d)&&(p=t);else if(d>=p){p>t&&(p=t);t>d&&(d=t)}else t>h?a(p,t)>a(p,d)&&(d=t):a(t,d)>a(p,d)&&(p=t)}else e(t,n);E=r,h=t}function n(){N.point=t}function r(){y[0]=p,y[1]=d;N.point=e;E=null}function i(e,n){if(E){var r=e-h;v+=va(r)>180?r+(r>0?360:-360):r}else g=e,m=n;Sl.point(e,n);t(e,n)}function o(){Sl.lineStart()}function s(){i(g,m);Sl.lineEnd();va(v)>ka&&(p=-(d=180));y[0]=p,y[1]=d;E=null}function a(e,t){return(t-=e)<0?t+360:t}function l(e,t){return e[0]-t[0]}function u(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e<t[0]||t[1]<e}var p,c,d,f,h,g,m,E,v,x,y,N={point:e,lineStart:n,lineEnd:r,polygonStart:function(){N.point=i;N.lineStart=o;N.lineEnd=s;v=0;Sl.polygonStart()},polygonEnd:function(){Sl.polygonEnd();N.point=e;N.lineStart=n;N.lineEnd=r;0>Ll?(p=-(d=180),c=-(f=90)):v>ka?f=90:-ka>v&&(c=-90);y[0]=p,y[1]=d}};return function(e){f=d=-(p=c=1/0);x=[];ia.geo.stream(e,N);var t=x.length;if(t){x.sort(l);for(var n,r=1,i=x[0],o=[i];t>r;++r){n=x[r];if(u(n[0],i)||u(n[1],i)){a(i[0],n[1])>a(i[0],i[1])&&(i[1]=n[1]);a(n[0],i[1])>a(i[0],i[1])&&(i[0]=n[0])}else o.push(i=n)}for(var s,n,h=-1/0,t=o.length-1,r=0,i=o[t];t>=r;i=n,++r){n=o[r];(s=a(i[1],n[0]))>h&&(h=s,p=n[0],d=i[1])}}x=y=null;return 1/0===p||1/0===c?[[0/0,0/0],[0/0,0/0]]:[[p,c],[d,f]]}}();ia.geo.centroid=function(e){Cl=bl=Rl=wl=Ol=_l=Fl=Pl=Ml=kl=Dl=0;ia.geo.stream(e,Gl);var t=Ml,n=kl,r=Dl,i=t*t+n*n+r*r;if(Da>i){t=_l,n=Fl,r=Pl;ka>bl&&(t=Rl,n=wl,r=Ol);i=t*t+n*n+r*r;if(Da>i)return[0/0,0/0]}return[Math.atan2(n,t)*Va,nt(r/Math.sqrt(i))*Va]};var Cl,bl,Rl,wl,Ol,_l,Fl,Pl,Ml,kl,Dl,Gl={sphere:y,point:Ln,lineStart:Cn,lineEnd:bn,polygonStart:function(){Gl.lineStart=Rn},polygonEnd:function(){Gl.lineStart=Cn}},Ul=Mn(On,Un,jn,[-Ga,-Ga/2]),Bl=1e9;ia.geo.clipExtent=function(){var e,t,n,r,i,o,s={stream:function(e){i&&(i.valid=!1);i=o(e);i.valid=!0;return i},extent:function(a){if(!arguments.length)return[[e,t],[n,r]];o=zn(e=+a[0][0],t=+a[0][1],n=+a[1][0],r=+a[1][1]);i&&(i.valid=!1,i=null);return s}};return s.extent([[0,0],[960,500]])};(ia.geo.conicEqualArea=function(){return Wn($n)}).raw=$n;ia.geo.albers=function(){return ia.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)};ia.geo.albersUsa=function(){function e(e){var o=e[0],s=e[1];t=null;(n(o,s),t)||(r(o,s),t)||i(o,s);return t}var t,n,r,i,o=ia.geo.albers(),s=ia.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=ia.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(e,n){t=[e,n]}};e.invert=function(e){var t=o.scale(),n=o.translate(),r=(e[0]-n[0])/t,i=(e[1]-n[1])/t;return(i>=.12&&.234>i&&r>=-.425&&-.214>r?s:i>=.166&&.234>i&&r>=-.214&&-.115>r?a:o).invert(e)};e.stream=function(e){var t=o.stream(e),n=s.stream(e),r=a.stream(e);return{point:function(e,i){t.point(e,i);n.point(e,i);r.point(e,i)},sphere:function(){t.sphere();n.sphere();r.sphere()},lineStart:function(){t.lineStart();n.lineStart();r.lineStart()},lineEnd:function(){t.lineEnd();n.lineEnd();r.lineEnd()},polygonStart:function(){t.polygonStart();n.polygonStart();r.polygonStart()},polygonEnd:function(){t.polygonEnd();n.polygonEnd();r.polygonEnd()}}};e.precision=function(t){if(!arguments.length)return o.precision();o.precision(t);s.precision(t);a.precision(t);return e};e.scale=function(t){if(!arguments.length)return o.scale();o.scale(t);s.scale(.35*t);a.scale(t);return e.translate(o.translate())};e.translate=function(t){if(!arguments.length)return o.translate();var u=o.scale(),p=+t[0],c=+t[1];n=o.translate(t).clipExtent([[p-.455*u,c-.238*u],[p+.455*u,c+.238*u]]).stream(l).point;r=s.translate([p-.307*u,c+.201*u]).clipExtent([[p-.425*u+ka,c+.12*u+ka],[p-.214*u-ka,c+.234*u-ka]]).stream(l).point;i=a.translate([p-.205*u,c+.212*u]).clipExtent([[p-.214*u+ka,c+.166*u+ka],[p-.115*u-ka,c+.234*u-ka]]).stream(l).point;return e};return e.scale(1070)};var jl,ql,Vl,Hl,zl,Wl,$l={point:y,lineStart:y,lineEnd:y,polygonStart:function(){ql=0;$l.lineStart=Yn},polygonEnd:function(){$l.lineStart=$l.lineEnd=$l.point=y;jl+=va(ql/2)}},Yl={point:Kn,lineStart:y,lineEnd:y,polygonStart:y,polygonEnd:y},Kl={point:Zn,lineStart:Jn,lineEnd:er,polygonStart:function(){Kl.lineStart=tr},polygonEnd:function(){Kl.point=Zn;Kl.lineStart=Jn;Kl.lineEnd=er}};ia.geo.path=function(){function e(e){if(e){"function"==typeof a&&o.pointRadius(+a.apply(this,arguments));s&&s.valid||(s=i(o));ia.geo.stream(e,s)}return o.result()}function t(){s=null;return e}var n,r,i,o,s,a=4.5;e.area=function(e){jl=0;ia.geo.stream(e,i($l));return jl};e.centroid=function(e){Rl=wl=Ol=_l=Fl=Pl=Ml=kl=Dl=0;ia.geo.stream(e,i(Kl));return Dl?[Ml/Dl,kl/Dl]:Pl?[_l/Pl,Fl/Pl]:Ol?[Rl/Ol,wl/Ol]:[0/0,0/0]};e.bounds=function(e){zl=Wl=-(Vl=Hl=1/0);ia.geo.stream(e,i(Yl));return[[Vl,Hl],[zl,Wl]]};e.projection=function(e){if(!arguments.length)return n;i=(n=e)?e.stream||ir(e):bt;return t()};e.context=function(e){if(!arguments.length)return r;o=null==(r=e)?new Qn:new nr(e);"function"!=typeof a&&o.pointRadius(a);return t()};e.pointRadius=function(t){if(!arguments.length)return a;a="function"==typeof t?t:(o.pointRadius(+t),+t);return e};return e.projection(ia.geo.albersUsa()).context(null)};ia.geo.transform=function(e){return{stream:function(t){var n=new or(t);for(var r in e)n[r]=e[r];return n}}};or.prototype={point:function(e,t){this.stream.point(e,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};ia.geo.projection=ar;ia.geo.projectionMutator=lr;(ia.geo.equirectangular=function(){return ar(pr)}).raw=pr.invert=pr;ia.geo.rotation=function(e){function t(t){t=e(t[0]*qa,t[1]*qa);return t[0]*=Va,t[1]*=Va,t}e=dr(e[0]%360*qa,e[1]*qa,e.length>2?e[2]*qa:0);t.invert=function(t){t=e.invert(t[0]*qa,t[1]*qa);return t[0]*=Va,t[1]*=Va,t};return t};cr.invert=pr;ia.geo.circle=function(){function e(){var e="function"==typeof r?r.apply(this,arguments):r,t=dr(-e[0]*qa,-e[1]*qa,0).invert,i=[];n(null,null,1,{point:function(e,n){i.push(e=t(e,n));e[0]*=Va,e[1]*=Va}});return{type:"Polygon",coordinates:[i]}}var t,n,r=[0,0],i=6;e.origin=function(t){if(!arguments.length)return r;r=t;return e};e.angle=function(r){if(!arguments.length)return t;n=mr((t=+r)*qa,i*qa);return e};e.precision=function(r){if(!arguments.length)return i;n=mr(t*qa,(i=+r)*qa);return e};return e.angle(90)};ia.geo.distance=function(e,t){var n,r=(t[0]-e[0])*qa,i=e[1]*qa,o=t[1]*qa,s=Math.sin(r),a=Math.cos(r),l=Math.sin(i),u=Math.cos(i),p=Math.sin(o),c=Math.cos(o);return Math.atan2(Math.sqrt((n=c*s)*n+(n=u*p-l*c*a)*n),l*p+u*c*a)};ia.geo.graticule=function(){function e(){return{type:"MultiLineString",coordinates:t()}}function t(){return ia.range(Math.ceil(o/m)*m,i,m).map(d).concat(ia.range(Math.ceil(u/E)*E,l,E).map(f)).concat(ia.range(Math.ceil(r/h)*h,n,h).filter(function(e){return va(e%m)>ka}).map(p)).concat(ia.range(Math.ceil(a/g)*g,s,g).filter(function(e){return va(e%E)>ka}).map(c))}var n,r,i,o,s,a,l,u,p,c,d,f,h=10,g=h,m=90,E=360,v=2.5;e.lines=function(){return t().map(function(e){return{type:"LineString",coordinates:e}})};e.outline=function(){return{type:"Polygon",coordinates:[d(o).concat(f(l).slice(1),d(i).reverse().slice(1),f(u).reverse().slice(1))]}};e.extent=function(t){return arguments.length?e.majorExtent(t).minorExtent(t):e.minorExtent()};e.majorExtent=function(t){if(!arguments.length)return[[o,u],[i,l]];o=+t[0][0],i=+t[1][0];u=+t[0][1],l=+t[1][1];o>i&&(t=o,o=i,i=t);u>l&&(t=u,u=l,l=t);return e.precision(v)};e.minorExtent=function(t){if(!arguments.length)return[[r,a],[n,s]];r=+t[0][0],n=+t[1][0];a=+t[0][1],s=+t[1][1];r>n&&(t=r,r=n,n=t);a>s&&(t=a,a=s,s=t);return e.precision(v)};e.step=function(t){return arguments.length?e.majorStep(t).minorStep(t):e.minorStep()};e.majorStep=function(t){if(!arguments.length)return[m,E];m=+t[0],E=+t[1];return e};e.minorStep=function(t){if(!arguments.length)return[h,g];h=+t[0],g=+t[1];return e};e.precision=function(t){if(!arguments.length)return v;v=+t;p=vr(a,s,90);c=xr(r,n,v);d=vr(u,l,90);f=xr(o,i,v);return e};return e.majorExtent([[-180,-90+ka],[180,90-ka]]).minorExtent([[-180,-80-ka],[180,80+ka]])};ia.geo.greatArc=function(){function e(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),n||i.apply(this,arguments)]}}var t,n,r=yr,i=Nr;e.distance=function(){return ia.geo.distance(t||r.apply(this,arguments),n||i.apply(this,arguments))};e.source=function(n){if(!arguments.length)return r;r=n,t="function"==typeof n?null:n;return e};e.target=function(t){if(!arguments.length)return i;i=t,n="function"==typeof t?null:t;return e};e.precision=function(){return arguments.length?e:0};return e};ia.geo.interpolate=function(e,t){return Ir(e[0]*qa,e[1]*qa,t[0]*qa,t[1]*qa)};ia.geo.length=function(e){Ql=0;ia.geo.stream(e,Xl);return Ql};var Ql,Xl={sphere:y,point:y,lineStart:Ar,lineEnd:y,polygonStart:y,polygonEnd:y},Zl=Tr(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(ia.geo.azimuthalEqualArea=function(){return ar(Zl)}).raw=Zl;var Jl=Tr(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},bt);(ia.geo.azimuthalEquidistant=function(){return ar(Jl)}).raw=Jl;(ia.geo.conicConformal=function(){return Wn(Lr)}).raw=Lr;(ia.geo.conicEquidistant=function(){return Wn(Sr)}).raw=Sr;var eu=Tr(function(e){return 1/e},Math.atan);(ia.geo.gnomonic=function(){return ar(eu)}).raw=eu;Cr.invert=function(e,t){return[e,2*Math.atan(Math.exp(t))-ja]};(ia.geo.mercator=function(){return br(Cr)}).raw=Cr;var tu=Tr(function(){return 1},Math.asin);(ia.geo.orthographic=function(){return ar(tu)}).raw=tu;var nu=Tr(function(e){return 1/(1+e)},function(e){return 2*Math.atan(e)});(ia.geo.stereographic=function(){return ar(nu)}).raw=nu;Rr.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-ja]};(ia.geo.transverseMercator=function(){var e=br(Rr),t=e.center,n=e.rotate;e.center=function(e){return e?t([-e[1],e[0]]):(e=t(),[e[1],-e[0]])};e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):(e=n(),[e[0],e[1],e[2]-90])};return n([0,0,90])}).raw=Rr;ia.geom={};ia.geom.hull=function(e){function t(e){if(e.length<3)return[];var t,i=Ct(n),o=Ct(r),s=e.length,a=[],l=[];for(t=0;s>t;t++)a.push([+i.call(this,e[t],t),+o.call(this,e[t],t),t]);a.sort(Fr);for(t=0;s>t;t++)l.push([a[t][0],-a[t][1]]);var u=_r(a),p=_r(l),c=p[0]===u[0],d=p[p.length-1]===u[u.length-1],f=[];for(t=u.length-1;t>=0;--t)f.push(e[a[u[t]][2]]);for(t=+c;t<p.length-d;++t)f.push(e[a[p[t]][2]]);return f}var n=wr,r=Or;if(arguments.length)return t(e);t.x=function(e){return arguments.length?(n=e,t):n};t.y=function(e){return arguments.length?(r=e,t):r};return t};ia.geom.polygon=function(e){Aa(e,ru);return e};var ru=ia.geom.polygon.prototype=[];ru.area=function(){for(var e,t=-1,n=this.length,r=this[n-1],i=0;++t<n;){e=r;r=this[t];i+=e[1]*r[0]-e[0]*r[1]}return.5*i};ru.centroid=function(e){var t,n,r=-1,i=this.length,o=0,s=0,a=this[i-1];arguments.length||(e=-1/(6*this.area()));for(;++r<i;){t=a;a=this[r];n=t[0]*a[1]-a[0]*t[1];o+=(t[0]+a[0])*n;s+=(t[1]+a[1])*n}return[o*e,s*e]};ru.clip=function(e){for(var t,n,r,i,o,s,a=kr(e),l=-1,u=this.length-kr(this),p=this[u-1];++l<u;){t=e.slice();e.length=0;i=this[l];o=t[(r=t.length-a)-1];n=-1;for(;++n<r;){s=t[n];if(Pr(s,p,i)){Pr(o,p,i)||e.push(Mr(o,s,p,i));e.push(s)}else Pr(o,p,i)&&e.push(Mr(o,s,p,i));o=s}a&&e.push(e[0]);p=i}return e};var iu,ou,su,au,lu,uu=[],pu=[];Hr.prototype.prepare=function(){for(var e,t=this.edges,n=t.length;n--;){e=t[n].edge;e.b&&e.a||t.splice(n,1)}t.sort(Wr);return t.length};ni.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}};ri.prototype={insert:function(e,t){var n,r,i;if(e){t.P=e;t.N=e.N;e.N&&(e.N.P=t);e.N=t;if(e.R){e=e.R;for(;e.L;)e=e.L;e.L=t}else e.R=t;n=e}else if(this._){e=ai(this._);t.P=null;t.N=e;e.P=e.L=t;n=e}else{t.P=t.N=null;this._=t;n=null}t.L=t.R=null;t.U=n;t.C=!0;e=t;for(;n&&n.C;){r=n.U;if(n===r.L){i=r.R;if(i&&i.C){n.C=i.C=!1;r.C=!0;e=r}else{if(e===n.R){oi(this,n);e=n;n=e.U}n.C=!1;r.C=!0;si(this,r)}}else{i=r.L;if(i&&i.C){n.C=i.C=!1;r.C=!0;e=r}else{if(e===n.L){si(this,n);e=n;n=e.U}n.C=!1;r.C=!0;oi(this,r)}}n=e.U}this._.C=!1},remove:function(e){e.N&&(e.N.P=e.P);e.P&&(e.P.N=e.N);e.N=e.P=null;var t,n,r,i=e.U,o=e.L,s=e.R;n=o?s?ai(s):o:s;i?i.L===e?i.L=n:i.R=n:this._=n;if(o&&s){r=n.C;n.C=e.C;n.L=o;o.U=n;if(n!==s){i=n.U;n.U=e.U;e=n.R;i.L=e;n.R=s;s.U=n}else{n.U=i;i=n;e=n.R}}else{r=e.C;e=n}e&&(e.U=i);if(!r)if(e&&e.C)e.C=!1;else{do{if(e===this._)break;if(e===i.L){t=i.R;if(t.C){t.C=!1;i.C=!0;oi(this,i);t=i.R}if(t.L&&t.L.C||t.R&&t.R.C){if(!t.R||!t.R.C){t.L.C=!1;t.C=!0;si(this,t);t=i.R}t.C=i.C;i.C=t.R.C=!1;oi(this,i);e=this._;break}}else{t=i.L;if(t.C){t.C=!1;i.C=!0;si(this,i);t=i.L}if(t.L&&t.L.C||t.R&&t.R.C){if(!t.L||!t.L.C){t.R.C=!1;t.C=!0;oi(this,t);t=i.L}t.C=i.C;i.C=t.L.C=!1;si(this,i);e=this._;break}}t.C=!0;e=i;i=i.U}while(!e.C);e&&(e.C=!1)}}};ia.geom.voronoi=function(e){function t(e){var t=new Array(e.length),r=a[0][0],i=a[0][1],o=a[1][0],s=a[1][1];li(n(e),a).cells.forEach(function(n,a){var l=n.edges,u=n.site,p=t[a]=l.length?l.map(function(e){var t=e.start();return[t.x,t.y]}):u.x>=r&&u.x<=o&&u.y>=i&&u.y<=s?[[r,s],[o,s],[o,i],[r,i]]:[];p.point=e[a]});return t}function n(e){return e.map(function(e,t){return{x:Math.round(o(e,t)/ka)*ka,y:Math.round(s(e,t)/ka)*ka,i:t}})}var r=wr,i=Or,o=r,s=i,a=cu;if(e)return t(e);t.links=function(e){return li(n(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})};t.triangles=function(e){var t=[];li(n(e)).cells.forEach(function(n,r){for(var i,o,s=n.site,a=n.edges.sort(Wr),l=-1,u=a.length,p=a[u-1].edge,c=p.l===s?p.r:p.l;++l<u;){i=p;o=c;p=a[l].edge;c=p.l===s?p.r:p.l;r<o.i&&r<c.i&&pi(s,o,c)<0&&t.push([e[r],e[o.i],e[c.i]])}});return t};t.x=function(e){return arguments.length?(o=Ct(r=e),t):r};t.y=function(e){return arguments.length?(s=Ct(i=e),t):i};t.clipExtent=function(e){if(!arguments.length)return a===cu?null:a;a=null==e?cu:e;return t};t.size=function(e){return arguments.length?t.clipExtent(e&&[[0,0],e]):a===cu?null:a&&a[1]};return t};var cu=[[-1e6,-1e6],[1e6,1e6]];ia.geom.delaunay=function(e){return ia.geom.voronoi().triangles(e)};ia.geom.quadtree=function(e,t,n,r,i){function o(e){function o(e,t,n,r,i,o,s,a){if(!isNaN(n)&&!isNaN(r))if(e.leaf){var l=e.x,p=e.y;if(null!=l)if(va(l-n)+va(p-r)<.01)u(e,t,n,r,i,o,s,a);else{var c=e.point;e.x=e.y=e.point=null;u(e,c,l,p,i,o,s,a);u(e,t,n,r,i,o,s,a)}else e.x=n,e.y=r,e.point=t}else u(e,t,n,r,i,o,s,a)}function u(e,t,n,r,i,s,a,l){var u=.5*(i+a),p=.5*(s+l),c=n>=u,d=r>=p,f=d<<1|c;e.leaf=!1;e=e.nodes[f]||(e.nodes[f]=fi());c?i=u:a=u;d?s=p:l=p;o(e,t,n,r,i,s,a,l)}var p,c,d,f,h,g,m,E,v,x=Ct(a),y=Ct(l);if(null!=t)g=t,m=n,E=r,v=i;else{E=v=-(g=m=1/0);c=[],d=[];h=e.length;if(s)for(f=0;h>f;++f){p=e[f];p.x<g&&(g=p.x);p.y<m&&(m=p.y);p.x>E&&(E=p.x);p.y>v&&(v=p.y);c.push(p.x);d.push(p.y)}else for(f=0;h>f;++f){var N=+x(p=e[f],f),I=+y(p,f);g>N&&(g=N);m>I&&(m=I);N>E&&(E=N);I>v&&(v=I);c.push(N);d.push(I)}}var A=E-g,T=v-m;A>T?v=m+A:E=g+T;var L=fi();L.add=function(e){o(L,e,+x(e,++f),+y(e,f),g,m,E,v)};L.visit=function(e){hi(e,L,g,m,E,v)};L.find=function(e){return gi(L,e[0],e[1],g,m,E,v)};f=-1;if(null==t){for(;++f<h;)o(L,e[f],c[f],d[f],g,m,E,v);--f}else e.forEach(L.add);c=d=e=p=null;return L}var s,a=wr,l=Or;if(s=arguments.length){a=ci;l=di;if(3===s){i=n;r=t;n=t=0}return o(e)}o.x=function(e){return arguments.length?(a=e,o):a};o.y=function(e){return arguments.length?(l=e,o):l};o.extent=function(e){if(!arguments.length)return null==t?null:[[t,n],[r,i]];null==e?t=n=r=i=null:(t=+e[0][0],n=+e[0][1],r=+e[1][0],i=+e[1][1]);return o};o.size=function(e){if(!arguments.length)return null==t?null:[r-t,i-n];null==e?t=n=r=i=null:(t=n=0,r=+e[0],i=+e[1]);return o};return o};ia.interpolateRgb=mi;ia.interpolateObject=Ei;ia.interpolateNumber=vi;ia.interpolateString=xi;var du=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,fu=new RegExp(du.source,"g");ia.interpolate=yi;ia.interpolators=[function(e,t){var n=typeof t;return("string"===n?il.has(t)||/^(#|rgb\(|hsl\()/.test(t)?mi:xi:t instanceof at?mi:Array.isArray(t)?Ni:"object"===n&&isNaN(t)?Ei:vi)(e,t)}];ia.interpolateArray=Ni;var hu=function(){return bt},gu=ia.map({linear:hu,poly:bi,quad:function(){return Li},cubic:function(){return Si},sin:function(){return Ri},exp:function(){return wi},circle:function(){return Oi},elastic:_i,back:Fi,bounce:function(){return Pi}}),mu=ia.map({"in":bt,out:Ai,"in-out":Ti,"out-in":function(e){return Ti(Ai(e))}});ia.ease=function(e){var t=e.indexOf("-"),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):"in";n=gu.get(n)||hu;r=mu.get(r)||bt;return Ii(r(n.apply(null,oa.call(arguments,1))))};ia.interpolateHcl=Mi;ia.interpolateHsl=ki;ia.interpolateLab=Di;ia.interpolateRound=Gi;ia.transform=function(e){var t=aa.createElementNS(ia.ns.prefix.svg,"g");return(ia.transform=function(e){if(null!=e){t.setAttribute("transform",e);var n=t.transform.baseVal.consolidate()}return new Ui(n?n.matrix:Eu)})(e)};Ui.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var Eu={a:1,b:0,c:0,d:1,e:0,f:0};ia.interpolateTransform=Vi;ia.layout={};ia.layout.bundle=function(){return function(e){for(var t=[],n=-1,r=e.length;++n<r;)t.push(Wi(e[n]));return t}};ia.layout.chord=function(){function e(){var e,u,c,d,f,h={},g=[],m=ia.range(o),E=[];n=[];r=[];e=0,d=-1;for(;++d<o;){u=0,f=-1;for(;++f<o;)u+=i[d][f];g.push(u);E.push(ia.range(o));e+=u}s&&m.sort(function(e,t){return s(g[e],g[t])});a&&E.forEach(function(e,t){e.sort(function(e,n){return a(i[t][e],i[t][n])})});e=(Ua-p*o)/e;u=0,d=-1;for(;++d<o;){c=u,f=-1;for(;++f<o;){var v=m[d],x=E[v][f],y=i[v][x],N=u,I=u+=y*e;h[v+"-"+x]={index:v,subindex:x,startAngle:N,endAngle:I,value:y}}r[v]={index:v,startAngle:c,endAngle:u,value:(u-c)/e};u+=p}d=-1;for(;++d<o;){f=d-1;for(;++f<o;){var A=h[d+"-"+f],T=h[f+"-"+d];(A.value||T.value)&&n.push(A.value<T.value?{source:T,target:A}:{source:A,target:T})}}l&&t()}function t(){n.sort(function(e,t){return l((e.source.value+e.target.value)/2,(t.source.value+t.target.value)/2)})}var n,r,i,o,s,a,l,u={},p=0;u.matrix=function(e){if(!arguments.length)return i;o=(i=e)&&i.length;n=r=null;return u};u.padding=function(e){if(!arguments.length)return p;p=e;n=r=null;return u};u.sortGroups=function(e){if(!arguments.length)return s;s=e;n=r=null;return u};u.sortSubgroups=function(e){if(!arguments.length)return a;a=e;n=null;return u};u.sortChords=function(e){if(!arguments.length)return l;l=e;n&&t();return u};u.chords=function(){n||e();return n};u.groups=function(){r||e();return r};return u};ia.layout.force=function(){function e(e){return function(t,n,r,i){if(t.point!==e){var o=t.cx-e.x,s=t.cy-e.y,a=i-n,l=o*o+s*s;if(l>a*a/m){if(h>l){var u=t.charge/l;e.px-=o*u;e.py-=s*u}return!0}if(t.point&&l&&h>l){var u=t.pointCharge/l;e.px-=o*u;e.py-=s*u}}return!t.charge}}function t(e){e.px=ia.event.x,e.py=ia.event.y;a.resume()}var n,r,i,o,s,a={},l=ia.dispatch("start","tick","end"),u=[1,1],p=.9,c=vu,d=xu,f=-30,h=yu,g=.1,m=.64,E=[],v=[];a.tick=function(){if((r*=.99)<.005){l.end({type:"end",alpha:r=0});return!0}var t,n,a,c,d,h,m,x,y,N=E.length,I=v.length;for(n=0;I>n;++n){a=v[n];c=a.source;d=a.target;x=d.x-c.x;y=d.y-c.y;if(h=x*x+y*y){h=r*o[n]*((h=Math.sqrt(h))-i[n])/h;x*=h;y*=h;d.x-=x*(m=c.weight/(d.weight+c.weight));d.y-=y*m;c.x+=x*(m=1-m);c.y+=y*m}}if(m=r*g){x=u[0]/2;y=u[1]/2;n=-1;if(m)for(;++n<N;){a=E[n];a.x+=(x-a.x)*m;a.y+=(y-a.y)*m}}if(f){Ji(t=ia.geom.quadtree(E),r,s);n=-1;for(;++n<N;)(a=E[n]).fixed||t.visit(e(a))}n=-1;for(;++n<N;){a=E[n];if(a.fixed){a.x=a.px;a.y=a.py}else{a.x-=(a.px-(a.px=a.x))*p;a.y-=(a.py-(a.py=a.y))*p}}l.tick({type:"tick",alpha:r})};a.nodes=function(e){if(!arguments.length)return E;E=e;return a};a.links=function(e){if(!arguments.length)return v;v=e;return a};a.size=function(e){if(!arguments.length)return u;u=e;return a};a.linkDistance=function(e){if(!arguments.length)return c;c="function"==typeof e?e:+e;return a};a.distance=a.linkDistance;a.linkStrength=function(e){if(!arguments.length)return d;d="function"==typeof e?e:+e;return a};a.friction=function(e){if(!arguments.length)return p;p=+e;return a};a.charge=function(e){if(!arguments.length)return f;f="function"==typeof e?e:+e;return a};a.chargeDistance=function(e){if(!arguments.length)return Math.sqrt(h);h=e*e;return a};a.gravity=function(e){if(!arguments.length)return g;g=+e;return a};a.theta=function(e){if(!arguments.length)return Math.sqrt(m);m=e*e;return a};a.alpha=function(e){if(!arguments.length)return r;e=+e;if(r)r=e>0?e:0;else if(e>0){l.start({type:"start",alpha:r=e});ia.timer(a.tick)}return a};a.start=function(){function e(e,r){if(!n){n=new Array(l);for(a=0;l>a;++a)n[a]=[];for(a=0;u>a;++a){var i=v[a];n[i.source.index].push(i.target);n[i.target.index].push(i.source)}}for(var o,s=n[t],a=-1,u=s.length;++a<u;)if(!isNaN(o=s[a][e]))return o;return Math.random()*r}var t,n,r,l=E.length,p=v.length,h=u[0],g=u[1];for(t=0;l>t;++t){(r=E[t]).index=t;r.weight=0}for(t=0;p>t;++t){r=v[t];"number"==typeof r.source&&(r.source=E[r.source]);"number"==typeof r.target&&(r.target=E[r.target]);++r.source.weight;++r.target.weight}for(t=0;l>t;++t){r=E[t];isNaN(r.x)&&(r.x=e("x",h));isNaN(r.y)&&(r.y=e("y",g));isNaN(r.px)&&(r.px=r.x);isNaN(r.py)&&(r.py=r.y)}i=[];if("function"==typeof c)for(t=0;p>t;++t)i[t]=+c.call(this,v[t],t);else for(t=0;p>t;++t)i[t]=c;o=[];if("function"==typeof d)for(t=0;p>t;++t)o[t]=+d.call(this,v[t],t);else for(t=0;p>t;++t)o[t]=d;s=[];if("function"==typeof f)for(t=0;l>t;++t)s[t]=+f.call(this,E[t],t);else for(t=0;l>t;++t)s[t]=f;return a.resume()};a.resume=function(){return a.alpha(.1)};a.stop=function(){return a.alpha(0)};a.drag=function(){n||(n=ia.behavior.drag().origin(bt).on("dragstart.force",Ki).on("drag.force",t).on("dragend.force",Qi));if(!arguments.length)return n;this.on("mouseover.force",Xi).on("mouseout.force",Zi).call(n);return void 0};return ia.rebind(a,l,"on")};var vu=20,xu=1,yu=1/0;ia.layout.hierarchy=function(){function e(i){var o,s=[i],a=[];i.depth=0;for(;null!=(o=s.pop());){a.push(o);if((u=n.call(e,o,o.depth))&&(l=u.length)){for(var l,u,p;--l>=0;){s.push(p=u[l]);p.parent=o;p.depth=o.depth+1}r&&(o.value=0);o.children=u}else{r&&(o.value=+r.call(e,o,o.depth)||0);delete o.children}}no(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t);r&&(i=e.parent)&&(i.value+=e.value)});return a}var t=oo,n=ro,r=io;e.sort=function(n){if(!arguments.length)return t;t=n;return e};e.children=function(t){if(!arguments.length)return n;n=t;return e};e.value=function(t){if(!arguments.length)return r;r=t;return e};e.revalue=function(t){if(r){to(t,function(e){e.children&&(e.value=0)});no(t,function(t){var n;t.children||(t.value=+r.call(e,t,t.depth)||0);(n=t.parent)&&(n.value+=t.value)})}return t};return e};ia.layout.partition=function(){function e(t,n,r,i){var o=t.children;t.x=n;t.y=t.depth*i;t.dx=r;t.dy=i;if(o&&(s=o.length)){var s,a,l,u=-1;r=t.value?r/t.value:0;for(;++u<s;){e(a=o[u],n,l=a.value*r,i);n+=l}}}function t(e){var n=e.children,r=0;if(n&&(i=n.length))for(var i,o=-1;++o<i;)r=Math.max(r,t(n[o]));return 1+r}function n(n,o){var s=r.call(this,n,o);e(s[0],0,i[0],i[1]/t(s[0]));return s}var r=ia.layout.hierarchy(),i=[1,1];n.size=function(e){if(!arguments.length)return i;i=e;return n};return eo(n,r)};ia.layout.pie=function(){function e(s){var a,l=s.length,u=s.map(function(n,r){return+t.call(e,n,r)}),p=+("function"==typeof r?r.apply(this,arguments):r),c=("function"==typeof i?i.apply(this,arguments):i)-p,d=Math.min(Math.abs(c)/l,+("function"==typeof o?o.apply(this,arguments):o)),f=d*(0>c?-1:1),h=(c-l*f)/ia.sum(u),g=ia.range(l),m=[];null!=n&&g.sort(n===Nu?function(e,t){return u[t]-u[e]}:function(e,t){return n(s[e],s[t])});g.forEach(function(e){m[e]={data:s[e],value:a=u[e],startAngle:p,endAngle:p+=a*h+f,padAngle:d}});return m}var t=Number,n=Nu,r=0,i=Ua,o=0;e.value=function(n){if(!arguments.length)return t;t=n;return e};e.sort=function(t){if(!arguments.length)return n;n=t;return e};e.startAngle=function(t){if(!arguments.length)return r;r=t;return e};e.endAngle=function(t){if(!arguments.length)return i;i=t;return e};e.padAngle=function(t){if(!arguments.length)return o;o=t;return e};return e};var Nu={};ia.layout.stack=function(){function e(a,l){if(!(d=a.length))return a;var u=a.map(function(n,r){return t.call(e,n,r)}),p=u.map(function(t){return t.map(function(t,n){return[o.call(e,t,n),s.call(e,t,n)]})}),c=n.call(e,p,l);u=ia.permute(u,c);p=ia.permute(p,c);var d,f,h,g,m=r.call(e,p,l),E=u[0].length;for(h=0;E>h;++h){i.call(e,u[0][h],g=m[h],p[0][h][1]);for(f=1;d>f;++f)i.call(e,u[f][h],g+=p[f-1][h][1],p[f][h][1])}return a}var t=bt,n=po,r=co,i=uo,o=ao,s=lo;e.values=function(n){if(!arguments.length)return t;t=n;return e};e.order=function(t){if(!arguments.length)return n;n="function"==typeof t?t:Iu.get(t)||po;return e};e.offset=function(t){if(!arguments.length)return r;r="function"==typeof t?t:Au.get(t)||co;return e};e.x=function(t){if(!arguments.length)return o;o=t;return e};e.y=function(t){if(!arguments.length)return s;s=t;return e};e.out=function(t){if(!arguments.length)return i;i=t;return e};return e};var Iu=ia.map({"inside-out":function(e){var t,n,r=e.length,i=e.map(fo),o=e.map(ho),s=ia.range(r).sort(function(e,t){return i[e]-i[t]}),a=0,l=0,u=[],p=[];for(t=0;r>t;++t){n=s[t];if(l>a){a+=o[n];u.push(n)}else{l+=o[n];p.push(n)}}return p.reverse().concat(u)},reverse:function(e){return ia.range(e.length).reverse()},"default":po}),Au=ia.map({silhouette:function(e){var t,n,r,i=e.length,o=e[0].length,s=[],a=0,l=[];for(n=0;o>n;++n){for(t=0,r=0;i>t;t++)r+=e[t][n][1];r>a&&(a=r);s.push(r)}for(n=0;o>n;++n)l[n]=(a-s[n])/2;return l},wiggle:function(e){var t,n,r,i,o,s,a,l,u,p=e.length,c=e[0],d=c.length,f=[];f[0]=l=u=0;for(n=1;d>n;++n){for(t=0,i=0;p>t;++t)i+=e[t][n][1];for(t=0,o=0,a=c[n][0]-c[n-1][0];p>t;++t){for(r=0,s=(e[t][n][1]-e[t][n-1][1])/(2*a);t>r;++r)s+=(e[r][n][1]-e[r][n-1][1])/a;o+=s*e[t][n][1]}f[n]=l-=i?o/i*a:0;u>l&&(u=l)}for(n=0;d>n;++n)f[n]-=u;return f},expand:function(e){var t,n,r,i=e.length,o=e[0].length,s=1/i,a=[];for(n=0;o>n;++n){for(t=0,r=0;i>t;t++)r+=e[t][n][1];if(r)for(t=0;i>t;t++)e[t][n][1]/=r;else for(t=0;i>t;t++)e[t][n][1]=s}for(n=0;o>n;++n)a[n]=0;return a},zero:co});ia.layout.histogram=function(){function e(e,o){for(var s,a,l=[],u=e.map(n,this),p=r.call(this,u,o),c=i.call(this,p,u,o),o=-1,d=u.length,f=c.length-1,h=t?1:1/d;++o<f;){s=l[o]=[];s.dx=c[o+1]-(s.x=c[o]);s.y=0}if(f>0){o=-1;
for(;++o<d;){a=u[o];if(a>=p[0]&&a<=p[1]){s=l[ia.bisect(c,a,1,f)-1];s.y+=h;s.push(e[o])}}}return l}var t=!0,n=Number,r=vo,i=mo;e.value=function(t){if(!arguments.length)return n;n=t;return e};e.range=function(t){if(!arguments.length)return r;r=Ct(t);return e};e.bins=function(t){if(!arguments.length)return i;i="number"==typeof t?function(e){return Eo(e,t)}:Ct(t);return e};e.frequency=function(n){if(!arguments.length)return t;t=!!n;return e};return e};ia.layout.pack=function(){function e(e,o){var s=n.call(this,e,o),a=s[0],l=i[0],u=i[1],p=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};a.x=a.y=0;no(a,function(e){e.r=+p(e.value)});no(a,Ao);if(r){var c=r*(t?1:Math.max(2*a.r/l,2*a.r/u))/2;no(a,function(e){e.r+=c});no(a,Ao);no(a,function(e){e.r-=c})}So(a,l/2,u/2,t?1:1/Math.max(2*a.r/l,2*a.r/u));return s}var t,n=ia.layout.hierarchy().sort(xo),r=0,i=[1,1];e.size=function(t){if(!arguments.length)return i;i=t;return e};e.radius=function(n){if(!arguments.length)return t;t=null==n||"function"==typeof n?n:+n;return e};e.padding=function(t){if(!arguments.length)return r;r=+t;return e};return eo(e,n)};ia.layout.tree=function(){function e(e,i){var p=s.call(this,e,i),c=p[0],d=t(c);no(d,n),d.parent.m=-d.z;to(d,r);if(u)to(c,o);else{var f=c,h=c,g=c;to(c,function(e){e.x<f.x&&(f=e);e.x>h.x&&(h=e);e.depth>g.depth&&(g=e)});var m=a(f,h)/2-f.x,E=l[0]/(h.x+a(h,f)/2+m),v=l[1]/(g.depth||1);to(c,function(e){e.x=(e.x+m)*E;e.y=e.depth*v})}return p}function t(e){for(var t,n={A:null,children:[e]},r=[n];null!=(t=r.pop());)for(var i,o=t.children,s=0,a=o.length;a>s;++s)r.push((o[s]=i={_:o[s],parent:t,children:(i=o[s].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:s}).a=i);return n.children[0]}function n(e){var t=e.children,n=e.parent.children,r=e.i?n[e.i-1]:null;if(t.length){_o(e);var o=(t[0].z+t[t.length-1].z)/2;if(r){e.z=r.z+a(e._,r._);e.m=e.z-o}else e.z=o}else r&&(e.z=r.z+a(e._,r._));e.parent.A=i(e,r,e.parent.A||n[0])}function r(e){e._.x=e.z+e.parent.m;e.m+=e.parent.m}function i(e,t,n){if(t){for(var r,i=e,o=e,s=t,l=i.parent.children[0],u=i.m,p=o.m,c=s.m,d=l.m;s=wo(s),i=Ro(i),s&&i;){l=Ro(l);o=wo(o);o.a=e;r=s.z+c-i.z-u+a(s._,i._);if(r>0){Oo(Fo(s,e,n),e,r);u+=r;p+=r}c+=s.m;u+=i.m;d+=l.m;p+=o.m}if(s&&!wo(o)){o.t=s;o.m+=c-p}if(i&&!Ro(l)){l.t=i;l.m+=u-d;n=e}}return n}function o(e){e.x*=l[0];e.y=e.depth*l[1]}var s=ia.layout.hierarchy().sort(null).value(null),a=bo,l=[1,1],u=null;e.separation=function(t){if(!arguments.length)return a;a=t;return e};e.size=function(t){if(!arguments.length)return u?null:l;u=null==(l=t)?o:null;return e};e.nodeSize=function(t){if(!arguments.length)return u?l:null;u=null==(l=t)?null:o;return e};return eo(e,s)};ia.layout.cluster=function(){function e(e,o){var s,a=t.call(this,e,o),l=a[0],u=0;no(l,function(e){var t=e.children;if(t&&t.length){e.x=Mo(t);e.y=Po(t)}else{e.x=s?u+=n(e,s):0;e.y=0;s=e}});var p=ko(l),c=Do(l),d=p.x-n(p,c)/2,f=c.x+n(c,p)/2;no(l,i?function(e){e.x=(e.x-l.x)*r[0];e.y=(l.y-e.y)*r[1]}:function(e){e.x=(e.x-d)/(f-d)*r[0];e.y=(1-(l.y?e.y/l.y:1))*r[1]});return a}var t=ia.layout.hierarchy().sort(null).value(null),n=bo,r=[1,1],i=!1;e.separation=function(t){if(!arguments.length)return n;n=t;return e};e.size=function(t){if(!arguments.length)return i?null:r;i=null==(r=t);return e};e.nodeSize=function(t){if(!arguments.length)return i?r:null;i=null!=(r=t);return e};return eo(e,t)};ia.layout.treemap=function(){function e(e,t){for(var n,r,i=-1,o=e.length;++i<o;){r=(n=e[i]).value*(0>t?0:t);n.area=isNaN(r)||0>=r?0:r}}function t(n){var o=n.children;if(o&&o.length){var s,a,l,u=c(n),p=[],d=o.slice(),h=1/0,g="slice"===f?u.dx:"dice"===f?u.dy:"slice-dice"===f?1&n.depth?u.dy:u.dx:Math.min(u.dx,u.dy);e(d,u.dx*u.dy/n.value);p.area=0;for(;(l=d.length)>0;){p.push(s=d[l-1]);p.area+=s.area;if("squarify"!==f||(a=r(p,g))<=h){d.pop();h=a}else{p.area-=p.pop().area;i(p,g,u,!1);g=Math.min(u.dx,u.dy);p.length=p.area=0;h=1/0}}if(p.length){i(p,g,u,!0);p.length=p.area=0}o.forEach(t)}}function n(t){var r=t.children;if(r&&r.length){var o,s=c(t),a=r.slice(),l=[];e(a,s.dx*s.dy/t.value);l.area=0;for(;o=a.pop();){l.push(o);l.area+=o.area;if(null!=o.z){i(l,o.z?s.dx:s.dy,s,!a.length);l.length=l.area=0}}r.forEach(n)}}function r(e,t){for(var n,r=e.area,i=0,o=1/0,s=-1,a=e.length;++s<a;)if(n=e[s].area){o>n&&(o=n);n>i&&(i=n)}r*=r;t*=t;return r?Math.max(t*i*h/r,r/(t*o*h)):1/0}function i(e,t,n,r){var i,o=-1,s=e.length,a=n.x,u=n.y,p=t?l(e.area/t):0;if(t==n.dx){(r||p>n.dy)&&(p=n.dy);for(;++o<s;){i=e[o];i.x=a;i.y=u;i.dy=p;a+=i.dx=Math.min(n.x+n.dx-a,p?l(i.area/p):0)}i.z=!0;i.dx+=n.x+n.dx-a;n.y+=p;n.dy-=p}else{(r||p>n.dx)&&(p=n.dx);for(;++o<s;){i=e[o];i.x=a;i.y=u;i.dx=p;u+=i.dy=Math.min(n.y+n.dy-u,p?l(i.area/p):0)}i.z=!1;i.dy+=n.y+n.dy-u;n.x+=p;n.dx-=p}}function o(r){var i=s||a(r),o=i[0];o.x=0;o.y=0;o.dx=u[0];o.dy=u[1];s&&a.revalue(o);e([o],o.dx*o.dy/o.value);(s?n:t)(o);d&&(s=i);return i}var s,a=ia.layout.hierarchy(),l=Math.round,u=[1,1],p=null,c=Go,d=!1,f="squarify",h=.5*(1+Math.sqrt(5));o.size=function(e){if(!arguments.length)return u;u=e;return o};o.padding=function(e){function t(t){var n=e.call(o,t,t.depth);return null==n?Go(t):Uo(t,"number"==typeof n?[n,n,n,n]:n)}function n(t){return Uo(t,e)}if(!arguments.length)return p;var r;c=null==(p=e)?Go:"function"==(r=typeof e)?t:"number"===r?(e=[e,e,e,e],n):n;return o};o.round=function(e){if(!arguments.length)return l!=Number;l=e?Math.round:Number;return o};o.sticky=function(e){if(!arguments.length)return d;d=e;s=null;return o};o.ratio=function(e){if(!arguments.length)return h;h=e;return o};o.mode=function(e){if(!arguments.length)return f;f=e+"";return o};return eo(o,a)};ia.random={normal:function(e,t){var n=arguments.length;2>n&&(t=1);1>n&&(e=0);return function(){var n,r,i;do{n=2*Math.random()-1;r=2*Math.random()-1;i=n*n+r*r}while(!i||i>1);return e+t*n*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var e=ia.random.normal.apply(ia,arguments);return function(){return Math.exp(e())}},bates:function(e){var t=ia.random.irwinHall(e);return function(){return t()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;e>n;n++)t+=Math.random();return t}}};ia.scale={};var Tu={floor:bt,ceil:bt};ia.scale.linear=function(){return Wo([0,1],[0,1],yi,!1)};var Lu={s:1,g:1,p:1,r:1,e:1};ia.scale.log=function(){return es(ia.scale.linear().domain([0,1]),10,!0,[1,10])};var Su=ia.format(".0e"),Cu={floor:function(e){return-Math.ceil(-e)},ceil:function(e){return-Math.floor(-e)}};ia.scale.pow=function(){return ts(ia.scale.linear(),1,[0,1])};ia.scale.sqrt=function(){return ia.scale.pow().exponent(.5)};ia.scale.ordinal=function(){return rs([],{t:"range",a:[[]]})};ia.scale.category10=function(){return ia.scale.ordinal().range(bu)};ia.scale.category20=function(){return ia.scale.ordinal().range(Ru)};ia.scale.category20b=function(){return ia.scale.ordinal().range(wu)};ia.scale.category20c=function(){return ia.scale.ordinal().range(Ou)};var bu=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(yt),Ru=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(yt),wu=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(yt),Ou=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(yt);ia.scale.quantile=function(){return is([],[])};ia.scale.quantize=function(){return os(0,1,[0,1])};ia.scale.threshold=function(){return ss([.5],[0,1])};ia.scale.identity=function(){return as([0,1])};ia.svg={};ia.svg.arc=function(){function e(){var e=Math.max(0,+n.apply(this,arguments)),u=Math.max(0,+r.apply(this,arguments)),p=s.apply(this,arguments)-ja,c=a.apply(this,arguments)-ja,d=Math.abs(c-p),f=p>c?0:1;e>u&&(h=u,u=e,e=h);if(d>=Ba)return t(u,f)+(e?t(e,1-f):"")+"Z";var h,g,m,E,v,x,y,N,I,A,T,L,S=0,C=0,b=[];if(E=(+l.apply(this,arguments)||0)/2){m=o===_u?Math.sqrt(e*e+u*u):+o.apply(this,arguments);f||(C*=-1);u&&(C=nt(m/u*Math.sin(E)));e&&(S=nt(m/e*Math.sin(E)))}if(u){v=u*Math.cos(p+C);x=u*Math.sin(p+C);y=u*Math.cos(c-C);N=u*Math.sin(c-C);var R=Math.abs(c-p-2*C)<=Ga?0:1;if(C&&hs(v,x,y,N)===f^R){var w=(p+c)/2;v=u*Math.cos(w);x=u*Math.sin(w);y=N=null}}else v=x=0;if(e){I=e*Math.cos(c-S);A=e*Math.sin(c-S);T=e*Math.cos(p+S);L=e*Math.sin(p+S);var O=Math.abs(p-c+2*S)<=Ga?0:1;if(S&&hs(I,A,T,L)===1-f^O){var _=(p+c)/2;I=e*Math.cos(_);A=e*Math.sin(_);T=L=null}}else I=A=0;if((h=Math.min(Math.abs(u-e)/2,+i.apply(this,arguments)))>.001){g=u>e^f?0:1;var F=null==T?[I,A]:null==y?[v,x]:Mr([v,x],[T,L],[y,N],[I,A]),P=v-F[0],M=x-F[1],k=y-F[0],D=N-F[1],G=1/Math.sin(Math.acos((P*k+M*D)/(Math.sqrt(P*P+M*M)*Math.sqrt(k*k+D*D)))/2),U=Math.sqrt(F[0]*F[0]+F[1]*F[1]);if(null!=y){var B=Math.min(h,(u-U)/(G+1)),j=gs(null==T?[I,A]:[T,L],[v,x],u,B,f),q=gs([y,N],[I,A],u,B,f);h===B?b.push("M",j[0],"A",B,",",B," 0 0,",g," ",j[1],"A",u,",",u," 0 ",1-f^hs(j[1][0],j[1][1],q[1][0],q[1][1]),",",f," ",q[1],"A",B,",",B," 0 0,",g," ",q[0]):b.push("M",j[0],"A",B,",",B," 0 1,",g," ",q[0])}else b.push("M",v,",",x);if(null!=T){var V=Math.min(h,(e-U)/(G-1)),H=gs([v,x],[T,L],e,-V,f),z=gs([I,A],null==y?[v,x]:[y,N],e,-V,f);h===V?b.push("L",z[0],"A",V,",",V," 0 0,",g," ",z[1],"A",e,",",e," 0 ",f^hs(z[1][0],z[1][1],H[1][0],H[1][1]),",",1-f," ",H[1],"A",V,",",V," 0 0,",g," ",H[0]):b.push("L",z[0],"A",V,",",V," 0 0,",g," ",H[0])}else b.push("L",I,",",A)}else{b.push("M",v,",",x);null!=y&&b.push("A",u,",",u," 0 ",R,",",f," ",y,",",N);b.push("L",I,",",A);null!=T&&b.push("A",e,",",e," 0 ",O,",",1-f," ",T,",",L)}b.push("Z");return b.join("")}function t(e,t){return"M0,"+e+"A"+e+","+e+" 0 1,"+t+" 0,"+-e+"A"+e+","+e+" 0 1,"+t+" 0,"+e}var n=us,r=ps,i=ls,o=_u,s=cs,a=ds,l=fs;e.innerRadius=function(t){if(!arguments.length)return n;n=Ct(t);return e};e.outerRadius=function(t){if(!arguments.length)return r;r=Ct(t);return e};e.cornerRadius=function(t){if(!arguments.length)return i;i=Ct(t);return e};e.padRadius=function(t){if(!arguments.length)return o;o=t==_u?_u:Ct(t);return e};e.startAngle=function(t){if(!arguments.length)return s;s=Ct(t);return e};e.endAngle=function(t){if(!arguments.length)return a;a=Ct(t);return e};e.padAngle=function(t){if(!arguments.length)return l;l=Ct(t);return e};e.centroid=function(){var e=(+n.apply(this,arguments)+ +r.apply(this,arguments))/2,t=(+s.apply(this,arguments)+ +a.apply(this,arguments))/2-ja;return[Math.cos(t)*e,Math.sin(t)*e]};return e};var _u="auto";ia.svg.line=function(){return ms(bt)};var Fu=ia.map({linear:Es,"linear-closed":vs,step:xs,"step-before":ys,"step-after":Ns,basis:Cs,"basis-open":bs,"basis-closed":Rs,bundle:ws,cardinal:Ts,"cardinal-open":Is,"cardinal-closed":As,monotone:ks});Fu.forEach(function(e,t){t.key=e;t.closed=/-closed$/.test(e)});var Pu=[0,2/3,1/3,0],Mu=[0,1/3,2/3,0],ku=[0,1/6,2/3,1/6];ia.svg.line.radial=function(){var e=ms(Ds);e.radius=e.x,delete e.x;e.angle=e.y,delete e.y;return e};ys.reverse=Ns;Ns.reverse=ys;ia.svg.area=function(){return Gs(bt)};ia.svg.area.radial=function(){var e=Gs(Ds);e.radius=e.x,delete e.x;e.innerRadius=e.x0,delete e.x0;e.outerRadius=e.x1,delete e.x1;e.angle=e.y,delete e.y;e.startAngle=e.y0,delete e.y0;e.endAngle=e.y1,delete e.y1;return e};ia.svg.chord=function(){function e(e,a){var l=t(this,o,e,a),u=t(this,s,e,a);return"M"+l.p0+r(l.r,l.p1,l.a1-l.a0)+(n(l,u)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,u.r,u.p0)+r(u.r,u.p1,u.a1-u.a0)+i(u.r,u.p1,l.r,l.p0))+"Z"}function t(e,t,n,r){var i=t.call(e,n,r),o=a.call(e,i,r),s=l.call(e,i,r)-ja,p=u.call(e,i,r)-ja;return{r:o,a0:s,a1:p,p0:[o*Math.cos(s),o*Math.sin(s)],p1:[o*Math.cos(p),o*Math.sin(p)]}}function n(e,t){return e.a0==t.a0&&e.a1==t.a1}function r(e,t,n){return"A"+e+","+e+" 0 "+ +(n>Ga)+",1 "+t}function i(e,t,n,r){return"Q 0,0 "+r}var o=yr,s=Nr,a=Us,l=cs,u=ds;e.radius=function(t){if(!arguments.length)return a;a=Ct(t);return e};e.source=function(t){if(!arguments.length)return o;o=Ct(t);return e};e.target=function(t){if(!arguments.length)return s;s=Ct(t);return e};e.startAngle=function(t){if(!arguments.length)return l;l=Ct(t);return e};e.endAngle=function(t){if(!arguments.length)return u;u=Ct(t);return e};return e};ia.svg.diagonal=function(){function e(e,i){var o=t.call(this,e,i),s=n.call(this,e,i),a=(o.y+s.y)/2,l=[o,{x:o.x,y:a},{x:s.x,y:a},s];l=l.map(r);return"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var t=yr,n=Nr,r=Bs;e.source=function(n){if(!arguments.length)return t;t=Ct(n);return e};e.target=function(t){if(!arguments.length)return n;n=Ct(t);return e};e.projection=function(t){if(!arguments.length)return r;r=t;return e};return e};ia.svg.diagonal.radial=function(){var e=ia.svg.diagonal(),t=Bs,n=e.projection;e.projection=function(e){return arguments.length?n(js(t=e)):t};return e};ia.svg.symbol=function(){function e(e,r){return(Du.get(t.call(this,e,r))||Hs)(n.call(this,e,r))}var t=Vs,n=qs;e.type=function(n){if(!arguments.length)return t;t=Ct(n);return e};e.size=function(t){if(!arguments.length)return n;n=Ct(t);return e};return e};var Du=ia.map({circle:Hs,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*Uu)),n=t*Uu;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/Gu),n=t*Gu/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/Gu),n=t*Gu/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});ia.svg.symbolTypes=Du.keys();var Gu=Math.sqrt(3),Uu=Math.tan(30*qa);ba.transition=function(e){for(var t,n,r=Bu||++Hu,i=Ks(e),o=[],s=ju||{time:Date.now(),ease:Ci,delay:0,duration:250},a=-1,l=this.length;++a<l;){o.push(t=[]);for(var u=this[a],p=-1,c=u.length;++p<c;){(n=u[p])&&Qs(n,p,i,r,s);t.push(n)}}return Ws(o,i,r)};ba.interrupt=function(e){return this.each(null==e?qu:zs(Ks(e)))};var Bu,ju,qu=zs(Ks()),Vu=[],Hu=0;Vu.call=ba.call;Vu.empty=ba.empty;Vu.node=ba.node;Vu.size=ba.size;ia.transition=function(e,t){return e&&e.transition?Bu?e.transition(t):e:Oa.transition(e)};ia.transition.prototype=Vu;Vu.select=function(e){var t,n,r,i=this.id,o=this.namespace,s=[];e=C(e);for(var a=-1,l=this.length;++a<l;){s.push(t=[]);for(var u=this[a],p=-1,c=u.length;++p<c;)if((r=u[p])&&(n=e.call(r,r.__data__,p,a))){"__data__"in r&&(n.__data__=r.__data__);Qs(n,p,o,i,r[o][i]);t.push(n)}else t.push(null)}return Ws(s,o,i)};Vu.selectAll=function(e){var t,n,r,i,o,s=this.id,a=this.namespace,l=[];e=b(e);for(var u=-1,p=this.length;++u<p;)for(var c=this[u],d=-1,f=c.length;++d<f;)if(r=c[d]){o=r[a][s];n=e.call(r,r.__data__,d,u);l.push(t=[]);for(var h=-1,g=n.length;++h<g;){(i=n[h])&&Qs(i,h,a,s,o);t.push(i)}}return Ws(l,a,s)};Vu.filter=function(e){var t,n,r,i=[];"function"!=typeof e&&(e=B(e));for(var o=0,s=this.length;s>o;o++){i.push(t=[]);for(var n=this[o],a=0,l=n.length;l>a;a++)(r=n[a])&&e.call(r,r.__data__,a,o)&&t.push(r)}return Ws(i,this.namespace,this.id)};Vu.tween=function(e,t){var n=this.id,r=this.namespace;return arguments.length<2?this.node()[r][n].tween.get(e):q(this,null==t?function(t){t[r][n].tween.remove(e)}:function(i){i[r][n].tween.set(e,t)})};Vu.attr=function(e,t){function n(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function i(e){return null==e?n:(e+="",function(){var t,n=this.getAttribute(a);return n!==e&&(t=s(n,e),function(e){this.setAttribute(a,t(e))})})}function o(e){return null==e?r:(e+="",function(){var t,n=this.getAttributeNS(a.space,a.local);return n!==e&&(t=s(n,e),function(e){this.setAttributeNS(a.space,a.local,t(e))})})}if(arguments.length<2){for(t in e)this.attr(t,e[t]);return this}var s="transform"==e?Vi:yi,a=ia.ns.qualify(e);return $s(this,"attr."+e,t,a.local?o:i)};Vu.attrTween=function(e,t){function n(e,n){var r=t.call(this,e,n,this.getAttribute(i));return r&&function(e){this.setAttribute(i,r(e))}}function r(e,n){var r=t.call(this,e,n,this.getAttributeNS(i.space,i.local));return r&&function(e){this.setAttributeNS(i.space,i.local,r(e))}}var i=ia.ns.qualify(e);return this.tween("attr."+e,i.local?r:n)};Vu.style=function(e,t,n){function r(){this.style.removeProperty(e)}function i(t){return null==t?r:(t+="",function(){var r,i=ua.getComputedStyle(this,null).getPropertyValue(e);return i!==t&&(r=yi(i,t),function(t){this.style.setProperty(e,r(t),n)})})}var o=arguments.length;if(3>o){if("string"!=typeof e){2>o&&(t="");for(n in e)this.style(n,e[n],t);return this}n=""}return $s(this,"style."+e,t,i)};Vu.styleTween=function(e,t,n){function r(r,i){var o=t.call(this,r,i,ua.getComputedStyle(this,null).getPropertyValue(e));return o&&function(t){this.style.setProperty(e,o(t),n)}}arguments.length<3&&(n="");return this.tween("style."+e,r)};Vu.text=function(e){return $s(this,"text",e,Ys)};Vu.remove=function(){var e=this.namespace;return this.each("end.transition",function(){var t;this[e].count<2&&(t=this.parentNode)&&t.removeChild(this)})};Vu.ease=function(e){var t=this.id,n=this.namespace;if(arguments.length<1)return this.node()[n][t].ease;"function"!=typeof e&&(e=ia.ease.apply(ia,arguments));return q(this,function(r){r[n][t].ease=e})};Vu.delay=function(e){var t=this.id,n=this.namespace;return arguments.length<1?this.node()[n][t].delay:q(this,"function"==typeof e?function(r,i,o){r[n][t].delay=+e.call(r,r.__data__,i,o)}:(e=+e,function(r){r[n][t].delay=e}))};Vu.duration=function(e){var t=this.id,n=this.namespace;return arguments.length<1?this.node()[n][t].duration:q(this,"function"==typeof e?function(r,i,o){r[n][t].duration=Math.max(1,e.call(r,r.__data__,i,o))}:(e=Math.max(1,e),function(r){r[n][t].duration=e}))};Vu.each=function(e,t){var n=this.id,r=this.namespace;if(arguments.length<2){var i=ju,o=Bu;try{Bu=n;q(this,function(t,i,o){ju=t[r][n];e.call(t,t.__data__,i,o)})}finally{ju=i;Bu=o}}else q(this,function(i){var o=i[r][n];(o.event||(o.event=ia.dispatch("start","end","interrupt"))).on(e,t)});return this};Vu.transition=function(){for(var e,t,n,r,i=this.id,o=++Hu,s=this.namespace,a=[],l=0,u=this.length;u>l;l++){a.push(e=[]);for(var t=this[l],p=0,c=t.length;c>p;p++){if(n=t[p]){r=n[s][i];Qs(n,p,s,o,{time:r.time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration})}e.push(n)}}return Ws(a,s,o)};ia.svg.axis=function(){function e(e){e.each(function(){var e,u=ia.select(this),p=this.__chart__||n,c=this.__chart__=n.copy(),d=null==l?c.ticks?c.ticks.apply(c,a):c.domain():l,f=null==t?c.tickFormat?c.tickFormat.apply(c,a):bt:t,h=u.selectAll(".tick").data(d,c),g=h.enter().insert("g",".domain").attr("class","tick").style("opacity",ka),m=ia.transition(h.exit()).style("opacity",ka).remove(),E=ia.transition(h.order()).style("opacity",1),v=Math.max(i,0)+s,x=jo(c),y=u.selectAll(".domain").data([0]),N=(y.enter().append("path").attr("class","domain"),ia.transition(y));g.append("line");g.append("text");var I,A,T,L,S=g.select("line"),C=E.select("line"),b=h.select("text").text(f),R=g.select("text"),w=E.select("text"),O="top"===r||"left"===r?-1:1;if("bottom"===r||"top"===r){e=Xs,I="x",T="y",A="x2",L="y2";b.attr("dy",0>O?"0em":".71em").style("text-anchor","middle");N.attr("d","M"+x[0]+","+O*o+"V0H"+x[1]+"V"+O*o)}else{e=Zs,I="y",T="x",A="y2",L="x2";b.attr("dy",".32em").style("text-anchor",0>O?"end":"start");N.attr("d","M"+O*o+","+x[0]+"H0V"+x[1]+"H"+O*o)}S.attr(L,O*i);R.attr(T,O*v);C.attr(A,0).attr(L,O*i);w.attr(I,0).attr(T,O*v);if(c.rangeBand){var _=c,F=_.rangeBand()/2;p=c=function(e){return _(e)+F}}else p.rangeBand?p=c:m.call(e,c,p);g.call(e,p,c);E.call(e,c,c)})}var t,n=ia.scale.linear(),r=zu,i=6,o=6,s=3,a=[10],l=null;e.scale=function(t){if(!arguments.length)return n;n=t;return e};e.orient=function(t){if(!arguments.length)return r;r=t in Wu?t+"":zu;return e};e.ticks=function(){if(!arguments.length)return a;a=arguments;return e};e.tickValues=function(t){if(!arguments.length)return l;l=t;return e};e.tickFormat=function(n){if(!arguments.length)return t;t=n;return e};e.tickSize=function(t){var n=arguments.length;if(!n)return i;i=+t;o=+arguments[n-1];return e};e.innerTickSize=function(t){if(!arguments.length)return i;i=+t;return e};e.outerTickSize=function(t){if(!arguments.length)return o;o=+t;return e};e.tickPadding=function(t){if(!arguments.length)return s;s=+t;return e};e.tickSubdivide=function(){return arguments.length&&e};return e};var zu="bottom",Wu={top:1,right:1,bottom:1,left:1};ia.svg.brush=function(){function e(o){o.each(function(){var o=ia.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",i).on("touchstart.brush",i),s=o.selectAll(".background").data([0]);s.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair");o.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=o.selectAll(".resize").data(h,bt);a.exit().remove();a.enter().append("g").attr("class",function(e){return"resize "+e}).style("cursor",function(e){return $u[e]}).append("rect").attr("x",function(e){return/[ew]$/.test(e)?-3:null}).attr("y",function(e){return/^[ns]/.test(e)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden");a.style("display",e.empty()?"none":null);var p,c=ia.transition(o),d=ia.transition(s);if(l){p=jo(l);d.attr("x",p[0]).attr("width",p[1]-p[0]);n(c)}if(u){p=jo(u);d.attr("y",p[0]).attr("height",p[1]-p[0]);r(c)}t(c)})}function t(e){e.selectAll(".resize").attr("transform",function(e){return"translate("+p[+/e$/.test(e)]+","+c[+/^s/.test(e)]+")"})}function n(e){e.select(".extent").attr("x",p[0]);e.selectAll(".extent,.n>rect,.s>rect").attr("width",p[1]-p[0])}function r(e){e.select(".extent").attr("y",c[0]);e.selectAll(".extent,.e>rect,.w>rect").attr("height",c[1]-c[0])}function i(){function i(){if(32==ia.event.keyCode){if(!b){v=null;w[0]-=p[1];w[1]-=c[1];b=2}A()}}function h(){if(32==ia.event.keyCode&&2==b){w[0]+=p[1];w[1]+=c[1];b=0;A()}}function g(){var e=ia.mouse(y),i=!1;if(x){e[0]+=x[0];e[1]+=x[1]}if(!b)if(ia.event.altKey){v||(v=[(p[0]+p[1])/2,(c[0]+c[1])/2]);w[0]=p[+(e[0]<v[0])];w[1]=c[+(e[1]<v[1])]}else v=null;if(S&&m(e,l,0)){n(T);i=!0}if(C&&m(e,u,1)){r(T);i=!0}if(i){t(T);I({type:"brush",mode:b?"move":"resize"})}}function m(e,t,n){var r,i,a=jo(t),l=a[0],u=a[1],h=w[n],g=n?c:p,m=g[1]-g[0];if(b){l-=h;u-=m+h}r=(n?f:d)?Math.max(l,Math.min(u,e[n])):e[n];if(b)i=(r+=h)+m;else{v&&(h=Math.max(l,Math.min(u,2*v[n]-r)));if(r>h){i=r;r=h}else i=h}if(g[0]!=r||g[1]!=i){n?s=null:o=null;g[0]=r;g[1]=i;return!0}}function E(){g();T.style("pointer-events","all").selectAll(".resize").style("display",e.empty()?"none":null);ia.select("body").style("cursor",null);O.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null);R();I({type:"brushend"})}var v,x,y=this,N=ia.select(ia.event.target),I=a.of(y,arguments),T=ia.select(y),L=N.datum(),S=!/^(n|s)$/.test(L)&&l,C=!/^(e|w)$/.test(L)&&u,b=N.classed("extent"),R=Y(),w=ia.mouse(y),O=ia.select(ua).on("keydown.brush",i).on("keyup.brush",h);ia.event.changedTouches?O.on("touchmove.brush",g).on("touchend.brush",E):O.on("mousemove.brush",g).on("mouseup.brush",E);T.interrupt().selectAll("*").interrupt();if(b){w[0]=p[0]-w[0];w[1]=c[0]-w[1]}else if(L){var _=+/w$/.test(L),F=+/^n/.test(L);x=[p[1-_]-w[0],c[1-F]-w[1]];w[0]=p[_];w[1]=c[F]}else ia.event.altKey&&(v=w.slice());T.style("pointer-events","none").selectAll(".resize").style("display",null);ia.select("body").style("cursor",N.style("cursor"));I({type:"brushstart"});g()}var o,s,a=L(e,"brushstart","brush","brushend"),l=null,u=null,p=[0,0],c=[0,0],d=!0,f=!0,h=Yu[0];e.event=function(e){e.each(function(){var e=a.of(this,arguments),t={x:p,y:c,i:o,j:s},n=this.__chart__||t;this.__chart__=t;if(Bu)ia.select(this).transition().each("start.brush",function(){o=n.i;s=n.j;p=n.x;c=n.y;e({type:"brushstart"})}).tween("brush:brush",function(){var n=Ni(p,t.x),r=Ni(c,t.y);o=s=null;return function(i){p=t.x=n(i);c=t.y=r(i);e({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=t.i;s=t.j;e({type:"brush",mode:"resize"});e({type:"brushend"})});else{e({type:"brushstart"});e({type:"brush",mode:"resize"});e({type:"brushend"})}})};e.x=function(t){if(!arguments.length)return l;l=t;h=Yu[!l<<1|!u];return e};e.y=function(t){if(!arguments.length)return u;u=t;h=Yu[!l<<1|!u];return e};e.clamp=function(t){if(!arguments.length)return l&&u?[d,f]:l?d:u?f:null;l&&u?(d=!!t[0],f=!!t[1]):l?d=!!t:u&&(f=!!t);return e};e.extent=function(t){var n,r,i,a,d;if(!arguments.length){if(l)if(o)n=o[0],r=o[1];else{n=p[0],r=p[1];l.invert&&(n=l.invert(n),r=l.invert(r));n>r&&(d=n,n=r,r=d)}if(u)if(s)i=s[0],a=s[1];else{i=c[0],a=c[1];u.invert&&(i=u.invert(i),a=u.invert(a));i>a&&(d=i,i=a,a=d)}return l&&u?[[n,i],[r,a]]:l?[n,r]:u&&[i,a]}if(l){n=t[0],r=t[1];u&&(n=n[0],r=r[0]);o=[n,r];l.invert&&(n=l(n),r=l(r));n>r&&(d=n,n=r,r=d);(n!=p[0]||r!=p[1])&&(p=[n,r])}if(u){i=t[0],a=t[1];l&&(i=i[1],a=a[1]);s=[i,a];u.invert&&(i=u(i),a=u(a));i>a&&(d=i,i=a,a=d);(i!=c[0]||a!=c[1])&&(c=[i,a])}return e};e.clear=function(){if(!e.empty()){p=[0,0],c=[0,0];o=s=null}return e};e.empty=function(){return!!l&&p[0]==p[1]||!!u&&c[0]==c[1]};return ia.rebind(e,a,"on")};var $u={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Yu=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Ku=hl.format=yl.timeFormat,Qu=Ku.utc,Xu=Qu("%Y-%m-%dT%H:%M:%S.%LZ");Ku.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Js:Xu;Js.parse=function(e){var t=new Date(e);return isNaN(t)?null:t};Js.toString=Xu.toString;hl.second=jt(function(e){return new gl(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()});hl.seconds=hl.second.range;hl.seconds.utc=hl.second.utc.range;hl.minute=jt(function(e){return new gl(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()});hl.minutes=hl.minute.range;hl.minutes.utc=hl.minute.utc.range;hl.hour=jt(function(e){var t=e.getTimezoneOffset()/60;return new gl(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()});hl.hours=hl.hour.range;hl.hours.utc=hl.hour.utc.range;hl.month=jt(function(e){e=hl.day(e);e.setDate(1);return e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()});hl.months=hl.month.range;hl.months.utc=hl.month.utc.range;var Zu=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ju=[[hl.second,1],[hl.second,5],[hl.second,15],[hl.second,30],[hl.minute,1],[hl.minute,5],[hl.minute,15],[hl.minute,30],[hl.hour,1],[hl.hour,3],[hl.hour,6],[hl.hour,12],[hl.day,1],[hl.day,2],[hl.week,1],[hl.month,1],[hl.month,3],[hl.year,1]],ep=Ku.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",On]]),tp={range:function(e,t,n){return ia.range(Math.ceil(e/n)*n,+t,n).map(ta)},floor:bt,ceil:bt};Ju.year=hl.year;hl.scale=function(){return ea(ia.scale.linear(),Ju,ep)};var np=Ju.map(function(e){return[e[0].utc,e[1]]}),rp=Qu.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",On]]);np.year=hl.year.utc;hl.scale.utc=function(){return ea(ia.scale.linear(),np,rp)};ia.text=Rt(function(e){return e.responseText});ia.json=function(e,t){return wt(e,"application/json",na,t)};ia.html=function(e,t){return wt(e,"text/html",ra,t)};ia.xml=Rt(function(e){return e.responseXML});"function"==typeof e&&e.amd?e(ia):"object"==typeof n&&n.exports&&(n.exports=ia);this.d3=ia}()},{}],54:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();(function(e,t){function n(t,n){var i,o,s,a=t.nodeName.toLowerCase();if("area"===a){i=t.parentNode;o=i.name;if(!t.href||!o||"map"!==i.nodeName.toLowerCase())return!1;s=e("img[usemap=#"+o+"]")[0];return!!s&&r(s)}return(/input|select|textarea|button|object/.test(a)?!t.disabled:"a"===a?t.href||n:n)&&r(t)}function r(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var i=0,o=/^ui-id-\d+$/;e.ui=e.ui||{};e.extend(e.ui,{version:"1.10.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}});e.fn.extend({focus:function(t){return function(n,r){return"number"==typeof n?this.each(function(){var t=this;setTimeout(function(){e(t).focus();r&&r.call(t)},n)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0);return/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(n){if(n!==t)return this.css("zIndex",n);if(this.length)for(var r,i,o=e(this[0]);o.length&&o[0]!==document;){r=o.css("position");if("absolute"===r||"relative"===r||"fixed"===r){i=parseInt(o.css("zIndex"),10);if(!isNaN(i)&&0!==i)return i}o=o.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++i)})},removeUniqueId:function(){return this.each(function(){o.test(this.id)&&e(this).removeAttr("id")})}});e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(t){return n(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var r=e.attr(t,"tabindex"),i=isNaN(r);return(i||r>=0)&&n(t,!i)}});e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(n,r){function i(t,n,r,i){e.each(o,function(){n-=parseFloat(e.css(t,"padding"+this))||0;r&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0);i&&(n-=parseFloat(e.css(t,"margin"+this))||0)});return n}var o="Width"===r?["Left","Right"]:["Top","Bottom"],s=r.toLowerCase(),a={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+r]=function(n){return n===t?a["inner"+r].call(this):this.each(function(){e(this).css(s,i(this,n)+"px")})};e.fn["outer"+r]=function(t,n){return"number"!=typeof t?a["outer"+r].call(this,t):this.each(function(){e(this).css(s,i(this,t,!0,n)+"px")})}});e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))});e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData));e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());e.support.selectstart="onselectstart"in document.createElement("div");e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")
}});e.extend(e.ui,{plugin:{add:function(t,n,r){var i,o=e.ui[t].prototype;for(i in r){o.plugins[i]=o.plugins[i]||[];o.plugins[i].push([n,r[i]])}},call:function(e,t,n){var r,i=e.plugins[t];if(i&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(r=0;r<i.length;r++)e.options[i[r][0]]&&i[r][1].apply(e.element,n)}},hasScroll:function(t,n){if("hidden"===e(t).css("overflow"))return!1;var r=n&&"left"===n?"scrollLeft":"scrollTop",i=!1;if(t[r]>0)return!0;t[r]=1;i=t[r]>0;t[r]=0;return i}})})(t)},{jquery:void 0}],55:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("./widget");(function(e){var t=!1;e(document).mouseup(function(){t=!1});e.widget("ui.mouse",{version:"1.10.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(n){if(!0===e.data(n.target,t.widgetName+".preventClickEvent")){e.removeData(n.target,t.widgetName+".preventClickEvent");n.stopImmediatePropagation();return!1}});this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);this._mouseMoveDelegate&&e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(n){if(!t){this._mouseStarted&&this._mouseUp(n);this._mouseDownEvent=n;var r=this,i=1===n.which,o="string"==typeof this.options.cancel&&n.target.nodeName?e(n.target).closest(this.options.cancel).length:!1;if(!i||o||!this._mouseCapture(n))return!0;this.mouseDelayMet=!this.options.delay;this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(n)&&this._mouseDelayMet(n)){this._mouseStarted=this._mouseStart(n)!==!1;if(!this._mouseStarted){n.preventDefault();return!0}}!0===e.data(n.target,this.widgetName+".preventClickEvent")&&e.removeData(n.target,this.widgetName+".preventClickEvent");this._mouseMoveDelegate=function(e){return r._mouseMove(e)};this._mouseUpDelegate=function(e){return r._mouseUp(e)};e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);n.preventDefault();t=!0;return!0}},_mouseMove:function(t){if(e.ui.ie&&(!document.documentMode||document.documentMode<9)&&!t.button)return this._mouseUp(t);if(this._mouseStarted){this._mouseDrag(t);return t.preventDefault()}if(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)){this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1;this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)}return!this._mouseStarted},_mouseUp:function(t){e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=!1;t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0);this._mouseStop(t)}return!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(t)},{"./widget":57,jquery:void 0}],56:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("./core");e("./mouse");e("./widget");(function(e){function t(e,t,n){return e>t&&t+n>e}function n(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))}e.widget("ui.sortable",e.ui.mouse,{version:"1.10.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var e=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?"x"===e.axis||n(this.items[0].item):!1;this.offset=this.element.offset();this._mouseInit();this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,n){if("disabled"===t){this.options[t]=n;this.widget().toggleClass("ui-sortable-disabled",!!n)}else e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,n){var r=null,i=!1,o=this;if(this.reverting)return!1;if(this.options.disabled||"static"===this.options.type)return!1;this._refreshItems(t);e(t.target).parents().each(function(){if(e.data(this,o.widgetName+"-item")===o){r=e(this);return!1}});e.data(t.target,o.widgetName+"-item")===o&&(r=e(t.target));if(!r)return!1;if(this.options.handle&&!n){e(this.options.handle,r).find("*").addBack().each(function(){this===t.target&&(i=!0)});if(!i)return!1}this.currentItem=r;this._removeCurrentsFromItems();return!0},_mouseStart:function(t,n,r){var i,o,s=this.options;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(t);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(t);this.originalPageX=t.pageX;this.originalPageY=t.pageY;s.cursorAt&&this._adjustOffsetFromHelper(s.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!==this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();s.containment&&this._setContainment();if(s.cursor&&"auto"!==s.cursor){o=this.document.find("body");this.storedCursor=o.css("cursor");o.css("cursor",s.cursor);this.storedStylesheet=e("<style>*{ cursor: "+s.cursor+" !important; }</style>").appendTo(o)}if(s.opacity){this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity"));this.helper.css("opacity",s.opacity)}if(s.zIndex){this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex"));this.helper.css("zIndex",s.zIndex)}this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset());this._trigger("start",t,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",t,this._uiHash(this));e.ui.ddmanager&&(e.ui.ddmanager.current=this);e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t);this.dragging=!0;this.helper.addClass("ui-sortable-helper");this._mouseDrag(t);return!0},_mouseDrag:function(t){var n,r,i,o,s=this.options,a=!1;this.position=this._generatePosition(t);this.positionAbs=this._convertPositionTo("absolute");this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){if(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName){this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<s.scrollSensitivity?this.scrollParent[0].scrollTop=a=this.scrollParent[0].scrollTop+s.scrollSpeed:t.pageY-this.overflowOffset.top<s.scrollSensitivity&&(this.scrollParent[0].scrollTop=a=this.scrollParent[0].scrollTop-s.scrollSpeed);this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<s.scrollSensitivity?this.scrollParent[0].scrollLeft=a=this.scrollParent[0].scrollLeft+s.scrollSpeed:t.pageX-this.overflowOffset.left<s.scrollSensitivity&&(this.scrollParent[0].scrollLeft=a=this.scrollParent[0].scrollLeft-s.scrollSpeed)}else{t.pageY-e(document).scrollTop()<s.scrollSensitivity?a=e(document).scrollTop(e(document).scrollTop()-s.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<s.scrollSensitivity&&(a=e(document).scrollTop(e(document).scrollTop()+s.scrollSpeed));t.pageX-e(document).scrollLeft()<s.scrollSensitivity?a=e(document).scrollLeft(e(document).scrollLeft()-s.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<s.scrollSensitivity&&(a=e(document).scrollLeft(e(document).scrollLeft()+s.scrollSpeed))}a!==!1&&e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)}this.positionAbs=this._convertPositionTo("absolute");this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px");this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px");for(n=this.items.length-1;n>=0;n--){r=this.items[n];i=r.item[0];o=this._intersectsWithPointer(r);if(o&&r.instance===this.currentContainer&&i!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==i&&!e.contains(this.placeholder[0],i)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],i):!0)){this.direction=1===o?"down":"up";if("pointer"!==this.options.tolerance&&!this._intersectsWithSides(r))break;this._rearrange(t,r);this._trigger("change",t,this._uiHash());break}}this._contactContainers(t);e.ui.ddmanager&&e.ui.ddmanager.drag(this,t);this._trigger("sort",t,this._uiHash());this.lastPositionAbs=this.positionAbs;return!1},_mouseStop:function(t,n){if(t){e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t);if(this.options.revert){var r=this,i=this.placeholder.offset(),o=this.options.axis,s={};o&&"x"!==o||(s.left=i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft));o&&"y"!==o||(s.top=i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop));this.reverting=!0;e(this.helper).animate(s,parseInt(this.options.revert,10)||500,function(){r._clear(t)})}else this._clear(t,n);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null});"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--){this.containers[t]._trigger("deactivate",null,this._uiHash(this));if(this.containers[t].containerCache.over){this.containers[t]._trigger("out",null,this._uiHash(this));this.containers[t].containerCache.over=0}}}if(this.placeholder){this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove();e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null});this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)}return this},serialize:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];t=t||{};e(n).each(function(){var n=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);n&&r.push((t.key||n[1]+"[]")+"="+(t.key&&t.expression?n[1]:n[2]))});!r.length&&t.key&&r.push(t.key+"=");return r.join("&")},toArray:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];t=t||{};n.each(function(){r.push(e(t.item||this).attr(t.attribute||"id")||"")});return r},_intersectsWith:function(e){var t=this.positionAbs.left,n=t+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,o=e.left,s=o+e.width,a=e.top,l=a+e.height,u=this.offset.click.top,p=this.offset.click.left,c="x"===this.options.axis||r+u>a&&l>r+u,d="y"===this.options.axis||t+p>o&&s>t+p,f=c&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?f:o<t+this.helperProportions.width/2&&n-this.helperProportions.width/2<s&&a<r+this.helperProportions.height/2&&i-this.helperProportions.height/2<l},_intersectsWithPointer:function(e){var n="x"===this.options.axis||t(this.positionAbs.top+this.offset.click.top,e.top,e.height),r="y"===this.options.axis||t(this.positionAbs.left+this.offset.click.left,e.left,e.width),i=n&&r,o=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return i?this.floating?s&&"right"===s||"down"===o?2:1:o&&("down"===o?2:1):!1},_intersectsWithSides:function(e){var n=t(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),r=t(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),i=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return this.floating&&o?"right"===o&&r||"left"===o&&!r:i&&("down"===i&&n||"up"===i&&!n)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){this._refreshItems(e);this.refreshPositions();return this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){function n(){a.push(this)}var r,i,o,s,a=[],l=[],u=this._connectWith();if(u&&t)for(r=u.length-1;r>=0;r--){o=e(u[r]);for(i=o.length-1;i>=0;i--){s=e.data(o[i],this.widgetFullName);s&&s!==this&&!s.options.disabled&&l.push([e.isFunction(s.options.items)?s.options.items.call(s.element):e(s.options.items,s.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),s])}}l.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(r=l.length-1;r>=0;r--)l[r][0].each(n);return e(a)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var n=0;n<t.length;n++)if(t[n]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[];this.containers=[this];var n,r,i,o,s,a,l,u,p=this.items,c=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(n=d.length-1;n>=0;n--){i=e(d[n]);for(r=i.length-1;r>=0;r--){o=e.data(i[r],this.widgetFullName);if(o&&o!==this&&!o.options.disabled){c.push([e.isFunction(o.options.items)?o.options.items.call(o.element[0],t,{item:this.currentItem}):e(o.options.items,o.element),o]);this.containers.push(o)}}}for(n=c.length-1;n>=0;n--){s=c[n][1];a=c[n][0];for(r=0,u=a.length;u>r;r++){l=e(a[r]);l.data(this.widgetName+"-item",s);p.push({item:l,instance:s,width:0,height:0,left:0,top:0})}}},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var n,r,i,o;for(n=this.items.length-1;n>=0;n--){r=this.items[n];if(r.instance===this.currentContainer||!this.currentContainer||r.item[0]===this.currentItem[0]){i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item;if(!t){r.width=i.outerWidth();r.height=i.outerHeight()}o=i.offset();r.left=o.left;r.top=o.top}}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(n=this.containers.length-1;n>=0;n--){o=this.containers[n].element.offset();this.containers[n].containerCache.left=o.left;this.containers[n].containerCache.top=o.top;this.containers[n].containerCache.width=this.containers[n].element.outerWidth();this.containers[n].containerCache.height=this.containers[n].element.outerHeight()}return this},_createPlaceholder:function(t){t=t||this;var n,r=t.options;if(!r.placeholder||r.placeholder.constructor===String){n=r.placeholder;r.placeholder={element:function(){var r=t.currentItem[0].nodeName.toLowerCase(),i=e("<"+r+">",t.document[0]).addClass(n||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");"tr"===r?t.currentItem.children().each(function(){e("<td> </td>",t.document[0]).attr("colspan",e(this).attr("colspan")||1).appendTo(i)}):"img"===r&&i.attr("src",t.currentItem.attr("src"));n||i.css("visibility","hidden");return i},update:function(e,i){if(!n||r.forcePlaceholderSize){i.height()||i.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10));i.width()||i.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10))}}}}t.placeholder=e(r.placeholder.element.call(t.element,t.currentItem));t.currentItem.after(t.placeholder);r.placeholder.update(t,t.placeholder)},_contactContainers:function(r){var i,o,s,a,l,u,p,c,d,f,h=null,g=null;for(i=this.containers.length-1;i>=0;i--)if(!e.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(h&&e.contains(this.containers[i].element[0],h.element[0]))continue;h=this.containers[i];g=i}else if(this.containers[i].containerCache.over){this.containers[i]._trigger("out",r,this._uiHash(this));this.containers[i].containerCache.over=0}if(h)if(1===this.containers.length){if(!this.containers[g].containerCache.over){this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}}else{s=1e4;a=null;f=h.floating||n(this.currentItem);l=f?"left":"top";u=f?"width":"height";p=this.positionAbs[l]+this.offset.click[l];for(o=this.items.length-1;o>=0;o--)if(e.contains(this.containers[g].element[0],this.items[o].item[0])&&this.items[o].item[0]!==this.currentItem[0]&&(!f||t(this.positionAbs.top+this.offset.click.top,this.items[o].top,this.items[o].height))){c=this.items[o].item.offset()[l];d=!1;if(Math.abs(c-p)>Math.abs(c+this.items[o][u]-p)){d=!0;c+=this.items[o][u]}if(Math.abs(c-p)<s){s=Math.abs(c-p);a=this.items[o];this.direction=d?"up":"down"}}if(!a&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[g])return;a?this._rearrange(r,a,null,!0):this._rearrange(r,null,this.containers[g].element,!0);this._trigger("change",r,this._uiHash());this.containers[g]._trigger("change",r,this._uiHash(this));this.currentContainer=this.containers[g];this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t,this.currentItem])):"clone"===n.helper?this.currentItem.clone():this.currentItem;r.parents("body").length||e("parent"!==n.appendTo?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]);r[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")});(!r[0].style.width||n.forceHelperSize)&&r.width(this.currentItem.width());(!r[0].style.height||n.forceHelperSize)&&r.height(this.currentItem.height());return r},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" "));e.isArray(t)&&(t={left:+t[0],top:+t[1]||0});"left"in t&&(this.offset.click.left=t.left+this.margins.left);"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left);"top"in t&&(this.offset.click.top=t.top+this.margins.top);"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();if("absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])){t.left+=this.scrollParent.scrollLeft();t.top+=this.scrollParent.scrollTop()}(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0});return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,n,r,i=this.options;"parent"===i.containment&&(i.containment=this.helper[0].parentNode);("document"===i.containment||"window"===i.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e("document"===i.containment?document:window).width()-this.helperProportions.width-this.margins.left,(e("document"===i.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]);if(!/^(document|window|parent)$/.test(i.containment)){t=e(i.containment)[0];n=e(i.containment).offset();r="hidden"!==e(t).css("overflow");this.containment=[n.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,n.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,n.left+(r?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,n.top+(r?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(t,n){n||(n=this.position);var r="absolute"===t?1:-1,i="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i=this.options,o=t.pageX,s=t.pageY,a="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=/(html|body)/i.test(a[0].tagName);"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset());if(this.originalPosition){if(this.containment){t.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left);t.pageY-this.offset.click.top<this.containment[1]&&(s=this.containment[1]+this.offset.click.top);t.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left);t.pageY-this.offset.click.top>this.containment[3]&&(s=this.containment[3]+this.offset.click.top)}if(i.grid){n=this.originalPageY+Math.round((s-this.originalPageY)/i.grid[1])*i.grid[1];s=this.containment?n-this.offset.click.top>=this.containment[1]&&n-this.offset.click.top<=this.containment[3]?n:n-this.offset.click.top>=this.containment[1]?n-i.grid[1]:n+i.grid[1]:n;r=this.originalPageX+Math.round((o-this.originalPageX)/i.grid[0])*i.grid[0];o=this.containment?r-this.offset.click.left>=this.containment[0]&&r-this.offset.click.left<=this.containment[2]?r:r-this.offset.click.left>=this.containment[0]?r-i.grid[0]:r+i.grid[0]:r}}return{top:s-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():l?0:a.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():l?0:a.scrollLeft())}},_rearrange:function(e,t,n,r){n?n[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i===this.counter&&this.refreshPositions(!r)})},_clear:function(e,t){function n(e,t,n){return function(r){n._trigger(e,r,t._uiHash(t))}}this.reverting=!1;var r,i=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(r in this._storedCSS)("auto"===this._storedCSS[r]||"static"===this._storedCSS[r])&&(this._storedCSS[r]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!t&&i.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))});!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||t||i.push(function(e){this._trigger("update",e,this._uiHash())});if(this!==this.currentContainer&&!t){i.push(function(e){this._trigger("remove",e,this._uiHash())});i.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer));i.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))}for(r=this.containers.length-1;r>=0;r--){t||i.push(n("deactivate",this,this.containers[r]));if(this.containers[r].containerCache.over){i.push(n("out",this,this.containers[r]));this.containers[r].containerCache.over=0}}if(this.storedCursor){this.document.find("body").css("cursor",this.storedCursor);this.storedStylesheet.remove()}this._storedOpacity&&this.helper.css("opacity",this._storedOpacity);this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex);this.dragging=!1;if(this.cancelHelperRemoval){if(!t){this._trigger("beforeStop",e,this._uiHash());for(r=0;r<i.length;r++)i[r].call(this,e);this._trigger("stop",e,this._uiHash())}this.fromOutside=!1;return!1}t||this._trigger("beforeStop",e,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!==this.currentItem[0]&&this.helper.remove();this.helper=null;if(!t){for(r=0;r<i.length;r++)i[r].call(this,e);this._trigger("stop",e,this._uiHash())}this.fromOutside=!1;return!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var n=t||this;return{helper:n.helper,placeholder:n.placeholder||e([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:t?t.element:null}}})})(t)},{"./core":54,"./mouse":55,"./widget":57,jquery:void 0}],57:[function(e){var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();(function(e,t){var n=0,r=Array.prototype.slice,i=e.cleanData;e.cleanData=function(t){for(var n,r=0;null!=(n=t[r]);r++)try{e(n).triggerHandler("remove")}catch(o){}i(t)};e.widget=function(t,n,r){var i,o,s,a,l={},u=t.split(".")[0];t=t.split(".")[1];i=u+"-"+t;if(!r){r=n;n=e.Widget}e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)};e[u]=e[u]||{};o=e[u][t];s=e[u][t]=function(e,t){if(!this._createWidget)return new s(e,t);arguments.length&&this._createWidget(e,t);return void 0};e.extend(s,o,{version:r.version,_proto:e.extend({},r),_childConstructors:[]});a=new n;a.options=e.widget.extend({},a.options);e.each(r,function(t,r){l[t]=e.isFunction(r)?function(){var e=function(){return n.prototype[t].apply(this,arguments)},i=function(e){return n.prototype[t].apply(this,e)};return function(){var t,n=this._super,o=this._superApply;this._super=e;this._superApply=i;t=r.apply(this,arguments);this._super=n;this._superApply=o;return t}}():r});s.prototype=e.widget.extend(a,{widgetEventPrefix:o?a.widgetEventPrefix||t:t},l,{constructor:s,namespace:u,widgetName:t,widgetFullName:i});if(o){e.each(o._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,s,n._proto)});delete o._childConstructors}else n._childConstructors.push(s);e.widget.bridge(t,s)};e.widget.extend=function(n){for(var i,o,s=r.call(arguments,1),a=0,l=s.length;l>a;a++)for(i in s[a]){o=s[a][i];s[a].hasOwnProperty(i)&&o!==t&&(n[i]=e.isPlainObject(o)?e.isPlainObject(n[i])?e.widget.extend({},n[i],o):e.widget.extend({},o):o)}return n};e.widget.bridge=function(n,i){var o=i.prototype.widgetFullName||n;e.fn[n]=function(s){var a="string"==typeof s,l=r.call(arguments,1),u=this;s=!a&&l.length?e.widget.extend.apply(null,[s].concat(l)):s;this.each(a?function(){var r,i=e.data(this,o);if(!i)return e.error("cannot call methods on "+n+" prior to initialization; attempted to call method '"+s+"'");if(!e.isFunction(i[s])||"_"===s.charAt(0))return e.error("no such method '"+s+"' for "+n+" widget instance");r=i[s].apply(i,l);if(r!==i&&r!==t){u=r&&r.jquery?u.pushStack(r.get()):r;return!1}}:function(){var t=e.data(this,o);t?t.option(s||{})._init():e.data(this,o,new i(s,this))});return u}};e.Widget=function(){};e.Widget._childConstructors=[];e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,r){r=e(r||this.defaultElement||this)[0];this.element=e(r);this.uuid=n++;this.eventNamespace="."+this.widgetName+this.uuid;this.options=e.widget.extend({},this.options,this._getCreateOptions(),t);this.bindings=e();this.hoverable=e();this.focusable=e();if(r!==this){e.data(r,this.widgetFullName,this);this._on(!0,this.element,{remove:function(e){e.target===r&&this.destroy()}});this.document=e(r.style?r.ownerDocument:r.document||r);this.window=e(this.document[0].defaultView||this.document[0].parentWindow)}this._create();this._trigger("create",null,this._getCreateEventData());this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy();this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName));this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled");this.bindings.unbind(this.eventNamespace);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(n,r){var i,o,s,a=n;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof n){a={};i=n.split(".");n=i.shift();if(i.length){o=a[n]=e.widget.extend({},this.options[n]);for(s=0;s<i.length-1;s++){o[i[s]]=o[i[s]]||{};o=o[i[s]]}n=i.pop();if(1===arguments.length)return o[n]===t?null:o[n];o[n]=r}else{if(1===arguments.length)return this.options[n]===t?null:this.options[n];a[n]=r}}this._setOptions(a);return this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){this.options[e]=t;if("disabled"===e){this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t);this.hoverable.removeClass("ui-state-hover");
this.focusable.removeClass("ui-state-focus")}return this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(t,n,r){var i,o=this;if("boolean"!=typeof t){r=n;n=t;t=!1}if(r){n=i=e(n);this.bindings=this.bindings.add(n)}else{r=n;n=this.element;i=this.widget()}e.each(r,function(r,s){function a(){return t||o.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof s?o[s]:s).apply(o,arguments):void 0}"string"!=typeof s&&(a.guid=s.guid=s.guid||a.guid||e.guid++);var l=r.match(/^(\w+)\s*(.*)$/),u=l[1]+o.eventNamespace,p=l[2];p?i.delegate(p,u,a):n.bind(u,a)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace;e.unbind(t).undelegate(t)},_delay:function(e,t){function n(){return("string"==typeof e?r[e]:e).apply(r,arguments)}var r=this;return setTimeout(n,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t);this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t);this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,n,r){var i,o,s=this.options[t];r=r||{};n=e.Event(n);n.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase();n.target=this.element[0];o=n.originalEvent;if(o)for(i in o)i in n||(n[i]=o[i]);this.element.trigger(n,r);return!(e.isFunction(s)&&s.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}};e.each({show:"fadeIn",hide:"fadeOut"},function(t,n){e.Widget.prototype["_"+t]=function(r,i,o){"string"==typeof i&&(i={effect:i});var s,a=i?i===!0||"number"==typeof i?n:i.effect||n:t;i=i||{};"number"==typeof i&&(i={duration:i});s=!e.isEmptyObject(i);i.complete=o;i.delay&&r.delay(i.delay);s&&e.effects&&e.effects.effect[a]?r[t](i):a!==t&&r[a]?r[a](i.duration,i.easing,o):r.queue(function(n){e(this)[t]();o&&o.call(r[0]);n()})}})})(t)},{jquery:void 0}],58:[function(t,n,r){(function(){var i;i=function(i){return"object"==typeof r&&"object"==typeof n?i(function(){try{return t("jquery")}catch(e){return window.jQuery}}()):"function"==typeof e&&e.amd?e(["jquery"],i):i(jQuery)};i(function(e){return e.pivotUtilities.d3_renderers={Treemap:function(t,n){var r,i,o,s,a,l,u,p,c,d,f,h,g,m;o={localeStrings:{}};n=e.extend(o,n);l=e("<div style='width: 100%; height: 100%;'>");p={name:"All",children:[]};r=function(e,t,n){var i,o,s,a,l,u;if(0!==t.length){null==e.children&&(e.children=[]);s=t.shift();u=e.children;for(a=0,l=u.length;l>a;a++){i=u[a];if(i.name===s){r(i,t,n);return}}o={name:s};r(o,t,n);return e.children.push(o)}e.value=n};m=t.getRowKeys();for(h=0,g=m.length;g>h;h++){u=m[h];d=t.getAggregator(u,[]).value();null!=d&&r(p,u,d)}i=d3.scale.category10();f=e(window).width()/1.4;s=e(window).height()/1.4;a=10;c=d3.layout.treemap().size([f,s]).sticky(!0).value(function(e){return e.size});d3.select(l[0]).append("div").style("position","relative").style("width",f+2*a+"px").style("height",s+2*a+"px").style("left",a+"px").style("top",a+"px").datum(p).selectAll(".node").data(c.padding([15,0,0,0]).value(function(e){return e.value}).nodes).enter().append("div").attr("class","node").style("background",function(e){return null!=e.children?"lightgrey":i(e.name)}).text(function(e){return e.name}).call(function(){this.style("left",function(e){return e.x+"px"}).style("top",function(e){return e.y+"px"}).style("width",function(e){return Math.max(0,e.dx-1)+"px"}).style("height",function(e){return Math.max(0,e.dy-1)+"px"})});return l}}})}).call(this)},{jquery:void 0}],59:[function(t,n,r){(function(){var i;i=function(i){return"object"==typeof r&&"object"==typeof n?i(function(){try{return t("jquery")}catch(e){return window.jQuery}}()):"function"==typeof e&&e.amd?e(["jquery"],i):i(jQuery)};i(function(e){var t;t=function(t,n){return function(r,i){var o,s,a,l,u,p,c,d,f,h,g,m,E,v,x,y,N,I,A,T,L,S,C,b,R;p={localeStrings:{vs:"vs",by:"by"}};i=e.extend(p,i);N=r.getRowKeys();0===N.length&&N.push([]);a=r.getColKeys();0===a.length&&a.push([]);h=function(){var e,t,n;n=[];for(e=0,t=N.length;t>e;e++){d=N[e];n.push(d.join("-"))}return n}();h.unshift("");m=0;l=[h];for(S=0,b=a.length;b>S;S++){s=a[S];x=[s.join("-")];m+=x[0].length;for(C=0,R=N.length;R>C;C++){y=N[C];o=r.getAggregator(y,s);x.push(null!=o.value()?o.value():null)}l.push(x)}I=T=r.aggregatorName+(r.valAttrs.length?"("+r.valAttrs.join(", ")+")":"");f=r.colAttrs.join("-");""!==f&&(I+=" "+i.localeStrings.vs+" "+f);c=r.rowAttrs.join("-");""!==c&&(I+=" "+i.localeStrings.by+" "+c);E={width:e(window).width()/1.4,height:e(window).height()/1.4,title:I,hAxis:{title:f,slantedText:m>50},vAxis:{title:T}};2===l[0].length&&""===l[0][1]&&(E.legend={position:"none"});for(g in n){A=n[g];E[g]=A}u=google.visualization.arrayToDataTable(l);v=e("<div style='width: 100%; height: 100%;'>");L=new google.visualization.ChartWrapper({dataTable:u,chartType:t,options:E});L.draw(v[0]);v.bind("dblclick",function(){var e;e=new google.visualization.ChartEditor;google.visualization.events.addListener(e,"ok",function(){return e.getChartWrapper().draw(v[0])});return e.openDialog(L)});return v}};return e.pivotUtilities.gchart_renderers={"Line Chart":t("LineChart"),"Bar Chart":t("ColumnChart"),"Stacked Bar Chart":t("ColumnChart",{isStacked:!0}),"Area Chart":t("AreaChart",{isStacked:!0})}})}).call(this)},{jquery:void 0}],60:[function(t,n,r){(function(){var i,o=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1},s=[].slice,a=function(e,t){return function(){return e.apply(t,arguments)}},l={}.hasOwnProperty;i=function(i){return"object"==typeof r&&"object"==typeof n?i(function(){try{return t("jquery")}catch(e){return window.jQuery}}()):"function"==typeof e&&e.amd?e(["jquery"],i):i(jQuery)};i(function(e){var t,n,r,i,u,p,c,d,f,h,g,m,E,v,x,y;n=function(e,t,n){var r,i,o,s;e+="";i=e.split(".");o=i[0];s=i.length>1?n+i[1]:"";r=/(\d+)(\d{3})/;for(;r.test(o);)o=o.replace(r,"$1"+t+"$2");return o+s};h=function(t){var r;r={digitsAfterDecimal:2,scaler:1,thousandsSep:",",decimalSep:".",prefix:"",suffix:"",showZero:!1};t=e.extend(r,t);return function(e){var r;if(isNaN(e)||!isFinite(e))return"";if(0===e&&!t.showZero)return"";r=n((t.scaler*e).toFixed(t.digitsAfterDecimal),t.thousandsSep,t.decimalSep);return""+t.prefix+r+t.suffix}};E=h();v=h({digitsAfterDecimal:0});x=h({digitsAfterDecimal:1,scaler:100,suffix:"%"});r={count:function(e){null==e&&(e=v);return function(){return function(){return{count:0,push:function(){return this.count++},value:function(){return this.count},format:e}}}},countUnique:function(e){null==e&&(e=v);return function(t){var n;n=t[0];return function(){return{uniq:[],push:function(e){var t;return t=e[n],o.call(this.uniq,t)<0?this.uniq.push(e[n]):void 0},value:function(){return this.uniq.length},format:e,numInputs:null!=n?0:1}}}},listUnique:function(e){return function(t){var n;n=t[0];return function(){return{uniq:[],push:function(e){var t;return t=e[n],o.call(this.uniq,t)<0?this.uniq.push(e[n]):void 0},value:function(){return this.uniq.join(e)},format:function(e){return e},numInputs:null!=n?0:1}}}},sum:function(e){null==e&&(e=E);return function(t){var n;n=t[0];return function(){return{sum:0,push:function(e){return isNaN(parseFloat(e[n]))?void 0:this.sum+=parseFloat(e[n])},value:function(){return this.sum},format:e,numInputs:null!=n?0:1}}}},average:function(e){null==e&&(e=E);return function(t){var n;n=t[0];return function(){return{sum:0,len:0,push:function(e){if(!isNaN(parseFloat(e[n]))){this.sum+=parseFloat(e[n]);return this.len++}},value:function(){return this.sum/this.len},format:e,numInputs:null!=n?0:1}}}},sumOverSum:function(e){null==e&&(e=E);return function(t){var n,r;r=t[0],n=t[1];return function(){return{sumNum:0,sumDenom:0,push:function(e){isNaN(parseFloat(e[r]))||(this.sumNum+=parseFloat(e[r]));return isNaN(parseFloat(e[n]))?void 0:this.sumDenom+=parseFloat(e[n])},value:function(){return this.sumNum/this.sumDenom},format:e,numInputs:null!=r&&null!=n?0:2}}}},sumOverSumBound80:function(e,t){null==e&&(e=!0);null==t&&(t=E);return function(n){var r,i;i=n[0],r=n[1];return function(){return{sumNum:0,sumDenom:0,push:function(e){isNaN(parseFloat(e[i]))||(this.sumNum+=parseFloat(e[i]));return isNaN(parseFloat(e[r]))?void 0:this.sumDenom+=parseFloat(e[r])},value:function(){var t;t=e?1:-1;return(.821187207574908/this.sumDenom+this.sumNum/this.sumDenom+1.2815515655446004*t*Math.sqrt(.410593603787454/(this.sumDenom*this.sumDenom)+this.sumNum*(1-this.sumNum/this.sumDenom)/(this.sumDenom*this.sumDenom)))/(1+1.642374415149816/this.sumDenom)},format:t,numInputs:null!=i&&null!=r?0:2}}}},fractionOf:function(e,t,n){null==t&&(t="total");null==n&&(n=x);return function(){var r;r=1<=arguments.length?s.call(arguments,0):[];return function(i,o,s){return{selector:{total:[[],[]],row:[o,[]],col:[[],s]}[t],inner:e.apply(null,r)(i,o,s),push:function(e){return this.inner.push(e)},format:n,value:function(){return this.inner.value()/i.getAggregator.apply(i,this.selector).inner.value()},numInputs:e.apply(null,r)().numInputs}}}}};i=function(e){return{Count:e.count(v),"Count Unique Values":e.countUnique(v),"List Unique Values":e.listUnique(", "),Sum:e.sum(E),"Integer Sum":e.sum(v),Average:e.average(E),"Sum over Sum":e.sumOverSum(E),"80% Upper Bound":e.sumOverSumBound80(!0,E),"80% Lower Bound":e.sumOverSumBound80(!1,E),"Sum as Fraction of Total":e.fractionOf(e.sum(),"total",x),"Sum as Fraction of Rows":e.fractionOf(e.sum(),"row",x),"Sum as Fraction of Columns":e.fractionOf(e.sum(),"col",x),"Count as Fraction of Total":e.fractionOf(e.count(),"total",x),"Count as Fraction of Rows":e.fractionOf(e.count(),"row",x),"Count as Fraction of Columns":e.fractionOf(e.count(),"col",x)}}(r);m={Table:function(e,t){return g(e,t)},"Table Barchart":function(t,n){return e(g(t,n)).barchart()},Heatmap:function(t,n){return e(g(t,n)).heatmap()},"Row Heatmap":function(t,n){return e(g(t,n)).heatmap("rowheatmap")},"Col Heatmap":function(t,n){return e(g(t,n)).heatmap("colheatmap")}};c={en:{aggregators:i,renderers:m,localeStrings:{renderError:"An error occurred rendering the PivotTable results.",computeError:"An error occurred computing the PivotTable results.",uiRenderError:"An error occurred rendering the PivotTable UI.",selectAll:"Select All",selectNone:"Select None",tooMany:"(too many to list)",filterResults:"Filter results",totals:"Totals",vs:"vs",by:"by"}}};d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];y=function(e){return("0"+e).substr(-2,2)};p={bin:function(e,t){return function(n){return n[e]-n[e]%t}},dateFormat:function(e,t,n,r){null==n&&(n=d);null==r&&(r=u);return function(i){var o;o=new Date(Date.parse(i[e]));return isNaN(o)?"":t.replace(/%(.)/g,function(e,t){switch(t){case"y":return o.getFullYear();case"m":return y(o.getMonth()+1);case"n":return n[o.getMonth()];case"d":return y(o.getDate());case"w":return r[o.getDay()];case"x":return o.getDay();case"H":return y(o.getHours());case"M":return y(o.getMinutes());case"S":return y(o.getSeconds());default:return"%"+t}})}}};f=function(){return function(e,t){var n,r,i,o,s,a,l;a=/(\d+)|(\D+)/g;s=/\d/;l=/^0/;if("number"==typeof e||"number"==typeof t)return isNaN(e)?1:isNaN(t)?-1:e-t;n=String(e).toLowerCase();i=String(t).toLowerCase();if(n===i)return 0;if(!s.test(n)||!s.test(i))return n>i?1:-1;n=n.match(a);i=i.match(a);for(;n.length&&i.length;){r=n.shift();o=i.shift();if(r!==o)return s.test(r)&&s.test(o)?r.replace(l,".0")-o.replace(l,".0"):r>o?1:-1}return n.length-i.length}}(this);e.pivotUtilities={aggregatorTemplates:r,aggregators:i,renderers:m,derivers:p,locales:c,naturalSort:f,numberFormat:h};t=function(){function t(e,n){this.getAggregator=a(this.getAggregator,this);this.getRowKeys=a(this.getRowKeys,this);this.getColKeys=a(this.getColKeys,this);this.sortKeys=a(this.sortKeys,this);this.arrSort=a(this.arrSort,this);this.natSort=a(this.natSort,this);this.aggregator=n.aggregator;this.aggregatorName=n.aggregatorName;this.colAttrs=n.cols;this.rowAttrs=n.rows;this.valAttrs=n.vals;this.tree={};this.rowKeys=[];this.colKeys=[];this.rowTotals={};this.colTotals={};this.allTotal=this.aggregator(this,[],[]);this.sorted=!1;t.forEachRecord(e,n.derivedAttributes,function(e){return function(t){return n.filter(t)?e.processRecord(t):void 0}}(this))}t.forEachRecord=function(t,n,r){var i,o,s,a,u,p,c,d,f,h,g,m;i=e.isEmptyObject(n)?r:function(e){var t,i,o;for(t in n){i=n[t];e[t]=null!=(o=i(e))?o:e[t]}return r(e)};if(e.isFunction(t))return t(i);if(e.isArray(t)){if(e.isArray(t[0])){g=[];for(s in t)if(l.call(t,s)){o=t[s];if(s>0){p={};h=t[0];for(a in h)if(l.call(h,a)){u=h[a];p[u]=o[a]}g.push(i(p))}}return g}m=[];for(d=0,f=t.length;f>d;d++){p=t[d];m.push(i(p))}return m}if(t instanceof jQuery){c=[];e("thead > tr > th",t).each(function(){return c.push(e(this).text())});return e("tbody > tr",t).each(function(){p={};e("td",this).each(function(t){return p[c[t]]=e(this).text()});return i(p)})}throw new Error("unknown input format")};t.convertToArray=function(e){var n;n=[];t.forEachRecord(e,{},function(e){return n.push(e)});return n};t.prototype.natSort=function(e,t){return f(e,t)};t.prototype.arrSort=function(e,t){return this.natSort(e.join(),t.join())};t.prototype.sortKeys=function(){if(!this.sorted){this.rowKeys.sort(this.arrSort);this.colKeys.sort(this.arrSort)}return this.sorted=!0};t.prototype.getColKeys=function(){this.sortKeys();return this.colKeys};t.prototype.getRowKeys=function(){this.sortKeys();return this.rowKeys};t.prototype.processRecord=function(e){var t,n,r,i,o,s,a,l,u,p,c,d,f;t=[];i=[];p=this.colAttrs;for(s=0,l=p.length;l>s;s++){o=p[s];t.push(null!=(c=e[o])?c:"null")}d=this.rowAttrs;for(a=0,u=d.length;u>a;a++){o=d[a];i.push(null!=(f=e[o])?f:"null")}r=i.join(String.fromCharCode(0));n=t.join(String.fromCharCode(0));this.allTotal.push(e);if(0!==i.length){if(!this.rowTotals[r]){this.rowKeys.push(i);this.rowTotals[r]=this.aggregator(this,i,[])}this.rowTotals[r].push(e)}if(0!==t.length){if(!this.colTotals[n]){this.colKeys.push(t);this.colTotals[n]=this.aggregator(this,[],t)}this.colTotals[n].push(e)}if(0!==t.length&&0!==i.length){this.tree[r]||(this.tree[r]={});this.tree[r][n]||(this.tree[r][n]=this.aggregator(this,i,t));return this.tree[r][n].push(e)}};t.prototype.getAggregator=function(e,t){var n,r,i;i=e.join(String.fromCharCode(0));r=t.join(String.fromCharCode(0));n=0===e.length&&0===t.length?this.allTotal:0===e.length?this.colTotals[r]:0===t.length?this.rowTotals[i]:this.tree[i][r];return null!=n?n:{value:function(){return null},format:function(){return""}}};return t}();g=function(t,n){var r,i,o,s,a,u,p,c,d,f,h,g,m,E,v,x,y,N,I,A,T;u={localeStrings:{totals:"Totals"}};n=e.extend(u,n);o=t.colAttrs;h=t.rowAttrs;m=t.getRowKeys();a=t.getColKeys();f=document.createElement("table");f.className="pvtTable";E=function(e,t,n){var r,i,o,s,a,l;if(0!==t){i=!0;for(s=a=0;n>=0?n>=a:a>=n;s=n>=0?++a:--a)e[t-1][s]!==e[t][s]&&(i=!1);if(i)return-1}r=0;for(;t+r<e.length;){o=!1;for(s=l=0;n>=0?n>=l:l>=n;s=n>=0?++l:--l)e[t][s]!==e[t+r][s]&&(o=!0);if(o)break;r++}return r};for(c in o)if(l.call(o,c)){i=o[c];N=document.createElement("tr");if(0===parseInt(c)&&0!==h.length){x=document.createElement("th");x.setAttribute("colspan",h.length);x.setAttribute("rowspan",o.length);N.appendChild(x)}x=document.createElement("th");x.className="pvtAxisLabel";x.textContent=i;N.appendChild(x);for(p in a)if(l.call(a,p)){s=a[p];T=E(a,parseInt(p),parseInt(c));if(-1!==T){x=document.createElement("th");x.className="pvtColLabel";x.textContent=s[c];x.setAttribute("colspan",T);parseInt(c)===o.length-1&&0!==h.length&&x.setAttribute("rowspan",2);N.appendChild(x)}}if(0===parseInt(c)){x=document.createElement("th");x.className="pvtTotalLabel";x.innerHTML=n.localeStrings.totals;x.setAttribute("rowspan",o.length+(0===h.length?0:1));N.appendChild(x)}f.appendChild(N)}if(0!==h.length){N=document.createElement("tr");for(p in h)if(l.call(h,p)){d=h[p];x=document.createElement("th");x.className="pvtAxisLabel";x.textContent=d;N.appendChild(x)}x=document.createElement("th");if(0===o.length){x.className="pvtTotalLabel";x.innerHTML=n.localeStrings.totals}N.appendChild(x);f.appendChild(N)}for(p in m)if(l.call(m,p)){g=m[p];N=document.createElement("tr");for(c in g)if(l.call(g,c)){I=g[c];T=E(m,parseInt(p),parseInt(c));if(-1!==T){x=document.createElement("th");x.className="pvtRowLabel";x.textContent=I;x.setAttribute("rowspan",T);parseInt(c)===h.length-1&&0!==o.length&&x.setAttribute("colspan",2);N.appendChild(x)}}for(c in a)if(l.call(a,c)){s=a[c];r=t.getAggregator(g,s);A=r.value();v=document.createElement("td");v.className="pvtVal row"+p+" col"+c;v.innerHTML=r.format(A);v.setAttribute("data-value",A);N.appendChild(v)}y=t.getAggregator(g,[]);A=y.value();v=document.createElement("td");v.className="pvtTotal rowTotal";v.innerHTML=y.format(A);v.setAttribute("data-value",A);v.setAttribute("data-for","row"+p);N.appendChild(v);f.appendChild(N)}N=document.createElement("tr");x=document.createElement("th");x.className="pvtTotalLabel";x.innerHTML=n.localeStrings.totals;x.setAttribute("colspan",h.length+(0===o.length?0:1));N.appendChild(x);for(c in a)if(l.call(a,c)){s=a[c];y=t.getAggregator([],s);A=y.value();v=document.createElement("td");v.className="pvtTotal colTotal";v.innerHTML=y.format(A);v.setAttribute("data-value",A);v.setAttribute("data-for","col"+c);N.appendChild(v)}y=t.getAggregator([],[]);A=y.value();v=document.createElement("td");v.className="pvtGrandTotal";v.innerHTML=y.format(A);v.setAttribute("data-value",A);N.appendChild(v);f.appendChild(N);f.setAttribute("data-numrows",m.length);f.setAttribute("data-numcols",a.length);return f};e.fn.pivot=function(n,i){var o,s,a,l,u;o={cols:[],rows:[],filter:function(){return!0},aggregator:r.count()(),aggregatorName:"Count",derivedAttributes:{},renderer:g,rendererOptions:null,localeStrings:c.en.localeStrings};i=e.extend(o,i);l=null;try{a=new t(n,i);try{l=i.renderer(a,i.rendererOptions)}catch(p){s=p;"undefined"!=typeof console&&null!==console&&console.error(s.stack);l=e("<span>").html(i.localeStrings.renderError)}}catch(p){s=p;"undefined"!=typeof console&&null!==console&&console.error(s.stack);l=e("<span>").html(i.localeStrings.computeError)}u=this[0];for(;u.hasChildNodes();)u.removeChild(u.lastChild);return this.append(l)};e.fn.pivotUI=function(n,r,i,s){var a,u,p,d,h,g,m,E,v,x,y,N,I,A,T,L,S,C,b,R,w,O,_,F,P,M,k,D,G,U,B,j,q,V,H,z,W,$,Y;null==i&&(i=!1);null==s&&(s="en");m={derivedAttributes:{},aggregators:c[s].aggregators,renderers:c[s].renderers,hiddenAttributes:[],menuLimit:200,cols:[],rows:[],vals:[],exclusions:{},unusedAttrsVertical:"auto",autoSortUnusedAttrs:!1,rendererOptions:{localeStrings:c[s].localeStrings},onRefresh:null,filter:function(){return!0},localeStrings:c[s].localeStrings};v=this.data("pivotUIOptions");I=null==v||i?e.extend(m,r):v;try{n=t.convertToArray(n);R=function(){var e,t;e=n[0];t=[];for(N in e)l.call(e,N)&&t.push(N);return t}();H=I.derivedAttributes;for(h in H)l.call(H,h)&&o.call(R,h)<0&&R.push(h);d={};for(k=0,B=R.length;B>k;k++){P=R[k];d[P]={}}t.forEachRecord(n,I.derivedAttributes,function(e){var t,n,r;r=[];for(N in e)if(l.call(e,N)){t=e[N];if(I.filter(e)){null==t&&(t="null");null==(n=d[N])[t]&&(n[t]=0);r.push(d[N][t]++)}}return r});_=e("<table cellpadding='5'>");C=e("<td>");S=e("<select class='pvtRenderer'>").appendTo(C).bind("change",function(){return T()});z=I.renderers;for(P in z)l.call(z,P)&&e("<option>").val(P).html(P).appendTo(S);g=e("<td class='pvtAxisContainer pvtUnused'>");b=function(){var e,t,n;n=[];for(e=0,t=R.length;t>e;e++){h=R[e];o.call(I.hiddenAttributes,h)<0&&n.push(h)}return n}();F=!1;if("auto"===I.unusedAttrsVertical){p=0;for(D=0,j=b.length;j>D;D++){a=b[D];p+=a.length}F=p>120}g.addClass(I.unusedAttrsVertical===!0||F?"pvtVertList":"pvtHorizList");M=function(t){var n,r,i,s,a,l,u,p,c,h,m,E,v,y,A;u=function(){var e;e=[];for(N in d[t])e.push(N);return e}();l=!1;E=e("<div>").addClass("pvtFilterBox").hide();E.append(e("<h4>").text(""+t+" ("+u.length+")"));if(u.length>I.menuLimit)E.append(e("<p>").html(I.localeStrings.tooMany));else{r=e("<p>").appendTo(E);r.append(e("<button>").html(I.localeStrings.selectAll).bind("click",function(){return E.find("input:visible").prop("checked",!0)}));r.append(e("<button>").html(I.localeStrings.selectNone).bind("click",function(){return E.find("input:visible").prop("checked",!1)}));r.append(e("<input>").addClass("pvtSearch").attr("placeholder",I.localeStrings.filterResults).bind("keyup",function(){var t;t=e(this).val().toLowerCase();return e(this).parents(".pvtFilterBox").find("label span").each(function(){var n;n=e(this).text().toLowerCase().indexOf(t);return-1!==n?e(this).parent().show():e(this).parent().hide()})}));i=e("<div>").addClass("pvtCheckContainer").appendTo(E);A=u.sort(f);for(v=0,y=A.length;y>v;v++){N=A[v];m=d[t][N];s=e("<label>");a=I.exclusions[t]?o.call(I.exclusions[t],N)>=0:!1;l||(l=a);e("<input type='checkbox' class='pvtFilter'>").attr("checked",!a).data("filter",[t,N]).appendTo(s);s.append(e("<span>").text(""+N+" ("+m+")"));i.append(e("<p>").append(s))}}h=function(){var t;t=e(E).find("[type='checkbox']").length-e(E).find("[type='checkbox']:checked").length;t>0?n.addClass("pvtFilteredAttribute"):n.removeClass("pvtFilteredAttribute");return u.length>I.menuLimit?E.toggle():E.toggle(0,T)};e("<p>").appendTo(E).append(e("<button>").text("OK").bind("click",h));p=function(t){E.css({left:t.pageX,top:t.pageY}).toggle();e(".pvtSearch").val("");return e("label").show()};c=e("<span class='pvtTriangle'>").html(" ▾").bind("click",p);n=e("<li class='axis_"+x+"'>").append(e("<span class='pvtAttr'>").text(t).data("attrName",t).append(c));l&&n.addClass("pvtFilteredAttribute");g.append(n).append(E);return n.bind("dblclick",p)};for(x in b){h=b[x];M(h)}w=e("<tr>").appendTo(_);u=e("<select class='pvtAggregator'>").bind("change",function(){return T()});W=I.aggregators;for(P in W)l.call(W,P)&&u.append(e("<option>").val(P).html(P));e("<td class='pvtVals'>").appendTo(w).append(u).append(e("<br>"));e("<td class='pvtAxisContainer pvtHorizList pvtCols'>").appendTo(w);O=e("<tr>").appendTo(_);O.append(e("<td valign='top' class='pvtAxisContainer pvtRows'>"));A=e("<td valign='top' class='pvtRendererArea'>").appendTo(O);if(I.unusedAttrsVertical===!0||F){_.find("tr:nth-child(1)").prepend(C);_.find("tr:nth-child(2)").prepend(g)}else _.prepend(e("<tr>").append(C).append(g));this.html(_);$=I.cols;for(G=0,q=$.length;q>G;G++){P=$[G];this.find(".pvtCols").append(this.find(".axis_"+b.indexOf(P)))}Y=I.rows;for(U=0,V=Y.length;V>U;U++){P=Y[U];this.find(".pvtRows").append(this.find(".axis_"+b.indexOf(P)))}null!=I.aggregatorName&&this.find(".pvtAggregator").val(I.aggregatorName);null!=I.rendererName&&this.find(".pvtRenderer").val(I.rendererName);y=!0;L=function(t){return function(){var r,i,s,a,l,p,c,d,f,h,g,m,E,v;d={derivedAttributes:I.derivedAttributes,localeStrings:I.localeStrings,rendererOptions:I.rendererOptions,cols:[],rows:[]};l=null!=(v=I.aggregators[u.val()]([])().numInputs)?v:0;h=[];t.find(".pvtRows li span.pvtAttr").each(function(){return d.rows.push(e(this).data("attrName"))});t.find(".pvtCols li span.pvtAttr").each(function(){return d.cols.push(e(this).data("attrName"))});t.find(".pvtVals select.pvtAttrDropdown").each(function(){if(0===l)return e(this).remove();l--;return""!==e(this).val()?h.push(e(this).val()):void 0});if(0!==l){c=t.find(".pvtVals");for(P=m=0;l>=0?l>m:m>l;P=l>=0?++m:--m){a=e("<select class='pvtAttrDropdown'>").append(e("<option>")).bind("change",function(){return T()});for(E=0,g=b.length;g>E;E++){r=b[E];a.append(e("<option>").val(r).text(r))}c.append(a)}}if(y){h=I.vals;x=0;t.find(".pvtVals select.pvtAttrDropdown").each(function(){e(this).val(h[x]);return x++});y=!1}d.aggregatorName=u.val();d.vals=h;d.aggregator=I.aggregators[u.val()](h);d.renderer=I.renderers[S.val()];i={};t.find("input.pvtFilter").not(":checked").each(function(){var t;t=e(this).data("filter");return null!=i[t[0]]?i[t[0]].push(t[1]):i[t[0]]=[t[1]]});d.filter=function(e){var t,n;if(!I.filter(e))return!1;for(N in i){t=i[N];if(n=""+e[N],o.call(t,n)>=0)return!1}return!0};A.pivot(n,d);p=e.extend(I,{cols:d.cols,rows:d.rows,vals:h,exclusions:i,aggregatorName:u.val(),rendererName:S.val()});t.data("pivotUIOptions",p);if(I.autoSortUnusedAttrs){s=e.pivotUtilities.naturalSort;f=t.find("td.pvtUnused.pvtAxisContainer");e(f).children("li").sort(function(t,n){return s(e(t).text(),e(n).text())}).appendTo(f)}A.css("opacity",1);return null!=I.onRefresh?I.onRefresh(p):void 0}}(this);T=function(){return function(){A.css("opacity",.5);return setTimeout(L,10)}}(this);T();this.find(".pvtAxisContainer").sortable({update:function(e,t){return null==t.sender?T():void 0},connectWith:this.find(".pvtAxisContainer"),items:"li",placeholder:"pvtPlaceholder"})}catch(K){E=K;"undefined"!=typeof console&&null!==console&&console.error(E.stack);this.html(I.localeStrings.uiRenderError)}return this};e.fn.heatmap=function(t){var n,r,i,o,s,a,l,u;null==t&&(t="heatmap");a=this.data("numrows");s=this.data("numcols");n=function(e,t,n){var r;r=function(){switch(e){case"red":return function(e){return"ff"+e+e};case"green":return function(e){return""+e+"ff"+e};case"blue":return function(e){return""+e+e+"ff"}}}();return function(e){var i,o;o=255-Math.round(255*(e-t)/(n-t));i=o.toString(16).split(".")[0];1===i.length&&(i=0+i);return r(i)}};r=function(t){return function(r,i){var o,s,a;s=function(n){return t.find(r).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?n(t,e(this)):void 0})};a=[];s(function(e){return a.push(e)});o=n(i,Math.min.apply(Math,a),Math.max.apply(Math,a));return s(function(e,t){return t.css("background-color","#"+o(e))})}}(this);switch(t){case"heatmap":r(".pvtVal","red");break;case"rowheatmap":for(i=l=0;a>=0?a>l:l>a;i=a>=0?++l:--l)r(".pvtVal.row"+i,"red");break;case"colheatmap":for(o=u=0;s>=0?s>u:u>s;o=s>=0?++u:--u)r(".pvtVal.col"+o,"red")}r(".pvtTotal.rowTotal","red");r(".pvtTotal.colTotal","red");return this};return e.fn.barchart=function(){var t,n,r,i,o;i=this.data("numrows");r=this.data("numcols");t=function(t){return function(n){var r,i,o,s;r=function(r){return t.find(n).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?r(t,e(this)):void 0})};s=[];r(function(e){return s.push(e)});i=Math.max.apply(Math,s);o=function(e){return 100*e/(1.4*i)};return r(function(t,n){var r,i;r=n.text();i=e("<div>").css({position:"relative",height:"55px"});i.append(e("<div>").css({position:"absolute",bottom:0,left:0,right:0,height:o(t)+"%","background-color":"gray"}));i.append(e("<div>").text(r).css({position:"relative","padding-left":"5px","padding-right":"5px"}));return n.css({padding:0,"padding-top":"5px","text-align":"center"}).html(i)})}}(this);for(n=o=0;i>=0?i>o:o>i;n=i>=0?++o:--o)t(".pvtVal.row"+n);t(".pvtTotal.colTotal");return this}})}).call(this)},{jquery:void 0}],61:[function(e,t){t.exports=e(7)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/node_modules/store/store.js":7}],62:[function(e,t){t.exports=e(25)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/yasgui-utils/package.json":25}],63:[function(e,t,n){arguments[4][9][0].apply(n,arguments)},{"../package.json":62,"./storage.js":64,"./svg.js":65,"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/main.js":9}],64:[function(e,t){t.exports=e(27)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-yasqe/node_modules/yasgui-utils/src/storage.js":27,store:61}],65:[function(e,t){t.exports=e(11)},{"/home/lrd900/yasgui/yasgui/node_modules/yasgui-utils/src/svg.js":11}],66:[function(e,t){t.exports={name:"yasgui-yasr",description:"Yet Another SPARQL Resultset GUI",version:"2.4.3",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasr.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasr.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1","gulp-html-replace":"^1.4.1","browserify-shim":"^3.8.1"},bugs:"https://github.com/YASGUI/YASR/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASR.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1",pivottable:"^1.2.2","jquery-ui":"^1.10.5",d3:"^3.4.13"},"browserify-shim":{google:"global:google"},browserify:{transform:["browserify-shim"]},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"},"../lib/DataTables/media/js/jquery.dataTables.js":{require:"datatables",global:"jQuery"},datatables:{require:"datatables",global:"jQuery"},d3:{require:"d3",global:"d3"},"jquery-ui/sortable":{require:"jquery-ui/sortable",global:"jQuery"},pivottable:{require:"pivottable",global:"jQuery"}}}},{}],67:[function(e,t){"use strict";t.exports=function(e){var t='"',n=",",r="\n",i=e.head.vars,o=e.results.bindings,s=function(){for(var e=0;e<i.length;e++)u(i[e]);c+=r},a=function(){for(var e=0;e<o.length;e++){l(o[e]);c+=r}},l=function(e){for(var t=0;t<i.length;t++){var n=i[t];u(e.hasOwnProperty(n)?e[n].value:"")}},u=function(e){e.replace(t,t+t);p(e)&&(e=t+e+t);c+=" "+e+" "+n},p=function(e){var r=!1;e.match("[\\w|"+n+"|"+t+"]")&&(r=!0);return r},c="";s();a();return c}},{}],68:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=t.exports=function(t){var r=n("<div class='booleanResult'></div>"),i=function(){r.empty().appendTo(t.resultsContainer);var i=t.results.getBoolean(),o=null,s=null;if(i===!0){o="check";s="True"}else if(i===!1){o="cross";s="False"}else{r.width("140");s="Could not find boolean value in response"}o&&e("yasgui-utils").svg.draw(r,e("./imgs.js")[o]);n("<span></span>").text(s).appendTo(r)},o=function(){return t.results.getBoolean&&(t.results.getBoolean()===!0||0==t.results.getBoolean())};return{name:null,draw:i,hideFromSelection:!0,getPriority:10,canHandleResults:o}};r.version={"YASR-boolean":e("../package.json").version,jquery:n.fn.jquery}},{"../package.json":66,"./imgs.js":73,jquery:void 0,"yasgui-utils":63}],69:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports={output:"table",useGoogleCharts:!0,outputPlugins:["table","error","boolean","rawResponse"],drawOutputSelector:!0,drawDownloadIcon:!0,getUsedPrefixes:null,persistency:{prefix:function(e){return"yasr_"+n(e.container).closest("[id]").attr("id")+"_"},outputSelector:function(){return"selector"},results:{id:function(e){return"results_"+n(e.container).closest("[id]").attr("id")},key:"results",maxSize:1e5}}}},{jquery:void 0}],70:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=t.exports=function(e){var t=n("<div class='errorResult'></div>"),i=(n.extend(!0,{},r.defaults),function(){var r=e.results.getException();t.empty().appendTo(e.resultsContainer);var i="Error";r.statusText&&r.statusText.length<100&&(i=r.statusText);void 0!=r.status&&(i+=" (#"+r.status+")");t.append(n("<span>",{"class":"exception"}).text(i));var o=null;r.responseText?o=r.responseText:"string"==typeof r&&(o=r);
o&&t.append(n("<pre>").text(o))}),o=function(e){return e.results.getException()||!1};return{name:null,draw:i,getPriority:20,hideFromSelection:!0,canHandleResults:o}};r.defaults={}},{jquery:void 0}],71:[function(e,t){(function(n){var r=e("events").EventEmitter,i=(function(){try{return e("jquery")}catch(t){return window.jQuery}}(),!1),o=!1,s=function(){r.call(this);var e=this;this.init=function(){if(o||("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)||i)("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)?e.emit("initDone"):o&&e.emit("initError");else{i=!0;a("//google.com/jsapi",function(){i=!1;e.emit("initDone")});var t=100,r=6e3,s=+new Date,l=function(){if(!("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null))if(+new Date-s>r){o=!0;i=!1;e.emit("initError")}else setTimeout(l,t)};l()}};this.googleLoad=function(){var t=function(){("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null).load("visualization","1",{packages:["corechart","charteditor"],callback:function(){e.emit("done")}})};if(i){e.once("initDone",t);e.once("initError",function(){e.emit("error","Could not load google loader")})}else if("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)t();else if(o)e.emit("error","Could not load google loader");else{e.once("initDone",t);e.once("initError",function(){e.emit("error","Could not load google loader")})}}},a=function(e,t){var n=document.createElement("script");n.type="text/javascript";n.readyState?n.onreadystatechange=function(){if("loaded"==n.readyState||"complete"==n.readyState){n.onreadystatechange=null;t()}}:n.onload=function(){t()};n.src=e;document.body.appendChild(n)};s.prototype=new r;t.exports=new s}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{events:2,jquery:void 0}],72:[function(e,t){(function(n){"use strict";function r(e,t,n){function r(e,t,o){var l,u,p,c,d,f,h,g;if(null==e||null==t)return e===t;if(e.__placeholder__||t.__placeholder__)return!0;if(e===t)return 0!==e||1/e==1/t;l=i.call(e);if(i.call(t)!=l)return!1;switch(l){case"[object String]":return e==String(t);case"[object Number]":return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object RegExp]":return e.source==t.source&&e.global==t.global&&e.multiline==t.multiline&&e.ignoreCase==t.ignoreCase}if("object"!=typeof e||"object"!=typeof t)return!1;u=o.length;for(;u--;)if(o[u]==e)return!0;o.push(e);p=0;c=!0;if("[object Array]"==l){d=e.length;f=t.length;if(a){switch(n){case"===":c=d===f;break;case"<==":c=f>=d;break;case"<<=":c=f>d}p=d;a=!1}else{c=d===f;p=d}if(c)for(;p--&&(c=p in e==p in t&&r(e[p],t[p],o)););}else{if("constructor"in e!="constructor"in t||e.constructor!=t.constructor)return!1;for(h in e)if(s(e,h)){p++;if(!(c=s(t,h)&&r(e[h],t[h],o)))break}if(c){g=0;for(h in t)s(t,h)&&++g;if(a)c="<<="===n?g>p:"<=="===n?g>=p:p===g;else{a=!1;c=p===g}}}o.pop();return c}var i={}.toString,o={}.hasOwnProperty,s=function(e,t){return o.call(e,t)},a=!0;return r(e,t,[])}var i=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),o=e("./utils.js"),s=e("yasgui-utils"),a=t.exports=function(t){var l=i.extend(!0,{},a.defaults),u=t.container.closest("[id]").attr("id");null==t.options.gchart&&(t.options.gchart={});var p=t.getPersistencyId("motionchart"),c=t.getPersistencyId("chartConfig");null==t.options.gchart.motionChartState&&(t.options.gchart.motionChartState=s.storage.get(p));null==t.options.gchart.chartConfig&&(t.options.gchart.chartConfig=s.storage.get(c));var d=null,f=function(e){var i="undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null;d=new i.visualization.ChartEditor;i.visualization.events.addListener(d,"ok",function(){var e,n;e=d.getChartWrapper();if(!r(e.getChartType,"MotionChart","===")){t.options.gchart.motionChartState=e.n;s.storage.set(p,t.options.gchart.motionChartState);e.setOption("state",t.options.gchart.motionChartState);i.visualization.events.addListener(e,"ready",function(){var n;n=e.getChart();i.visualization.events.addListener(n,"statechange",function(){t.options.gchart.motionChartState=n.getState();s.storage.set(p,t.options.gchart.motionChartState)})})}n=e.getDataTable();e.setDataTable(null);t.options.gchart.chartConfig=e.toJSON();s.storage.set(c,t.options.gchart.chartConfig);e.setDataTable(n);e.draw()});e&&e()};return{name:"Google Chart",hideFromSelection:!1,priority:7,canHandleResults:function(e){var t,n;return null!=(t=e.results)&&(n=t.getVariables())&&n.length>0},getDownloadInfo:function(){if(!t.results)return null;var e=t.resultsContainer.find("svg");return 0==e.length?null:{getContent:function(){return e[0].outerHTML},filename:"queryResults.svg",contentType:"image/svg+xml",buttonTitle:"Download SVG Image"}},draw:function(){var r=function(){t.resultsContainer.empty();var e=u+"_gchartWrapper",n=null;t.resultsContainer.append(i("<button>",{"class":"openGchartBtn yasr_btn"}).text("Chart Config").click(function(){d.openDialog(n)})).append(i("<div>",{id:e,"class":"gchartWrapper"}));var r=new google.visualization.DataTable,a=t.results.getAsJson();a.head.vars.forEach(function(e){var t=o.getGoogleType(a.results.bindings[0][e]);r.addColumn(t,e)});var c=null;t.options.getUsedPrefixes&&(c="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);a.results.bindings.forEach(function(e){var t=[];a.head.vars.forEach(function(n){t.push(o.castGoogleType(e[n],c))});r.addRow(t)});if(t.options.gchart.chartConfig){n=new google.visualization.ChartWrapper(t.options.gchart.chartConfig);if("MotionChart"===n.getChartType()&&null!=t.options.gchart.motionChartState){n.setOption("state",t.options.gchart.motionChartState);google.visualization.events.addListener(n,"ready",function(){var e;e=n.getChart();google.visualization.events.addListener(e,"statechange",function(){t.options.gchart.motionChartState=e.getState();s.storage.set(p,t.options.gchart.motionChartState)})})}n.setDataTable(r)}else n=new google.visualization.ChartWrapper({chartType:"Table",dataTable:r,containerId:e});n.setOption("width",l.width);n.setOption("height",l.height);n.draw();t.updateHeader()};("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)&&("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null).visualization&&d?r():e("./gChartLoader.js").on("done",function(){f();r()}).on("error",function(){console.log("errorrr")}).googleLoad()}}};a.defaults={height:"600px",width:"100%",persistencyId:"gchart"}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./gChartLoader.js":71,"./utils.js":84,jquery:void 0,"yasgui-utils":63}],73:[function(e,t){"use strict";t.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',move:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_11656_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="753" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="287" inkscape:window-y="249" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><polygon points="33,83 50,100 67,83 54,83 54,17 67,17 50,0 33,17 46,17 46,83 " transform="translate(-7.962963,-10)" /><polygon points="83,67 100,50 83,33 83,46 17,46 17,33 0,50 17,67 17,54 83,54 " transform="translate(-7.962963,-10)" /></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}},{}],74:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("yasgui-utils");console=console||{log:function(){}};var i=t.exports=function(t,s,a){var l={};l.options=n.extend(!0,{},i.defaults,s);l.container=n("<div class='yasr'></div>").appendTo(t);l.header=n("<div class='yasr_header'></div>").appendTo(l.container);l.resultsContainer=n("<div class='yasr_results'></div>").appendTo(l.container);l.storage=r.storage;var u=null;l.getPersistencyId=function(e){null===u&&(u=l.options.persistency&&l.options.persistency.prefix?"string"==typeof l.options.persistency.prefix?l.options.persistency.prefix:l.options.persistency.prefix(l):!1);return u&&e?u+("string"==typeof e?e:e(l)):null};l.options.useGoogleCharts&&e("./gChartLoader.js").once("initError",function(){l.options.useGoogleCharts=!1}).init();l.plugins={};for(var p in i.plugins)(l.options.useGoogleCharts||"gchart"!=p)&&(l.plugins[p]=new i.plugins[p](l));l.updateHeader=function(){var e=l.header.find(".yasr_downloadIcon").removeAttr("title"),t=l.plugins[l.options.output];if(t){var n=t.getDownloadInfo?t.getDownloadInfo():null;if(n){n.buttonTitle&&e.attr("title",n.buttonTitle);e.prop("disabled",!1);e.find("path").each(function(){this.style.fill="black"})}else{e.prop("disabled",!0).prop("title","Download not supported for this result representation");e.find("path").each(function(){this.style.fill="gray"})}}};l.draw=function(e){if(!l.results)return!1;e||(e=l.options.output);var t=null,r=-1,i=[];for(var o in l.plugins)if(l.plugins[o].canHandleResults(l)){var s=l.plugins[o].getPriority;"function"==typeof s&&(s=s(l));if(null!=s&&void 0!=s&&s>r){r=s;t=o}}else i.push(o);c(i);if(e in l.plugins&&l.plugins[e].canHandleResults(l)){n(l.resultsContainer).empty();l.plugins[e].draw();return!0}if(t){n(l.resultsContainer).empty();l.plugins[t].draw();return!0}return!1};var c=function(e){l.header.find(".yasr_btnGroup .yasr_btn").removeClass("disabled");e.forEach(function(e){l.header.find(".yasr_btnGroup .select_"+e).addClass("disabled")})};l.somethingDrawn=function(){return!l.resultsContainer.is(":empty")};l.setResponse=function(t,n,i){try{l.results=e("./parsers/wrapper.js")(t,n,i)}catch(o){l.results={getException:function(){return o}}}l.draw();var s=l.getPersistencyId(l.options.persistency.results.key);s&&(l.results.getOriginalResponseAsString&&l.results.getOriginalResponseAsString().length<l.options.persistency.results.maxSize?r.storage.set(s,l.results.getAsStoreObject(),"month"):r.storage.remove(s))};var d=l.getPersistencyId(l.options.persistency.outputSelector);if(d){var f=r.storage.get(d);f&&(l.options.output=f)}o(l);if(!a&&l.options.persistency&&l.options.persistency.results){var h,g=l.getPersistencyId(l.options.persistency.results.key);g&&(h=r.storage.get(g));if(!h&&l.options.persistency.results.id){var m="string"==typeof l.options.persistency.results.id?l.options.persistency.results.id:l.options.persistency.results.id(l);if(m){h=r.storage.get(m);h&&r.storage.remove(m)}}h&&(n.isArray(h)?l.setResponse.apply(this,h):l.setResponse(h))}a&&l.setResponse(a);l.updateHeader();return l},o=function(t){var i=function(){var e=n('<div class="yasr_btnGroup"></div>');n.each(t.plugins,function(i,o){if(!o.hideFromSelection){var s=o.name||i,a=n("<button class='yasr_btn'></button>").text(s).addClass("select_"+i).click(function(){e.find("button.selected").removeClass("selected");n(this).addClass("selected");t.options.output=i;var o=t.getPersistencyId(t.options.persistency.outputSelector);o&&r.storage.set(o,t.options.output,"month");t.draw();t.updateHeader()}).appendTo(e);t.options.output==i&&a.addClass("selected")}});e.children().length>1&&t.header.append(e)},o=function(){var r=function(e,t){var n=null,r=window.URL||window.webkitURL||window.mozURL||window.msURL;if(r&&Blob){var i=new Blob([e],{type:t});n=r.createObjectURL(i)}return n},i=n("<button class='yasr_btn yasr_downloadIcon btn_icon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").download)).click(function(){var i=t.plugins[t.options.output];if(i&&i.getDownloadInfo){var o=i.getDownloadInfo(),s=r(o.getContent(),o.contentType?o.contentType:"text/plain"),a=n("<a></a>",{href:s,download:o.filename});e("./utils.js").fireClick(a)}});t.header.append(i)},s=function(){var r=n("<button class='yasr_btn btn_fullscreen btn_icon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").fullscreen)).click(function(){t.container.addClass("yasr_fullscreen")});t.header.append(r)},a=function(){var r=n("<button class='yasr_btn btn_smallscreen btn_icon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").smallscreen)).click(function(){t.container.removeClass("yasr_fullscreen")});t.header.append(r)};s();a();t.options.drawOutputSelector&&i();t.options.drawDownloadIcon&&o()};i.plugins={};i.registerOutput=function(e,t){i.plugins[e]=t};i.defaults=e("./defaults.js");i.version={YASR:e("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":e("yasgui-utils").version};i.$=n;try{i.registerOutput("boolean",e("./boolean.js"))}catch(s){}try{i.registerOutput("rawResponse",e("./rawResponse.js"))}catch(s){}try{i.registerOutput("table",e("./table.js"))}catch(s){}try{i.registerOutput("error",e("./error.js"))}catch(s){}try{i.registerOutput("pivot",e("./pivot.js"))}catch(s){}try{i.registerOutput("gchart",e("./gchart.js"))}catch(s){}},{"../package.json":66,"./boolean.js":68,"./defaults.js":69,"./error.js":70,"./gChartLoader.js":71,"./gchart.js":72,"./imgs.js":73,"./parsers/wrapper.js":79,"./pivot.js":81,"./rawResponse.js":82,"./table.js":83,"./utils.js":84,jquery:void 0,"yasgui-utils":63}],75:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})(),t.exports=function(t){return e("./dlv.js")(t,",")}},{"./dlv.js":76,jquery:void 0}],76:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("../../lib/jquery.csv-0.71.js");t.exports=function(e,t){var r={},i=n.csv.toArrays(e,{separator:t}),o=function(e){return 0==e.indexOf("http")?"uri":null},s=function(){if(2==i.length&&1==i[0].length&&1==i[1].length&&"boolean"==i[0][0]&&("1"==i[1][0]||"0"==i[1][0])){r["boolean"]="1"==i[1][0]?!0:!1;return!0}return!1},a=function(){if(i.length>0&&i[0].length>0){r.head={vars:i[0]};return!0}return!1},l=function(){if(i.length>1){r.results={bindings:[]};for(var e=1;e<i.length;e++){for(var t={},n=0;n<i[e].length;n++){var s=r.head.vars[n];if(s){var a=i[e][n],l=o(a);t[s]={value:a};l&&(t[s].type=l)}}r.results.bindings.push(t)}r.head={vars:i[0]};return!0}return!1},u=s();if(!u){var p=a();p&&l()}return r}},{"../../lib/jquery.csv-0.71.js":45,jquery:void 0}],77:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})(),t.exports=function(e){if("string"==typeof e)try{return JSON.parse(e)}catch(t){return!1}return"object"==typeof e&&e.constructor==={}.constructor?e:!1}},{jquery:void 0}],78:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})(),t.exports=function(t){return e("./dlv.js")(t," ")}},{"./dlv.js":76,jquery:void 0}],79:[function(e,t){"use strict";(function(){try{return e("jquery")}catch(t){return window.jQuery}})(),t.exports=function(t,n,r){var i={xml:e("./xml.js"),json:e("./json.js"),tsv:e("./tsv.js"),csv:e("./csv.js")},o=null,s=null,a=null,l=null,u=null,p=function(){if("object"==typeof t){if(t.exception)u=t.exception;else if(void 0!=t.status&&(t.status>=300||0===t.status)){u={status:t.status};"string"==typeof r&&(u.errorString=r);t.responseText&&(u.responseText=t.responseText);t.statusText&&(u.statusText=t.statusText)}if(t.contentType)o=t.contentType.toLowerCase();else if(t.getResponseHeader&&t.getResponseHeader("content-type")){var e=t.getResponseHeader("content-type").trim().toLowerCase();e.length>0&&(o=e)}t.response?s=t.response:n||r||(s=t)}u||s||(s=t.responseText?t.responseText:t)},c=function(){if(a)return a;if(a===!1||u)return!1;var e=function(){if(o)if(o.indexOf("json")>-1){try{a=i.json(s)
}catch(e){u=e}l="json"}else if(o.indexOf("xml")>-1){try{a=i.xml(s)}catch(e){u=e}l="xml"}else if(o.indexOf("csv")>-1){try{a=i.csv(s)}catch(e){u=e}l="csv"}else if(o.indexOf("tab-separated")>-1){try{a=i.tsv(s)}catch(e){u=e}l="tsv"}},t=function(){a=i.json(s);if(a)l="json";else try{a=i.xml(s);a&&(l="xml")}catch(e){}};e();a||t();a||(a=!1);return a},d=function(){var e=c();return e&&"head"in e?e.head.vars:null},f=function(){var e=c();return e&&"results"in e?e.results.bindings:null},h=function(){var e=c();return e&&"boolean"in e?e["boolean"]:null},g=function(){return s},m=function(){var e="";"string"==typeof s?e=s:"json"==l?e=JSON.stringify(s,void 0,2):"xml"==l&&(e=(new XMLSerializer).serializeToString(s));return e},E=function(){return u},v=function(){null==l&&c();return l},x=function(){var e={};if(t.status){e.status=t.status;e.responseText=t.responseText;e.statusText=t.statusText;e.contentType=o}else e=t;var i=n,s=void 0;"string"==typeof r&&(s=r);return[e,i,s]};p();a=c();return{getAsStoreObject:x,getAsJson:c,getOriginalResponse:g,getOriginalResponseAsString:m,getOriginalContentType:function(){return o},getVariables:d,getBindings:f,getBoolean:h,getType:v,getException:E}}},{"./csv.js":75,"./json.js":77,"./tsv.js":78,"./xml.js":80,jquery:void 0}],80:[function(e,t){"use strict";{var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports=function(e){var t=function(e){s.head={};for(var t=0;t<e.childNodes.length;t++){var n=e.childNodes[t];if("variable"==n.nodeName){s.head.vars||(s.head.vars=[]);var r=n.getAttribute("name");r&&s.head.vars.push(r)}}},r=function(e){s.results={};s.results.bindings=[];for(var t=0;t<e.childNodes.length;t++){for(var n=e.childNodes[t],r=null,i=0;i<n.childNodes.length;i++){var o=n.childNodes[i];if("binding"==o.nodeName){var a=o.getAttribute("name");if(a){r=r||{};r[a]={};for(var l=0;l<o.childNodes.length;l++){var u=o.childNodes[l],p=u.nodeName;if("#text"!=p){r[a].type=p;r[a].value=u.innerHTML;var c=u.getAttribute("datatype");c&&(r[a].datatype=c)}}}}}r&&s.results.bindings.push(r)}},i=function(e){s["boolean"]="true"==e.innerHTML?!0:!1},o=null;"string"==typeof e?o=n.parseXML(e):n.isXMLDoc(e)&&(o=e);var e=null;if(!(o.childNodes.length>0))return null;e=o.childNodes[0];for(var s={},a=0;a<e.childNodes.length;a++){var l=e.childNodes[a];"head"==l.nodeName&&t(l);"results"==l.nodeName&&r(l);"boolean"==l.nodeName&&i(l)}return s}}},{jquery:void 0}],81:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("./utils.js"),i=e("yasgui-utils"),o=e("./imgs.js");(function(){try{return e("jquery-ui/sortable")}catch(t){return window.jQuery}})();(function(){try{return e("pivottable")}catch(t){return window.jQuery}})();if(!n.fn.pivotUI)throw new Error("Pivot lib not loaded");var s=t.exports=function(t){var a=n.extend(!0,{},s.defaults);if(a.useD3Chart){try{var l=function(){try{return e("d3")}catch(t){return window.d3}}();l&&e("../node_modules/pivottable/dist/d3_renderers.js")}catch(u){}n.pivotUtilities.d3_renderers&&n.extend(!0,n.pivotUtilities.renderers,n.pivotUtilities.d3_renderers)}var p,c=null,d=function(){var e=t.results.getVariables();if(!a.mergeLabelsWithUris)return e;var n=[];c="string"==typeof a.mergeLabelsWithUris?a.mergeLabelsWithUris:"Label";e.forEach(function(t){-1!==t.indexOf(c,t.length-c.length)&&e.indexOf(t.substring(0,t.length-c.length))>=0||n.push(t)});return n},f=function(e){var n=d(),i=null;t.options.getUsedPrefixes&&(i="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);t.results.getBindings().forEach(function(t){var o={};n.forEach(function(e){if(e in t){var n=t[e].value;c&&t[e+c]?n=t[e+c].value:"uri"==t[e].type&&(n=r.uriToPrefixed(i,n));o[e]=n}else o[e]=null});e(o)})},h=t.getPersistencyId(a.persistencyId),g=function(){var e=i.storage.get(h);if(e){var r=t.results.getVariables(),o=!0;e.cols.forEach(function(e){r.indexOf(e)<0&&(o=!1)});o&&e.rows.forEach(function(e){r.indexOf(e)<0&&(o=!1)});if(!o){e.cols=[];e.rows=[]}n.pivotUtilities.renderers[e.rendererName]||delete e.rendererName}else e={};return e},m=function(){var r=function(){var e=function(e){if(h){var n={cols:e.cols,rows:e.rows,rendererName:e.rendererName,aggregatorName:e.aggregatorName,vals:e.vals};i.storage.set(h,n,"month")}e.rendererName.toLowerCase().indexOf(" chart")>=0?r.show():r.hide();t.updateHeader()},r=n("<button>",{"class":"openPivotGchart yasr_btn"}).text("Chart Config").click(function(){p.find('div[dir="ltr"]').dblclick()}).appendTo(t.resultsContainer);p=n("<div>",{"class":"pivotTable"}).appendTo(n(t.resultsContainer));var a=n.extend(!0,{},g(),s.defaults.pivotTable);a.onRefresh=function(){var t=a.onRefresh;return function(n){e(n);t&&t(n)}}();window.pivot=p.pivotUI(f,a);var l=n(i.svg.getElement(o.move));p.find(".pvtTriangle").replaceWith(l);n(".pvtCols").prepend(n("<div>",{"class":"containerHeader"}).text("Columns"));n(".pvtRows").prepend(n("<div>",{"class":"containerHeader"}).text("Rows"));n(".pvtUnused").prepend(n("<div>",{"class":"containerHeader"}).text("Available Variables"));n(".pvtVals").prepend(n("<div>",{"class":"containerHeader"}).text("Cells"));setTimeout(t.updateHeader,400)};t.options.useGoogleCharts&&a.useGoogleCharts&&!n.pivotUtilities.gchart_renderers?e("./gChartLoader.js").on("done",function(){try{e("../node_modules/pivottable/dist/gchart_renderers.js");n.extend(!0,n.pivotUtilities.renderers,n.pivotUtilities.gchart_renderers)}catch(t){a.useGoogleCharts=!1}r()}).on("error",function(){console.log("could not load gchart");a.useGoogleCharts=!1;r()}).googleLoad():r()},E=function(){return t.results&&t.results.getVariables&&t.results.getVariables()&&t.results.getVariables().length>0},v=function(){if(!t.results)return null;var e=t.resultsContainer.find(".pvtRendererArea svg");return 0==e.length?null:{getContent:function(){return e[0].outerHTML},filename:"queryResults.svg",contentType:"image/svg+xml",buttonTitle:"Download SVG Image"}};return{getDownloadInfo:v,options:a,draw:m,name:"Pivot Table",canHandleResults:E,getPriority:4}};s.defaults={mergeLabelsWithUris:!1,useGoogleCharts:!0,useD3Chart:!0,persistencyId:"pivot",pivotTable:{}};s.version={"YASR-rawResponse":e("../package.json").version,jquery:n.fn.jquery}},{"../node_modules/pivottable/dist/d3_renderers.js":58,"../node_modules/pivottable/dist/gchart_renderers.js":59,"../package.json":66,"./gChartLoader.js":71,"./imgs.js":73,"./utils.js":84,d3:53,jquery:void 0,"jquery-ui/sortable":56,pivottable:60,"yasgui-utils":63}],82:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=function(){try{return e("codemirror")}catch(t){return window.CodeMirror}}();e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/mode/xml/xml.js");e("codemirror/mode/javascript/javascript.js");var i=t.exports=function(e){var t=n.extend(!0,{},i.defaults),o=null,s=function(){var n=t.CodeMirror;n.value=e.results.getOriginalResponseAsString();var i=e.results.getType();if(i){"json"==i&&(i={name:"javascript",json:!0});n.mode=i}o=r(e.resultsContainer.get()[0],n);o.on("fold",function(){o.refresh()});o.on("unfold",function(){o.refresh()})},a=function(){if(!e.results)return!1;if(!e.results.getOriginalResponseAsString)return!1;var t=e.results.getOriginalResponseAsString();return t&&0!=t.length||!e.results.getException()?!0:!1},l=function(){if(!e.results)return null;var t=e.results.getOriginalContentType(),n=e.results.getType();return{getContent:function(){return e.results.getOriginalResponse()},filename:"queryResults"+(n?"."+n:""),contentType:t?t:"text/plain",buttonTitle:"Download raw response"}};return{draw:s,name:"Raw Response",canHandleResults:a,getPriority:2,getDownloadInfo:l}};i.defaults={CodeMirror:{readOnly:!0,lineNumbers:!0,lineWrapping:!0,foldGutter:!0,gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"]}};i.version={"YASR-rawResponse":e("../package.json").version,jquery:n.fn.jquery,CodeMirror:r.version}},{"../package.json":66,codemirror:void 0,"codemirror/addon/edit/matchbrackets.js":46,"codemirror/addon/fold/brace-fold.js":47,"codemirror/addon/fold/foldcode.js":48,"codemirror/addon/fold/foldgutter.js":49,"codemirror/addon/fold/xml-fold.js":50,"codemirror/mode/javascript/javascript.js":51,"codemirror/mode/xml/xml.js":52,jquery:void 0}],83:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("yasgui-utils"),i=e("./imgs.js");(function(){try{return e("datatables")}catch(t){return window.jQuery}})();e("../lib/colResizable-1.4.js");var o=t.exports=function(t){var s=null,a={name:"Table",getPriority:10},u=a.options=n.extend(!0,{},o.defaults),p=u.persistency?t.getPersistencyId(u.persistency.tableLength):null,c=function(){var e=[],n=t.results.getBindings(),r=t.results.getVariables(),i=null;t.options.getUsedPrefixes&&(i="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);for(var o=0;o<n.length;o++){var s=[];s.push("");for(var l=n[o],p=0;p<r.length;p++){var c=r[p];s.push(c in l?u.getCellContent?u.getCellContent(t,a,l,c,{rowId:o,colId:p,usedPrefixes:i}):"":"")}e.push(s)}return e},d=function(){s.on("order.dt",function(){f()});p&&s.on("length.dt",function(e,t,n){r.storage.set(p,n,"month")});n.extend(!0,u.callbacks,u.handlers);s.delegate("td","click",function(e){if(u.callbacks&&u.callbacks.onCellClick){var t=u.callbacks.onCellClick(this,e);if(t===!1)return!1}}).delegate("td","mouseenter",function(e){u.callbacks&&u.callbacks.onCellMouseEnter&&u.callbacks.onCellMouseEnter(this,e);var t=n(this);u.fetchTitlesFromPreflabel&&void 0===t.attr("title")&&0==t.text().trim().indexOf("http")&&l(t)}).delegate("td","mouseleave",function(e){u.callbacks&&u.callbacks.onCellMouseLeave&&u.callbacks.onCellMouseLeave(this,e)})};a.draw=function(){s=n('<table cellpadding="0" cellspacing="0" border="0" class="resultsTable"></table>');n(t.resultsContainer).html(s);var e=u.datatable;e.data=c();e.columns=u.getColumns(t,a);var i=r.storage.get(p);i&&(e.pageLength=i);s.DataTable(n.extend(!0,{},e));f();d();s.colResizable();s.find("thead").outerHeight();n(t.resultsContainer).find(".JCLRgrip").height(s.find("thead").outerHeight());var o=t.header.outerHeight()-5;if(o>0){t.resultsContainer.find(".dataTables_wrapper").css("position","relative").css("top","-"+o+"px").css("margin-bottom","-"+o+"px");n(t.resultsContainer).find(".JCLRgrip").css("marginTop",o+"px")}};var f=function(){var e={sorting:"unsorted",sorting_asc:"sortAsc",sorting_desc:"sortDesc"};s.find(".sortIcons").remove();for(var t in e){var o=n("<div class='sortIcons'></div>");r.svg.draw(o,i[e[t]]);s.find("th."+t).append(o)}};a.canHandleResults=function(){return t.results&&t.results.getVariables&&t.results.getVariables()&&t.results.getVariables().length>0};a.getDownloadInfo=function(){return t.results?{getContent:function(){return e("./bindingsToCsv.js")(t.results.getAsJson())},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:null};return a},s=function(e,t,n){var r=n.value;if(n["xml:lang"])r='"'+n.value+'"@'+n["xml:lang"];else if(n.datatype){var i="http://www.w3.org/2001/XMLSchema#",o=n.datatype;o=0==o.indexOf(i)?"xsd:"+o.substring(i.length):"<"+o+">";r='"'+r+'"^^'+o}return r},a=function(e,t,n,r,i){var o=n[r],a=null;if("uri"==o.type){var l=null,u=o.value,p=u;if(i.usedPrefixes)for(var c in i.usedPrefixes)if(0==p.indexOf(i.usedPrefixes[c])){p=c+":"+u.substring(i.usedPrefixes[c].length);break}if(t.options.mergeLabelsWithUris){var d="string"==typeof t.options.mergeLabelsWithUris?t.options.mergeLabelsWithUris:"Label";if(n[r+d]){p=s(e,t,n[r+d]);l=u}}a="<a "+(l?"title='"+u+"' ":"")+"class='uri' target='_blank' href='"+u+"'>"+p+"</a>"}else a="<span class='nonUri'>"+s(e,t,o)+"</span>";return"<div>"+a+"</div>"},l=function(e){var t=function(){e.attr("title","")};n.get("http://preflabel.org/api/v1/label/"+encodeURIComponent(e.text())+"?silent=true").success(function(n){"object"==typeof n&&n.label?e.attr("title",n.label):"string"==typeof n&&n.length>0?e.attr("title",n):t()}).fail(t)};o.defaults={getCellContent:a,persistency:{tableLength:"tableLength"},getColumns:function(e,t){var n=function(n){if(!t.options.mergeLabelsWithUris)return!0;var r="string"==typeof t.options.mergeLabelsWithUris?t.options.mergeLabelsWithUris:"Label";return-1!==n.indexOf(r,n.length-r.length)&&e.results.getVariables().indexOf(n.substring(0,n.length-r.length))>=0?!1:!0},r=[];r.push({title:""});e.results.getVariables().forEach(function(e){r.push({title:"<span>"+e+"</span>",visible:n(e)})});return r},fetchTitlesFromPreflabel:!0,mergeLabelsWithUris:!1,callbacks:{onCellMouseEnter:null,onCellMouseLeave:null,onCellClick:null},datatable:{autoWidth:!1,order:[],pageLength:50,lengthMenu:[[10,50,100,1e3,-1],[10,50,100,1e3,"All"]],lengthChange:!0,pagingType:"full_numbers",drawCallback:function(e){for(var t=0;t<e.aiDisplay.length;t++)n("td:eq(0)",e.aoData[e.aiDisplay[t]].nTr).html(t+1);var r=!1;n(e.nTableWrapper).find(".paginate_button").each(function(){-1==n(this).attr("class").indexOf("current")&&-1==n(this).attr("class").indexOf("disabled")&&(r=!0)});r?n(e.nTableWrapper).find(".dataTables_paginate").show():n(e.nTableWrapper).find(".dataTables_paginate").hide()},columnDefs:[{width:"32px",orderable:!1,targets:0}]}};o.version={"YASR-table":e("../package.json").version,jquery:n.fn.jquery,"jquery-datatables":n.fn.DataTable.version}},{"../lib/colResizable-1.4.js":44,"../package.json":66,"./bindingsToCsv.js":67,"./imgs.js":73,datatables:void 0,jquery:void 0,"yasgui-utils":63}],84:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports={uriToPrefixed:function(e,t){if(e)for(var n in e)if(0==t.indexOf(e[n])){t=n+":"+t.substring(e[n].length);break}return t},getGoogleType:function(e){if(null==e.type||"typed-literal"!==e.type&&"literal"!==e.type)return"string";switch(e.datatype){case"http://www.w3.org/2001/XMLSchema#float":case"http://www.w3.org/2001/XMLSchema#decimal":case"http://www.w3.org/2001/XMLSchema#int":case"http://www.w3.org/2001/XMLSchema#integer":case"http://www.w3.org/2001/XMLSchema#long":case"http://www.w3.org/2001/XMLSchema#gYearMonth":case"http://www.w3.org/2001/XMLSchema#gYear":case"http://www.w3.org/2001/XMLSchema#gMonthDay":case"http://www.w3.org/2001/XMLSchema#gDay":case"http://www.w3.org/2001/XMLSchema#gMonth":return"number";case"http://www.w3.org/2001/XMLSchema#date":return"date";case"http://www.w3.org/2001/XMLSchema#dateTime":return"datetime";case"http://www.w3.org/2001/XMLSchema#time":return"timeofday";default:return"string"}},castGoogleType:function(e,n){if(null==e)return null;if(null==e.type||"typed-literal"!==e.type&&"literal"!==e.type)return(e.type="uri")?t.exports.uriToPrefixed(n,e.value):e.value;switch(e.datatype){case"http://www.w3.org/2001/XMLSchema#float":case"http://www.w3.org/2001/XMLSchema#decimal":case"http://www.w3.org/2001/XMLSchema#int":case"http://www.w3.org/2001/XMLSchema#integer":case"http://www.w3.org/2001/XMLSchema#long":case"http://www.w3.org/2001/XMLSchema#gYearMonth":case"http://www.w3.org/2001/XMLSchema#gYear":case"http://www.w3.org/2001/XMLSchema#gMonthDay":case"http://www.w3.org/2001/XMLSchema#gDay":case"http://www.w3.org/2001/XMLSchema#gMonth":return Number(e.value);case"http://www.w3.org/2001/XMLSchema#date":case"http://www.w3.org/2001/XMLSchema#dateTime":case"http://www.w3.org/2001/XMLSchema#time":return new Date(e.value);default:return e.value}},fireClick:function(e){e&&e.each(function(e,t){var r=n(t);if(document.dispatchEvent){var i=document.createEvent("MouseEvents");i.initMouseEvent("click",!0,!0,window,1,1,1,1,1,!1,!1,!1,!1,0,r[0]);r[0].dispatchEvent(i)}else document.fireEvent&&r[0].click()})}}},{jquery:void 0}],85:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports={persistencyPrefix:function(e){return"yasgui_"+n(e.wrapperElement).closest("[id]").attr("id")+"_"},api:{corsProxy:null}}},{jquery:void 0}],86:[function(e,t){"use strict";t.exports={persistent:null,consumeShareLink:null,createShareLink:null,sparql:{showQueryButton:!0,acceptHeaderGraph:"text/turtle",acceptHeaderSelect:"application/sparql-results+json"}}},{}],87:[function(e,t){"use strict";t.exports={yasgui:'<svg xmlns:osb="http://www.openswatchbook.org/uri/2009/osb" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" viewBox="0 0 603.99 522.51" width="100%" height="100%" version="1.1" inkscape:version="0.48.4 r9939" sodipodi:docname="test.svg"> <defs > <linearGradient osb:paint="solid"> <stop style="stop-color:#3b3b3b;stop-opacity:1;" offset="0" /> </linearGradient> <inkscape:path-effect effect="skeletal" is_visible="true" pattern="M 0,5 C 0,2.24 2.24,0 5,0 7.76,0 10,2.24 10,5 10,7.76 7.76,10 5,10 2.24,10 0,7.76 0,5 z" copytype="single_stretched" prop_scale="1" scale_y_rel="false" spacing="0" normal_offset="0" tang_offset="0" prop_units="false" vertical_pattern="false" fuse_tolerance="0" /> <inkscape:path-effect effect="spiro" is_visible="true" /> <inkscape:path-effect effect="skeletal" is_visible="true" pattern="M 0,5 C 0,2.24 2.24,0 5,0 7.76,0 10,2.24 10,5 10,7.76 7.76,10 5,10 2.24,10 0,7.76 0,5 z" copytype="single_stretched" prop_scale="1" scale_y_rel="false" spacing="0" normal_offset="0" tang_offset="0" prop_units="false" vertical_pattern="false" fuse_tolerance="0" /> <inkscape:path-effect effect="spiro" is_visible="true" /> </defs> <sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="0.35" inkscape:cx="-469.55507" inkscape:cy="840.5292" inkscape:document-units="px" inkscape:current-layer="layer1" showgrid="false" inkscape:window-width="1855" inkscape:window-height="1056" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" /> <metadata > <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title /> </cc:Work> </rdf:RDF> </metadata> <g inkscape:label="Layer 1" inkscape:groupmode="layer" transform="translate(-50.966817,-280.33262)"> <rect style="fill:#3b3b3b;fill-opacity:1;stroke:none" width="40.000004" height="478.57324" x="-374.48849" y="103.99496" transform="matrix(-2.679181e-4,-0.99999996,0.99999993,-3.6684387e-4,0,0)" /> <rect style="fill:#3b3b3b;fill-opacity:1;stroke:none" width="40.000004" height="560" x="651.37634" y="-132.06581" transform="matrix(0.74639582,0.66550228,-0.66550228,0.74639582,0,0)" /> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.28877887,0,0,0.25811209,92.132758,620.67568)" /> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.28877887,0,0,0.25811209,457.84706,214.96137)" /> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.28877887,0,0,0.25811209,-30.152972,219.81853)" /> <g transform="matrix(0.68747304,-0.7262099,0.7262099,0.68747304,0,0)" inkscape:transform-center-x="239.86342" inkscape:transform-center-y="-26.958107" style="font-size:40px;font-style:normal;font-weight:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#3b3b3b;fill-opacity:1;stroke:none;font-family:Sans" > <path d="m -320.16655,490.61871 33.2,0 -32.4,75.4 0,64.6 -32.2,0 0,-64.6 -32.4,-75.4 33.2,0 15.2,43 15.4,-43 0,0" style="font-size:200px;font-variant:normal;font-stretch:normal;letter-spacing:20px;fill:#3b3b3b;font-family:RR Beaver;-inkscape-font-specification:RR Beaver" /> <path d="m -177.4603,630.61871 -32.2,0 -21.6,-80.4 -21.6,80.4 -32.2,0 37.4,-140 0.4,0 32,0 0.4,0 37.4,140 0,0" style="font-size:200px;font-variant:normal;font-stretch:normal;letter-spacing:20px;fill:#3b3b3b;font-family:RR Beaver;-inkscape-font-specification:RR Beaver" /> <path d="m -84.835303,544.41871 c 5.999926,9e-5 11.59992,1.13342 16.8,3.4 5.19991,2.26675 9.733238,5.40008 13.6,9.4 3.866564,3.86674 6.933228,8.40007 9.2,13.6 2.266556,5.20006 3.399889,10.80005 3.4,16.8 -1.11e-4,6.00004 -1.133444,11.60003 -3.4,16.8 -2.266772,5.20002 -5.333436,9.73335 -9.2,13.6 -3.866762,3.86668 -8.40009,6.93334 -13.6,9.2 -5.20008,2.26667 -10.800074,3.4 -16.8,3.4 l -64.599997,0 0,-32.2 64.599997,0 c 3.066595,-0.1333 5.599926,-1.19996 7.6,-3.2 2.133255,-2.13329 3.199921,-4.66662 3.2,-7.6 -7.9e-5,-3.06662 -1.066745,-5.59995 -3.2,-7.6 -2.000074,-2.13328 -4.533405,-3.19994 -7.6,-3.2 l -21.599997,0 c -6.00004,6e-5 -11.60004,-1.13328 -16.8,-3.4 -5.20003,-2.2666 -9.73336,-5.33327 -13.6,-9.2 -3.86668,-3.99993 -6.93335,-8.59992 -9.2,-13.8 -2.26667,-5.19991 -3.40001,-10.79991 -3.4,-16.8 -10e-6,-5.99989 1.13333,-11.59989 3.4,-16.8 2.26665,-5.19988 5.33332,-9.73321 9.2,-13.6 3.86664,-3.86653 8.39997,-6.9332 13.6,-9.2 5.19996,-2.26652 10.79996,-3.39986 16.8,-3.4 l 42.999997,0 0,32.4 -42.999997,0 c -3.06671,1.1e-4 -5.66671,1.06678 -7.8,3.2 -2.00004,2.00011 -3.00004,4.46677 -3,7.4 -4e-5,3.06676 0.99996,5.66676 3,7.8 2.13329,2.00009 4.73329,3.00009 7.8,3 l 21.599997,0 0,0" style="font-size:200px;font-variant:normal;font-stretch:normal;letter-spacing:20px;fill:#3b3b3b;font-family:RR Beaver;-inkscape-font-specification:RR Beaver" /> </g> <g style="font-size:40px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Theorem NBP;-inkscape-font-specification:Theorem NBP" > <path d="m 422.17683,677.02126 36.55,0 -5.44,27.54 -1.87,9.18 c -1.0201,5.10003 -2.94677,9.86003 -5.78,14.28 -2.83343,4.42002 -6.23343,8.27335 -10.2,11.56 -3.85342,3.28667 -8.21675,5.89334 -13.09,7.82 -4.76007,1.92667 -9.69007,2.89 -14.79,2.89 l -18.36,0 c -5.10004,0 -9.69003,-0.96333 -13.77,-2.89 -3.96669,-1.92666 -7.31002,-4.53333 -10.03,-7.82 -2.60668,-3.28665 -4.42002,-7.13998 -5.44,-11.56 -1.02001,-4.41997 -1.02001,-9.17997 0,-14.28 l 9.18,-45.9 c 1.01998,-5.09991 2.94664,-9.85991 5.78,-14.28 2.8333,-4.4199 6.17663,-8.27323 10.03,-11.56 3.96662,-3.28656 8.32995,-5.89322 13.09,-7.82 4.87328,-1.92655 9.85994,-2.88988 14.96,-2.89 l 18.36,0 c 5.09991,1.2e-4 9.63324,0.96345 13.6,2.89 4.0799,1.92678 7.42323,4.53344 10.03,7.82 2.71989,3.28677 4.58989,7.1401 5.61,11.56 1.01988,4.42009 1.01988,9.18009 0,14.28 l -27.37,0 c 0.45325,-2.49325 -9e-5,-4.58991 -1.36,-6.29 -1.36009,-1.81324 -3.34342,-2.71991 -5.95,-2.72 l -18.36,0 c -2.60673,9e-5 -4.98672,0.90676 -7.14,2.72 -2.15339,1.70009 -3.45672,3.79675 -3.91,6.29 l -9.18,45.9 c -0.45337,2.49337 -4e-5,4.6467 1.36,6.46 1.35996,1.81336 3.34329,2.72003 5.95,2.72 l 18.36,0 c 2.6066,3e-5 4.98659,-0.90664 7.14,-2.72 2.15326,-1.8133 3.45659,-3.96663 3.91,-6.46 l 1.87,-9.18 -9.18,0 5.44,-27.54" style="font-size:170px;font-style:italic;font-weight:bold;letter-spacing:20px;fill:#c80000;font-family:RR Beaver;-inkscape-font-specification:RR Beaver Bold Italic" /> <path d="m 569.69808,713.74126 c -1.0201,5.10003 -2.94677,9.86003 -5.78,14.28 -2.83343,4.42002 -6.23343,8.27335 -10.2,11.56 -3.85342,3.28667 -8.21675,5.89334 -13.09,7.82 -4.76007,1.92667 -9.69007,2.89 -14.79,2.89 l -18.36,0 c -5.10004,0 -9.69003,-0.96333 -13.77,-2.89 -3.96669,-1.92666 -7.31002,-4.53333 -10.03,-7.82 -2.60668,-3.28665 -4.42002,-7.13998 -5.44,-11.56 -1.02001,-4.41997 -1.02001,-9.17997 0,-14.28 l 16.49,-82.45 27.37,0 -16.49,82.45 c -0.45337,2.49337 -4e-5,4.6467 1.36,6.46 1.35996,1.81336 3.34329,2.72003 5.95,2.72 l 18.36,0 c 2.6066,3e-5 4.98659,-0.90664 7.14,-2.72 2.15326,-1.8133 3.45659,-3.96663 3.91,-6.46 l 16.49,-82.45 27.37,0 -16.49,82.45" style="font-size:170px;font-style:italic;font-weight:bold;letter-spacing:20px;fill:#c80000;font-family:RR Beaver;-inkscape-font-specification:RR Beaver Bold Italic" /> <path d="m 613.00933,631.29126 27.37,0 -23.8,119 -27.37,0 23.8,-119 0,0" style="font-size:170px;font-style:italic;font-weight:bold;letter-spacing:20px;fill:#c80000;font-family:RR Beaver;-inkscape-font-specification:RR Beaver Bold Italic" /> </g> <path sodipodi:type="arc" style="fill:#ffffff;fill-opacity:1;stroke:#3b3b3b;stroke-width:61.04665375;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" sodipodi:cx="455.71429" sodipodi:cy="513.79077" sodipodi:rx="144.28572" sodipodi:ry="161.42857" d="m 600.00002,513.79077 c 0,89.15454 -64.59892,161.42858 -144.28573,161.42858 -79.6868,0 -144.28572,-72.27404 -144.28572,-161.42858 0,-89.15454 64.59892,-161.42857 144.28572,-161.42857 79.68681,0 144.28573,72.27403 144.28573,161.42857 z" transform="matrix(0.4331683,0,0,0.38716814,381.83246,155.72497)" /> </g></svg>',cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',plus:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="5 -10 59.259258 79.999999" enable-background="new 0 0 100 100" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_79066_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="6.675088" inkscape:cx="46.670641" inkscape:cy="16.037704" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Your_Icon" /><g transform="translate(-23.47037,-20)"><g ><g ><g /></g><g /></g></g><path d="M 67.12963,22.5 H 42.129629 v -25 c 0,-4.142 -3.357,-7.5 -7.5,-7.5 -4.141999,0 -7.5,3.358 -7.5,7.5 v 25 H 2.1296295 c -4.142,0 -7.5,3.358 -7.5,7.5 0,4.143 3.358,7.5 7.5,7.5 H 27.129629 v 25 c 0,4.143 3.358001,7.5 7.5,7.5 4.143,0 7.5,-3.357 7.5,-7.5 v -25 H 67.12963 c 4.143,0 7.5,-3.357 7.5,-7.5 0,-4.142 -3.357,-7.5 -7.5,-7.5 z" inkscape:connector-curvature="0" style="fill:#000000" /></svg>'}},{}],88:[function(e){"use strict";var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),n=e("selectize"),r=e("yasgui-utils");n.define("allowRegularTextInput",function(){var e=this;this.onMouseDown=function(){var t=e.onMouseDown;return function(n){if(e.$dropdown.is(":visible")){n.stopPropagation();n.preventDefault()}else{t.apply(this,arguments);var r=this.getValue();this.clear(!0);this.setTextboxValue(r);this.refreshOptions(!0)}}}()});t.fn.endpointCombi=function(e,n){var o=function(n){e.corsEnabled||(e.corsEnabled={});n in e.corsEnabled||t.ajax({url:n,data:{query:"ASK {?x ?y ?z}"},complete:function(t){e.corsEnabled[n]=t.status>0}})},s=function(t){var n=null;e.persistencyPrefix&&(n=e.persistencyPrefix+"endpoint_"+t);var i=[];for(var o in l[0].selectize.options){var s=l[0].selectize.options[o];if(s.optgroup==t){var a={endpoint:s.endpoint};s.text&&(a.label=s.text);i.push(a)}}r.storage.set(n,i)},a=function(t,n){var o=null;e.persistencyPrefix&&(o=e.persistencyPrefix+"endpoint_"+n);var s=r.storage.get(o);if(!s&&"catalogue"==n){s=i();r.storage.set(o,s)}t(s,n)},l=this,u={selectize:{plugins:["allowRegularTextInput"],create:function(e,t){t({endpoint:e,optgroup:"own"})},createOnBlur:!0,onItemAdd:function(t){n.onChange&&n.onChange(t);e.options.api.corsProxy&&o(t)},onOptionRemove:function(){s("own");s("catalogue")},optgroups:[{value:"own",label:"History"},{value:"catalogue",label:"Catalogue"}],optgroupOrder:["own","catalogue"],sortField:"endpoint",valueField:"endpoint",labelField:"endpoint",searchField:["endpoint","text"],render:{option:function(e,t){var n='<a href="javascript:void(0)" class="close pull-right" tabindex="-1" title="Remove from '+("own"==e.optgroup?"history":"catalogue")+'">×</a>',r='<div class="endpointUrl">'+t(e.endpoint)+"</div>",i="";e.text&&(i='<div class="endpointTitle">'+t(e.text)+"</div>");return'<div class="endpointOptionRow">'+n+r+i+"</div>"}}}};n=n?t.extend(!0,{},u,n):u;
this.addClass("endpointText form-control");this.selectize(n.selectize);l[0].selectize.$dropdown.off("mousedown","[data-selectable]");l[0].selectize.$dropdown.on("mousedown","[data-selectable]",function(e){var n,r,i=l[0].selectize;if(e.preventDefault){e.preventDefault();e.stopPropagation()}r=t(e.currentTarget);if(t(e.target).hasClass("close")){l[0].selectize.removeOption(r.attr("data-value"));l[0].selectize.refreshOptions()}else if(r.hasClass("create"))i.createItem();else{n=r.attr("data-value");if("undefined"!=typeof n){i.lastQuery=null;i.setTextboxValue("");i.addItem(n);!i.settings.hideSelected&&e.type&&/mouse/.test(e.type)&&i.setActiveOption(i.getOption(n))}}});var p=function(e,t){t.optgroup&&s(t.optgroup)},c=function(e,t){if(e){l[0].selectize.off("option_add",p);e.forEach(function(e){l[0].selectize.addOption({endpoint:e.endpoint,text:e.title,optgroup:t})});l[0].selectize.on("option_add",p)}};a(c,"catalogue");a(c,"own");if(n.value){n.value in l[0].selectize.options||l[0].selectize.addOption({endpoint:n.value,optgroup:"own"});l[0].selectize.addItem(n.value)}return this};var i=function(){var e=[{endpoint:"http%3A%2F%2Fvisualdataweb.infor.uva.es%2Fsparql"},{endpoint:"http%3A%2F%2Fbiolit.rkbexplorer.com%2Fsparql",title:"A Short Biographical Dictionary of English Literature (RKBExplorer)"},{endpoint:"http%3A%2F%2Faemet.linkeddata.es%2Fsparql",title:"AEMET metereological dataset"},{endpoint:"http%3A%2F%2Fsparql.jesandco.org%3A8890%2Fsparql",title:"ASN:US"},{endpoint:"http%3A%2F%2Fdata.allie.dbcls.jp%2Fsparql",title:"Allie Abbreviation And Long Form Database in Life Science"},{endpoint:"http%3A%2F%2Fvocabulary.semantic-web.at%2FPoolParty%2Fsparql%2FAustrianSkiTeam",title:"Alpine Ski Racers of Austria"},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Feuropeana%2Fsparql%2F",title:"Amsterdam Museum as Linked Open Data in the Europeana Data Model"},{endpoint:"http%3A%2F%2Fopendata.aragon.es%2Fsparql",title:"AragoDBPedia"},{endpoint:"http%3A%2F%2Fdata.archiveshub.ac.uk%2Fsparql",title:"Archives Hub Linked Data"},{endpoint:"http%3A%2F%2Fwww.auth.gr%2Fsparql",title:"Aristotle University"},{endpoint:"http%3A%2F%2Facm.rkbexplorer.com%2Fsparql%2F",title:"Association for Computing Machinery (ACM) (RKBExplorer)"},{endpoint:"http%3A%2F%2Fabs.270a.info%2Fsparql",title:"Australian Bureau of Statistics (ABS) Linked Data"},{endpoint:"http%3A%2F%2Flab.environment.data.gov.au%2Fsparql",title:"Australian Climate Observations Reference Network - Surface Air Temperature Dataset"},{endpoint:"http%3A%2F%2Flod.b3kat.de%2Fsparql",title:"B3Kat - Library Union Catalogues of Bavaria, Berlin and Brandenburg"},{endpoint:"http%3A%2F%2Fdati.camera.it%2Fsparql"},{endpoint:"http%3A%2F%2Fbis.270a.info%2Fsparql",title:"Bank for International Settlements (BIS) Linked Data"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fbdgp_20081030",title:"Bdgp"},{endpoint:"http%3A%2F%2Faffymetrix.bio2rdf.org%2Fsparql",title:"Bio2RDF::Affymetrix"},{endpoint:"http%3A%2F%2Fbiomodels.bio2rdf.org%2Fsparql",title:"Bio2RDF::Biomodels"},{endpoint:"http%3A%2F%2Fbioportal.bio2rdf.org%2Fsparql",title:"Bio2RDF::Bioportal"},{endpoint:"http%3A%2F%2Fclinicaltrials.bio2rdf.org%2Fsparql",title:"Bio2RDF::Clinicaltrials"},{endpoint:"http%3A%2F%2Fctd.bio2rdf.org%2Fsparql",title:"Bio2RDF::Ctd"},{endpoint:"http%3A%2F%2Fdbsnp.bio2rdf.org%2Fsparql",title:"Bio2RDF::Dbsnp"},{endpoint:"http%3A%2F%2Fdrugbank.bio2rdf.org%2Fsparql",title:"Bio2RDF::Drugbank"},{endpoint:"http%3A%2F%2Fgenage.bio2rdf.org%2Fsparql",title:"Bio2RDF::Genage"},{endpoint:"http%3A%2F%2Fgendr.bio2rdf.org%2Fsparql",title:"Bio2RDF::Gendr"},{endpoint:"http%3A%2F%2Fgoa.bio2rdf.org%2Fsparql",title:"Bio2RDF::Goa"},{endpoint:"http%3A%2F%2Fhgnc.bio2rdf.org%2Fsparql",title:"Bio2RDF::Hgnc"},{endpoint:"http%3A%2F%2Fhomologene.bio2rdf.org%2Fsparql",title:"Bio2RDF::Homologene"},{endpoint:"http%3A%2F%2Finoh.bio2rdf.org%2Fsparql",title:"Bio2RDF::INOH"},{endpoint:"http%3A%2F%2Finterpro.bio2rdf.org%2Fsparql",title:"Bio2RDF::Interpro"},{endpoint:"http%3A%2F%2Fiproclass.bio2rdf.org%2Fsparql",title:"Bio2RDF::Iproclass"},{endpoint:"http%3A%2F%2Firefindex.bio2rdf.org%2Fsparql",title:"Bio2RDF::Irefindex"},{endpoint:"http%3A%2F%2Fbiopax.kegg.bio2rdf.org%2Fsparql",title:"Bio2RDF::KEGG::BioPAX"},{endpoint:"http%3A%2F%2Flinkedspl.bio2rdf.org%2Fsparql",title:"Bio2RDF::Linkedspl"},{endpoint:"http%3A%2F%2Flsr.bio2rdf.org%2Fsparql",title:"Bio2RDF::Lsr"},{endpoint:"http%3A%2F%2Fmesh.bio2rdf.org%2Fsparql",title:"Bio2RDF::Mesh"},{endpoint:"http%3A%2F%2Fmgi.bio2rdf.org%2Fsparql",title:"Bio2RDF::Mgi"},{endpoint:"http%3A%2F%2Fncbigene.bio2rdf.org%2Fsparql",title:"Bio2RDF::Ncbigene"},{endpoint:"http%3A%2F%2Fndc.bio2rdf.org%2Fsparql",title:"Bio2RDF::Ndc"},{endpoint:"http%3A%2F%2Fnetpath.bio2rdf.org%2Fsparql",title:"Bio2RDF::NetPath"},{endpoint:"http%3A%2F%2Fomim.bio2rdf.org%2Fsparql",title:"Bio2RDF::Omim"},{endpoint:"http%3A%2F%2Forphanet.bio2rdf.org%2Fsparql",title:"Bio2RDF::Orphanet"},{endpoint:"http%3A%2F%2Fpid.bio2rdf.org%2Fsparql",title:"Bio2RDF::PID"},{endpoint:"http%3A%2F%2Fbiopax.pharmgkb.bio2rdf.org%2Fsparql",title:"Bio2RDF::PharmGKB::BioPAX"},{endpoint:"http%3A%2F%2Fpharmgkb.bio2rdf.org%2Fsparql",title:"Bio2RDF::Pharmgkb"},{endpoint:"http%3A%2F%2Fpubchem.bio2rdf.org%2Fsparql",title:"Bio2RDF::PubChem"},{endpoint:"http%3A%2F%2Frhea.bio2rdf.org%2Fsparql",title:"Bio2RDF::Rhea"},{endpoint:"http%3A%2F%2Fspike.bio2rdf.org%2Fsparql",title:"Bio2RDF::SPIKE"},{endpoint:"http%3A%2F%2Fsabiork.bio2rdf.org%2Fsparql",title:"Bio2RDF::Sabiork"},{endpoint:"http%3A%2F%2Fsgd.bio2rdf.org%2Fsparql",title:"Bio2RDF::Sgd"},{endpoint:"http%3A%2F%2Fsider.bio2rdf.org%2Fsparql",title:"Bio2RDF::Sider"},{endpoint:"http%3A%2F%2Ftaxonomy.bio2rdf.org%2Fsparql",title:"Bio2RDF::Taxonomy"},{endpoint:"http%3A%2F%2Fwikipathways.bio2rdf.org%2Fsparql",title:"Bio2RDF::Wikipathways"},{endpoint:"http%3A%2F%2Fwormbase.bio2rdf.org%2Fsparql",title:"Bio2RDF::Wormbase"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fbiomodels%2Fsparql",title:"BioModels RDF"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fbiosamples%2Fsparql",title:"BioSamples RDF"},{endpoint:"http%3A%2F%2Fhelheim.deusto.es%2Fbizkaisense%2Fsparql",title:"BizkaiSense"},{endpoint:"http%3A%2F%2Fbnb.data.bl.uk%2Fsparql"},{endpoint:"http%3A%2F%2Fbudapest.rkbexplorer.com%2Fsparql%2F",title:"Budapest University of Technology and Economics (RKBExplorer)"},{endpoint:"http%3A%2F%2Fbfs.270a.info%2Fsparql",title:"Bundesamt für Statistik (BFS) - Swiss Federal Statistical Office (FSO) Linked Data"},{endpoint:"http%3A%2F%2Fopendata-bundestag.de%2Fsparql",title:"BundestagNebeneinkuenfte"},{endpoint:"http%3A%2F%2Fdata.colinda.org%2Fendpoint.php",title:"COLINDA - Conference Linked Data"},{endpoint:"http%3A%2F%2Fcrtm.linkeddata.es%2Fsparql",title:"CRTM"},{endpoint:"http%3A%2F%2Fdata.fundacionctic.org%2Fsparql",title:"CTIC Public Dataset Catalogs"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fchembl%2Fsparql",title:"ChEMBL RDF"},{endpoint:"http%3A%2F%2Fchebi.bio2rdf.org%2Fsparql",title:"Chemical Entities of Biological Interest (ChEBI)"},{endpoint:"http%3A%2F%2Fciteseer.rkbexplorer.com%2Fsparql%2F",title:"CiteSeer (Research Index) (RKBExplorer)"},{endpoint:"http%3A%2F%2Fcordis.rkbexplorer.com%2Fsparql%2F",title:"Community R&D Information Service (CORDIS) (RKBExplorer)"},{endpoint:"http%3A%2F%2Fsemantic.ckan.net%2Fsparql%2F",title:"Comprehensive Knowledge Archive Network"},{endpoint:"http%3A%2F%2Fvocabulary.wolterskluwer.de%2FPoolParty%2Fsparql%2Fcourt",title:"Courts thesaurus"},{endpoint:"http%3A%2F%2Fcultura.linkeddata.es%2Fsparql",title:"CulturaLinkedData"},{endpoint:"http%3A%2F%2Fdblp.rkbexplorer.com%2Fsparql%2F",title:"DBLP Computer Science Bibliography (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdblp.l3s.de%2Fd2r%2Fsparql",title:"DBLP in RDF (L3S)"},{endpoint:"http%3A%2F%2Fdbtune.org%2Fmusicbrainz%2Fsparql",title:"DBTune.org Musicbrainz D2R Server"},{endpoint:"http%3A%2F%2Fdbpedia.org%2Fsparql",title:"DBpedia"},{endpoint:"http%3A%2F%2Feu.dbpedia.org%2Fsparql",title:"DBpedia in Basque"},{endpoint:"http%3A%2F%2Fnl.dbpedia.org%2Fsparql",title:"DBpedia in Dutch"},{endpoint:"http%3A%2F%2Ffr.dbpedia.org%2Fsparql",title:"DBpedia in French"},{endpoint:"http%3A%2F%2Fde.dbpedia.org%2Fsparql",title:"DBpedia in German"},{endpoint:"http%3A%2F%2Fja.dbpedia.org%2Fsparql",title:"DBpedia in Japanese"},{endpoint:"http%3A%2F%2Fpt.dbpedia.org%2Fsparql",title:"DBpedia in Portuguese"},{endpoint:"http%3A%2F%2Fes.dbpedia.org%2Fsparql",title:"DBpedia in Spanish"},{endpoint:"http%3A%2F%2Flive.dbpedia.org%2Fsparql",title:"DBpedia-Live"},{endpoint:"http%3A%2F%2Fdeploy.rkbexplorer.com%2Fsparql%2F",title:"DEPLOY (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.ox.ac.uk%2Fsparql%2F"},{endpoint:"http%3A%2F%2Fdatos.bcn.cl%2Fsparql",title:"Datos.bcn.cl"},{endpoint:"http%3A%2F%2Fdeepblue.rkbexplorer.com%2Fsparql%2F",title:"Deep Blue (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdewey.info%2Fsparql.php",title:"Dewey Decimal Classification (DDC)"},{endpoint:"http%3A%2F%2Frdf.disgenet.org%2Fsparql%2F",title:"DisGeNET"},{endpoint:"http%3A%2F%2Fitaly.rkbexplorer.com%2Fsparql",title:"Diverse Italian ReSIST Partner Institutions (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdutchshipsandsailors.nl%2Fdata%2Fsparql%2F",title:"Dutch Ships and Sailors "},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Fdss%2Fsparql%2F",title:"Dutch Ships and Sailors "},{endpoint:"http%3A%2F%2Fwww.eclap.eu%2Fsparql",title:"ECLAP"},{endpoint:"http%3A%2F%2Fcr.eionet.europa.eu%2Fsparql"},{endpoint:"http%3A%2F%2Fera.rkbexplorer.com%2Fsparql%2F",title:"ERA - Australian Research Council publication ratings (RKBExplorer)"},{endpoint:"http%3A%2F%2Fkent.zpr.fer.hr%3A8080%2FeducationalProgram%2Fsparql",title:"Educational programs - SISVU"},{endpoint:"http%3A%2F%2Fwebenemasuno.linkeddata.es%2Fsparql",title:"El Viajero's tourism dataset"},{endpoint:"http%3A%2F%2Fwww.ida.liu.se%2Fprojects%2Fsemtech%2Fopenrdf-sesame%2Frepositories%2Fenergy",title:"Energy efficiency assessments and improvements"},{endpoint:"http%3A%2F%2Fheritagedata.org%2Flive%2Fsparql"},{endpoint:"http%3A%2F%2Fenipedia.tudelft.nl%2Fsparql",title:"Enipedia - Energy Industry Data"},{endpoint:"http%3A%2F%2Fenvironment.data.gov.uk%2Fsparql%2Fbwq%2Fquery",title:"Environment Agency Bathing Water Quality"},{endpoint:"http%3A%2F%2Fecb.270a.info%2Fsparql",title:"European Central Bank (ECB) Linked Data"},{endpoint:"http%3A%2F%2Fsemantic.eea.europa.eu%2Fsparql"},{endpoint:"http%3A%2F%2Feuropeana.ontotext.com%2Fsparql"},{endpoint:"http%3A%2F%2Feventmedia.eurecom.fr%2Fsparql",title:"EventMedia"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fforge%2Fquery",title:"FORGE Course information"},{endpoint:"http%3A%2F%2Ffactforge.net%2Fsparql",title:"Fact Forge"},{endpoint:"http%3A%2F%2Flogd.tw.rpi.edu%2Fsparql"},{endpoint:"http%3A%2F%2Ffrb.270a.info%2Fsparql",title:"Federal Reserve Board (FRB) Linked Data"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fflybase",title:"Flybase"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fflyted",title:"Flyted"},{endpoint:"http%3A%2F%2Ffao.270a.info%2Fsparql",title:"Food and Agriculture Organization of the United Nations (FAO) Linked Data"},{endpoint:"http%3A%2F%2Fft.rkbexplorer.com%2Fsparql%2F",title:"France Telecom Recherche et Développement (RKBExplorer)"},{endpoint:"http%3A%2F%2Flisbon.rkbexplorer.com%2Fsparql",title:"Fundação da Faculdade de Ciencas da Universidade de Lisboa (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Fatlas%2Fsparql",title:"Gene Expression Atlas RDF"},{endpoint:"http%3A%2F%2Fgeo.linkeddata.es%2Fsparql",title:"GeoLinkedData"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2FGeologicTimeScale",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2FGeologicUnit",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2Flithology",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fresource.geolba.ac.at%2FPoolParty%2Fsparql%2Ftectonicunit",title:"Geological Survey of Austria (GBA) - Thesaurus"},{endpoint:"http%3A%2F%2Fvocabulary.wolterskluwer.de%2FPoolParty%2Fsparql%2Farbeitsrecht",title:"German labor law thesaurus"},{endpoint:"http%3A%2F%2Fdata.globalchange.gov%2Fsparql",title:"Global Change Information System"},{endpoint:"http%3A%2F%2Fwordnet.okfn.gr%3A8890%2Fsparql%2F",title:"Greek Wordnet"},{endpoint:"http%3A%2F%2Flod.hebis.de%2Fsparql",title:"HeBIS - Bibliographic Resources of the Library Union Catalogues of Hessen and parts of the Rhineland Palatinate"},{endpoint:"http%3A%2F%2Fhealthdata.tw.rpi.edu%2Fsparql",title:"HealthData.gov Platform (HDP) on the Semantic Web"},{endpoint:"http%3A%2F%2Fhelheim.deusto.es%2Fhedatuz%2Fsparql",title:"Hedatuz"},{endpoint:"http%3A%2F%2Fgreek-lod.auth.gr%2Ffire-brigade%2Fsparql",title:"Hellenic Fire Brigade"},{endpoint:"http%3A%2F%2Fgreek-lod.auth.gr%2Fpolice%2Fsparql",title:"Hellenic Police"},{endpoint:"http%3A%2F%2Fsetaria.oszk.hu%2Fsparql",title:"Hungarian National Library (NSZL) catalog"},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Fiati%2Fsparql%2F",title:"IATI as Linked Data"},{endpoint:"http%3A%2F%2Fibm.rkbexplorer.com%2Fsparql%2F",title:"IBM Research GmbH (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwww.icane.es%2Fopendata%2Fsparql",title:"ICANE"},{endpoint:"http%3A%2F%2Fieee.rkbexplorer.com%2Fsparql%2F",title:"IEEE Papers (RKBExplorer)"},{endpoint:"http%3A%2F%2Fieeevis.tw.rpi.edu%2Fsparql",title:"IEEE VIS Source Data"},{endpoint:"http%3A%2F%2Fwww.imagesnippets.com%2Fsparql%2Fimages",title:"Imagesnippets Image Descriptions"},{endpoint:"http%3A%2F%2Fopendatacommunities.org%2Fsparql"},{endpoint:"http%3A%2F%2Fpurl.org%2Ftwc%2Fhub%2Fsparql",title:"Instance Hub (all)"},{endpoint:"http%3A%2F%2Feurecom.rkbexplorer.com%2Fsparql%2F",title:"Institut Eurécom (RKBExplorer)"},{endpoint:"http%3A%2F%2Fimf.270a.info%2Fsparql",title:"International Monetary Fund (IMF) Linked Data"},{endpoint:"http%3A%2F%2Fwww.rechercheisidore.fr%2Fsparql",title:"Isidore"},{endpoint:"http%3A%2F%2Fsparql.kupkb.org%2Fsparql",title:"Kidney and Urinary Pathway Knowledge Base"},{endpoint:"http%3A%2F%2Fkisti.rkbexplorer.com%2Fsparql%2F",title:"Korean Institute of Science Technology and Information (RKBExplorer)"},{endpoint:"http%3A%2F%2Flod.kaist.ac.kr%2Fsparql",title:"Korean Traditional Recipes"},{endpoint:"http%3A%2F%2Flaas.rkbexplorer.com%2Fsparql%2F",title:"LAAS-CNRS (RKBExplorer)"},{endpoint:"http%3A%2F%2Fsmartcity.linkeddata.es%2Fsparql",title:"LCC (Leeds City Council Energy Consumption Linked Data)"},{endpoint:"http%3A%2F%2Flod.ac%2Fbdls%2Fsparql",title:"LODAC BDLS"},{endpoint:"http%3A%2F%2Fdata.linkededucation.org%2Frequest%2Flak-conference%2Fsparql",title:"Learning Analytics and Knowledge (LAK) Dataset"},{endpoint:"http%3A%2F%2Fwww.linklion.org%3A8890%2Fsparql",title:"LinkLion - A Link Repository for the Web of Data"},{endpoint:"http%3A%2F%2Fsparql.reegle.info%2F",title:"Linked Clean Energy Data (reegle.info)"},{endpoint:"http%3A%2F%2Fsparql.contextdatacloud.org",title:"Linked Crowdsourced Data"},{endpoint:"http%3A%2F%2Flinkedlifedata.com%2Fsparql",title:"Linked Life Data"},{endpoint:"http%3A%2F%2Fdata.logainm.ie%2Fsparql",title:"Linked Logainm"},{endpoint:"http%3A%2F%2Fdata.linkedmdb.org%2Fsparql",title:"Linked Movie DataBase"},{endpoint:"http%3A%2F%2Fdata.aalto.fi%2Fsparql",title:"Linked Open Aalto Data Service"},{endpoint:"http%3A%2F%2Fdbmi-icode-01.dbmi.pitt.edu%2FlinkedSPLs%2Fsparql",title:"Linked Structured Product Labels"},{endpoint:"http%3A%2F%2Flinkedgeodata.org%2Fsparql%2F",title:"LinkedGeoData"},{endpoint:"http%3A%2F%2Flinkedspending.aksw.org%2Fsparql",title:"LinkedSpending: OpenSpending becomes Linked Open Data"},{endpoint:"http%3A%2F%2Fhelheim.deusto.es%2Flinkedstats%2Fsparql",title:"LinkedStats"},{endpoint:"http%3A%2F%2Flinkedu.eu%2Fcatalogue%2Fsparql%2F",title:"LinkedUp Catalogue of Educational Datasets"},{endpoint:"http%3A%2F%2Fid.sgcb.mcu.es%2Fsparql",title:"Lista de Encabezamientos de Materia as Linked Open Data"},{endpoint:"http%3A%2F%2Fonto.mondis.cz%2Fopenrdf-sesame%2Frepositories%2Fmondis-record-owlim",title:"MONDIS"},{endpoint:"http%3A%2F%2Fapps.morelab.deusto.es%2Flabman%2Fsparql",title:"MORElab"},{endpoint:"http%3A%2F%2Fsparql.msc2010.org",title:"Mathematics Subject Classification"},{endpoint:"http%3A%2F%2Fdoc.metalex.eu%3A8000%2Fsparql%2F",title:"MetaLex Document Server"},{endpoint:"http%3A%2F%2Frdf.muninn-project.org%2Fsparql",title:"Muninn World War I"},{endpoint:"http%3A%2F%2Flod.sztaki.hu%2Fsparql",title:"National Digital Data Archive of Hungary (partial)"},{endpoint:"http%3A%2F%2Fnsf.rkbexplorer.com%2Fsparql%2F",title:"National Science Foundation (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.nobelprize.org%2Fsparql",title:"Nobel Prizes"},{endpoint:"http%3A%2F%2Fdata.lenka.no%2Fsparql",title:"Norwegian geo-divisions"},{endpoint:"http%3A%2F%2Fspatial.ucd.ie%2Flod%2Fsparql",title:"OSM Semantic Network"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fdon%2Fquery",title:"OUNL DSpace in RDF"},{endpoint:"http%3A%2F%2Fdata.oceandrilling.org%2Fsparql"},{endpoint:"http%3A%2F%2Fonto.beef.org.pl%2Fsparql",title:"OntoBeef"},{endpoint:"http%3A%2F%2Foai.rkbexplorer.com%2Fsparql%2F",title:"Open Archive Initiative Harvest over OAI-PMH (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Focw%2Fquery",title:"Open Courseware Consortium metadata in RDF"},{endpoint:"http%3A%2F%2Fopendata.ccd.uniroma2.it%2FLMF%2Fsparql%2Fselect",title:"Open Data @ Tor Vergata"},{endpoint:"http%3A%2F%2Fvocabulary.semantic-web.at%2FPoolParty%2Fsparql%2FOpenData",title:"Open Data Thesaurus"},{endpoint:"http%3A%2F%2Fdata.cnr.it%2Fsparql-proxy%2F",title:"Open Data from the Italian National Research Council"},{endpoint:"http%3A%2F%2Fdata.utpl.edu.ec%2Fecuadorresearch%2Flod%2Fsparql",title:"Open Data of Ecuador"},{endpoint:"http%3A%2F%2Fen.openei.org%2Fsparql",title:"OpenEI - Open Energy Info"},{endpoint:"http%3A%2F%2Flod.openlinksw.com%2Fsparql",title:"OpenLink Software LOD Cache"},{endpoint:"http%3A%2F%2Fsparql.openmobilenetwork.org",title:"OpenMobileNetwork"},{endpoint:"http%3A%2F%2Fapps.ideaconsult.net%3A8080%2Fontology",title:"OpenTox"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Fcoins%2Fsparql",title:"OpenUpLabs COINS"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Fdclg%2Fsparql",title:"OpenUpLabs DCLG"},{endpoint:"http%3A%2F%2Fos.services.tso.co.uk%2Fgeo%2Fsparql",title:"OpenUpLabs Geographic"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Flegislation%2Fsparql",title:"OpenUpLabs Legislation"},{endpoint:"http%3A%2F%2Fgov.tso.co.uk%2Ftransport%2Fsparql",title:"OpenUpLabs Transport"},{endpoint:"http%3A%2F%2Fos.rkbexplorer.com%2Fsparql%2F",title:"Ordnance Survey (RKBExplorer)"},{endpoint:"http%3A%2F%2Fdata.organic-edunet.eu%2Fsparql",title:"Organic Edunet Linked Open Data"},{endpoint:"http%3A%2F%2Foecd.270a.info%2Fsparql",title:"Organisation for Economic Co-operation and Development (OECD) Linked Data"},{endpoint:"https%3A%2F%2Fdata.ox.ac.uk%2Fsparql%2F",title:"OxPoints (University of Oxford)"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fprod%2Fquery",title:"PROD - JISC Project Directory in RDF"},{endpoint:"http%3A%2F%2Fld.panlex.org%2Fsparql",title:"PanLex"},{endpoint:"http%3A%2F%2Flinked-data.org%2Fsparql",title:"Phonetics Information Base and Lexicon (PHOIBLE)"},{endpoint:"http%3A%2F%2Flinked.opendata.cz%2Fsparql",title:"Publications of Charles University in Prague"},{endpoint:"http%3A%2F%2Flinkeddata4.dia.fi.upm.es%3A8907%2Fsparql",title:"RDFLicense"},{endpoint:"http%3A%2F%2Frisks.rkbexplorer.com%2Fsparql%2F",title:"RISKS Digest (RKBExplorer)"},{endpoint:"http%3A%2F%2Fruian.linked.opendata.cz%2Fsparql",title:"RUIAN - Register of territorial identification, addresses and real estates of the Czech Republic"},{endpoint:"http%3A%2F%2Fcurriculum.rkbexplorer.com%2Fsparql%2F",title:"ReSIST MSc in Resilient Computing Curriculum (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwiki.rkbexplorer.com%2Fsparql%2F",title:"ReSIST Project Wiki (RKBExplorer)"},{endpoint:"http%3A%2F%2Fresex.rkbexplorer.com%2Fsparql%2F",title:"ReSIST Resilience Mechanisms (RKBExplorer.com)"},{endpoint:"https%3A%2F%2Fwww.ebi.ac.uk%2Frdf%2Fservices%2Freactome%2Fsparql",title:"Reactome RDF"},{endpoint:"http%3A%2F%2Flod.xdams.org%2Fsparql"},{endpoint:"http%3A%2F%2Frae2001.rkbexplorer.com%2Fsparql%2F",title:"Research Assessment Exercise 2001 (RKBExplorer)"},{endpoint:"http%3A%2F%2Fcourseware.rkbexplorer.com%2Fsparql%2F",title:"Resilient Computing Courseware (RKBExplorer)"},{endpoint:"http%3A%2F%2Flink.informatics.stonybrook.edu%2Fsparql%2F",title:"RxNorm"},{endpoint:"http%3A%2F%2Fdata.rism.info%2Fsparql"},{endpoint:"http%3A%2F%2Fbiordf.net%2Fsparql",title:"SADI Semantic Web Services framework registry"},{endpoint:"http%3A%2F%2Fseek.rkbexplorer.com%2Fsparql%2F",title:"SEEK-AT-WD ICT tools for education - Web-Share"},{endpoint:"http%3A%2F%2Fzbw.eu%2Fbeta%2Fsparql%2Fstw%2Fquery",title:"STW Thesaurus for Economics"},{endpoint:"http%3A%2F%2Fsouthampton.rkbexplorer.com%2Fsparql%2F",title:"School of Electronics and Computer Science, University of Southampton (RKBExplorer)"},{endpoint:"http%3A%2F%2Fserendipity.utpl.edu.ec%2Flod%2Fsparql",title:"Serendipity"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fslidewiki%2Fquery",title:"Slidewiki (RDF/SPARQL)"},{endpoint:"http%3A%2F%2Fsmartlink.open.ac.uk%2Fsmartlink%2Fsparql",title:"SmartLink: Linked Services Non-Functional Properties"},{endpoint:"http%3A%2F%2Fsocialarchive.iath.virginia.edu%2Fsparql%2Feac",title:"Social Networks and Archival Context Fall 2011"},{endpoint:"http%3A%2F%2Fsocialarchive.iath.virginia.edu%2Fsparql%2Fsnac-viaf",title:"Social Networks and Archival Context Fall 2011"},{endpoint:"http%3A%2F%2Fvocabulary.semantic-web.at%2FPoolParty%2Fsparql%2Fsemweb",title:"Social Semantic Web Thesaurus"},{endpoint:"http%3A%2F%2Flinguistic.linkeddata.es%2Fsparql",title:"Spanish Linguistic Datasets"},{endpoint:"http%3A%2F%2Fcrashmap.okfn.gr%3A8890%2Fsparql",title:"Statistics on Fatal Traffic Accidents in greek roads"},{endpoint:"http%3A%2F%2Fcrime.rkbexplorer.com%2Fsparql%2F",title:"Street level crime reports for England and Wales"},{endpoint:"http%3A%2F%2Fsymbolicdata.org%3A8890%2Fsparql",title:"SymbolicData"},{endpoint:"http%3A%2F%2Fagalpha.mathbiol.org%2Frepositories%2Ftcga",title:"TCGA Roadmap"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Ftcm",title:"TCMGeneDIT Dataset"},{endpoint:"http%3A%2F%2Fdata.linkededucation.org%2Frequest%2Fted%2Fsparql",title:"TED Talks"},{endpoint:"http%3A%2F%2Fdarmstadt.rkbexplorer.com%2Fsparql%2F",title:"Technische Universität Darmstadt (RKBExplorer)"},{endpoint:"http%3A%2F%2Flinguistic.linkeddata.es%2Fterminesp%2Fsparql-editor",title:"Terminesp Linked Data"},{endpoint:"http%3A%2F%2Facademia6.poolparty.biz%2FPoolParty%2Fsparql%2FTesauro-Materias-BUPM",title:"Tesauro materias BUPM"},{endpoint:"http%3A%2F%2Fapps.morelab.deusto.es%2Fteseo%2Fsparql",title:"Teseo"},{endpoint:"http%3A%2F%2Flinkeddata.ge.imati.cnr.it%3A8890%2Fsparql",title:"ThIST"},{endpoint:"http%3A%2F%2Fring.ciard.net%2Fsparql1",title:"The CIARD RING"},{endpoint:"http%3A%2F%2Fvocab.getty.edu%2Fsparql"},{endpoint:"http%3A%2F%2Flod.gesis.org%2Fthesoz%2Fsparql",title:"TheSoz Thesaurus for the Social Sciences (GESIS)"},{endpoint:"http%3A%2F%2Fdigitale.bncf.firenze.sbn.it%2Fopenrdf-workbench%2Frepositories%2FNS%2Fquery",title:"Thesaurus BNCF"},{endpoint:"http%3A%2F%2Ftour-pedia.org%2Fsparql",title:"Tourpedia"},{endpoint:"http%3A%2F%2Ftkm.kiom.re.kr%2Fontology%2Fsparql",title:"Traditional Korean Medicine Ontology"},{endpoint:"http%3A%2F%2Ftransparency.270a.info%2Fsparql",title:"Transparency International Linked Data"},{endpoint:"http%3A%2F%2Fjisc.rkbexplorer.com%2Fsparql%2F",title:"UK JISC (RKBExplorer)"},{endpoint:"http%3A%2F%2Funlocode.rkbexplorer.com%2Fsparql%2F",title:"UN/LOCODE (RKBExplorer)"},{endpoint:"http%3A%2F%2Fuis.270a.info%2Fsparql",title:"UNESCO Institute for Statistics (UIS) Linked Data"},{endpoint:"http%3A%2F%2Fskos.um.es%2Fsparql%2F",title:"UNESCO Thesaurus"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fkis1112%2Fquery",title:"UNISTAT-KIS 2011/2012 in RDF (Key Information Set - UK Universities)"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fkis%2Fquery",title:"UNISTAT-KIS in RDF (Key Information Set - UK Universities)"},{endpoint:"http%3A%2F%2Flinkeddata.uriburner.com%2Fsparql",title:"URIBurner"},{endpoint:"http%3A%2F%2Fbeta.sparql.uniprot.org"},{endpoint:"http%3A%2F%2Fdata.utpl.edu.ec%2Futpl%2Flod%2Fsparql",title:"Universidad Técnica Particular de Loja - Linked Open Data"},{endpoint:"http%3A%2F%2Fresrev.ilrt.bris.ac.uk%2Fdata-server-workshop%2Fsparql",title:"University of Bristol"},{endpoint:"http%3A%2F%2Fdata.linkedu.eu%2Fhud%2Fquery",title:"University of Huddersfield -- Circulation and Recommendation Data"},{endpoint:"http%3A%2F%2Fnewcastle.rkbexplorer.com%2Fsparql%2F",title:"University of Newcastle upon Tyne (RKBExplorer)"},{endpoint:"http%3A%2F%2Froma.rkbexplorer.com%2Fsparql%2F",title:'Università degli studi di Roma "La Sapienza" (RKBExplorer)'},{endpoint:"http%3A%2F%2Fpisa.rkbexplorer.com%2Fsparql%2F",title:"Università di Pisa (RKBExplorer)"},{endpoint:"http%3A%2F%2Fulm.rkbexplorer.com%2Fsparql%2F",title:"Universität Ulm (RKBExplorer)"},{endpoint:"http%3A%2F%2Firit.rkbexplorer.com%2Fsparql%2F",title:"Université Paul Sabatier - Toulouse 3 (RKB Explorer)"},{endpoint:"http%3A%2F%2Fsemanticweb.cs.vu.nl%2Fverrijktkoninkrijk%2Fsparql%2F",title:"Verrijkt Koninkrijk"},{endpoint:"http%3A%2F%2Fkaunas.rkbexplorer.com%2Fsparql",title:"Vytautas Magnus University, Kaunas (RKBExplorer)"},{endpoint:"http%3A%2F%2Fwebscience.rkbexplorer.com%2Fsparql",title:"Web Science Conference (RKBExplorer)"},{endpoint:"http%3A%2F%2Fsparql.wikipathways.org%2F",title:"WikiPathways"},{endpoint:"http%3A%2F%2Fwww.opmw.org%2Fsparql",title:"Wings workflow provenance dataset"},{endpoint:"http%3A%2F%2Fwordnet.rkbexplorer.com%2Fsparql%2F",title:"WordNet (RKBExplorer)"},{endpoint:"http%3A%2F%2Fworldbank.270a.info%2Fsparql",title:"World Bank Linked Data"},{endpoint:"http%3A%2F%2Fmlode.nlp2rdf.org%2Fsparql"},{endpoint:"http%3A%2F%2Fldf.fi%2Fww1lod%2Fsparql",title:"World War 1 as Linked Open Data"},{endpoint:"http%3A%2F%2Faksw.org%2Fsparql",title:"aksw.org Research Group dataset"},{endpoint:"http%3A%2F%2Fcrm.rkbexplorer.com%2Fsparql",title:"crm"},{endpoint:"http%3A%2F%2Fdata.open.ac.uk%2Fquery",title:"data.open.ac.uk, Linked Data from the Open University"},{endpoint:"http%3A%2F%2Fsparql.data.southampton.ac.uk%2F"},{endpoint:"http%3A%2F%2Fdatos.bne.es%2Fsparql",title:"datos.bne.es"},{endpoint:"http%3A%2F%2Fkaiko.getalp.org%2Fsparql",title:"dbnary"},{endpoint:"http%3A%2F%2Fdigitaleconomy.rkbexplorer.com%2Fsparql",title:"digitaleconomy"},{endpoint:"http%3A%2F%2Fdotac.rkbexplorer.com%2Fsparql%2F",title:"dotAC (RKBExplorer)"},{endpoint:"http%3A%2F%2Fforeign.rkbexplorer.com%2Fsparql%2F",title:"ePrints Harvest (RKBExplorer)"},{endpoint:"http%3A%2F%2Feprints.rkbexplorer.com%2Fsparql%2F",title:"ePrints3 Institutional Archive Collection (RKBExplorer)"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Feducation%2Fsparql",title:"education.data.gov.uk"},{endpoint:"http%3A%2F%2Fepsrc.rkbexplorer.com%2Fsparql",title:"epsrc"},{endpoint:"http%3A%2F%2Fwww.open-biomed.org.uk%2Fsparql%2Fendpoint%2Fflyatlas",title:"flyatlas"},{endpoint:"http%3A%2F%2Fiserve.kmi.open.ac.uk%2Fiserve%2Fsparql",title:"iServe: Linked Services Registry"},{endpoint:"http%3A%2F%2Fichoose.tw.rpi.edu%2Fsparql",title:"ichoose"},{endpoint:"http%3A%2F%2Fkdata.kr%2Fsparql%2Fendpoint.jsp",title:"kdata"},{endpoint:"http%3A%2F%2Flofd.tw.rpi.edu%2Fsparql",title:"lofd"},{endpoint:"http%3A%2F%2Fprovenanceweb.org%2Fsparql",title:"provenanceweb"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Freference%2Fsparql",title:"reference.data.gov.uk"},{endpoint:"http%3A%2F%2Fforeign.rkbexplorer.com%2Fsparql",title:"rkb-explorer-foreign"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Fstatistics%2Fsparql",title:"statistics.data.gov.uk"},{endpoint:"http%3A%2F%2Fservices.data.gov.uk%2Ftransport%2Fsparql",title:"transport.data.gov.uk"},{endpoint:"http%3A%2F%2Fopendap.tw.rpi.edu%2Fsparql",title:"twc-opendap"},{endpoint:"http%3A%2F%2Fwebconf.rkbexplorer.com%2Fsparql",title:"webconf"},{endpoint:"http%3A%2F%2Fwiktionary.dbpedia.org%2Fsparql",title:"wiktionary.dbpedia.org"},{endpoint:"http%3A%2F%2Fdiwis.imis.athena-innovation.gr%3A8181%2Fsparql",title:"xxxxx"}];e.forEach(function(t,n){e[n].endpoint=decodeURIComponent(t.endpoint)});e.sort(function(e,t){var n=e.title||e.endpoint,r=t.title||t.endpoint;return n.toUpperCase().localeCompare(r.toUpperCase())});return e}},{jquery:void 0,selectize:5,"yasgui-utils":9}],89:[function(e){e("./outsideclick.js");e("./tab.js");e("./endpointCombi.js")},{"./endpointCombi.js":88,"./outsideclick.js":90,"./tab.js":91}],90:[function(e){"use strict";var t=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.fn.onOutsideClick=function(e,n){n=t.extend({skipFirst:!1,allowedElements:t()},n);var r=t(this),i=function(o){var s=function(e){return!e.is(o.target)&&0===e.has(o.target).length};if(s(r)&&s(n.allowedElements))if(n.skipFirst)n.skipFirst=!1;else{e();t(document).off("mouseup",i)}};t(document).mouseup(i);return this}},{jquery:void 0}],91:[function(e){function t(e){return this.each(function(){var t=n(this),i=t.data("bs.tab");i||t.data("bs.tab",i=new r(this));"string"==typeof e&&i[e]()})}var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=function(e){this.element=n(e)};r.VERSION="3.3.1";r.TRANSITION_DURATION=150;r.prototype.show=function(){var e=this.element,t=e.closest("ul:not(.dropdown-menu)"),r=e.data("target");if(!r){r=e.attr("href");r=r&&r.replace(/.*(?=#[^\s]*$)/,"")}if(!e.parent("li").hasClass("active")){var i=t.find(".active:last a"),o=n.Event("hide.bs.tab",{relatedTarget:e[0]}),s=n.Event("show.bs.tab",{relatedTarget:i[0]});i.trigger(o);e.trigger(s);if(!s.isDefaultPrevented()&&!o.isDefaultPrevented()){var a=n(r);this.activate(e.closest("li"),t);this.activate(a,a.parent(),function(){i.trigger({type:"hidden.bs.tab",relatedTarget:e[0]});e.trigger({type:"shown.bs.tab",relatedTarget:i[0]})})}}};r.prototype.activate=function(e,t,i){function o(){s.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1);e.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0);if(a){e[0].offsetWidth;e.addClass("in")}else e.removeClass("fade");e.parent(".dropdown-menu")&&e.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0);i&&i()}var s=t.find("> .active"),a=i&&n.support.transition&&(s.length&&s.hasClass("fade")||!!t.find("> .fade").length);s.length&&a?s.one("bsTransitionEnd",o).emulateTransitionEnd(r.TRANSITION_DURATION):o();s.removeClass("in")};var i=n.fn.tab;n.fn.tab=t;n.fn.tab.Constructor=r;n.fn.tab.noConflict=function(){n.fn.tab=i;return this};var o=function(e){e.preventDefault();t.call(n(this),"show")};n(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',o).on("click.bs.tab.data-api",'[data-toggle="pill"]',o)},{jquery:void 0}],92:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("yasgui-utils");e("./jquery/extendJquery.js");var i=t.exports=function(t,o){var s={};s.wrapperElement=n('<div class="yasgui"></div>').appendTo(n(t));s.options=n.extend(!0,{},i.defaults,o);s.history=[];s.persistencyPrefix=null;s.options.persistencyPrefix&&(s.persistencyPrefix="function"==typeof s.options.persistencyPrefix?s.options.persistencyPrefix(s):s.options.persistencyPrefix);if(s.persistencyPrefix){var a=r.storage.get(s.persistencyPrefix+"history");a&&(s.history=a)}s.store=function(){s.persistentOptions&&r.storage.set(s.persistencyPrefix,s.persistentOptions)};var l=function(){var e=r.storage.get(s.persistencyPrefix);e||(e={});return e};s.persistentOptions=l();s.tabManager=e("./tabManager.js")(s);
s.tabManager.init();return s};i.YASQE=e("yasgui-yasqe");i.YASQE.defaults=n.extend(!0,i.YASQE.defaults,e("./defaultsYasqe.js"));i.YASR=e("yasgui-yasr");i.$=n;i.defaults=e("./defaults.js")},{"./defaults.js":85,"./defaultsYasqe.js":86,"./jquery/extendJquery.js":89,"./tabManager.js":95,jquery:void 0,"yasgui-utils":9,"yasgui-yasqe":38,"yasgui-yasr":74}],93:[function(e,t){var n=function(e){var t=[];e||(e=window.location.search.substring(1));if(e.length>0)for(var n=e.split("&"),r=0;r<n.length;r++){var i=n[r].split("="),o=i[0],s=i[1];if(o.length>0&&s&&s.length>0){s=s.replace(/\+/g," ");s=decodeURIComponent(s);t.push({name:i[0],value:s})}}return t};t.exports={getCreateLinkHandler:function(e){return function(){var t=[{name:"outputFormat",value:e.yasr.options.output},{name:"query",value:e.yasqe.getValue()},{name:"contentTypeConstruct",value:e.persistentOptions.yasqe.sparql.acceptHeaderGraph},{name:"contentTypeSelect",value:e.persistentOptions.yasqe.sparql.acceptHeaderSelect},{name:"endpoint",value:e.persistentOptions.yasqe.sparql.endpoint},{name:"requestMethod",value:e.persistentOptions.yasqe.sparql.requestMethod},{name:"tabTitle",value:e.persistentOptions.name}];e.persistentOptions.yasqe.sparql.args.forEach(function(e){t.push(e)});e.persistentOptions.yasqe.sparql.namedGraphs.forEach(function(e){t.push({name:"namedGraph",value:e})});e.persistentOptions.yasqe.sparql.defaultGraphs.forEach(function(e){t.push({name:"defaultGraph",value:e})});var r=[];t.forEach(function(e){r.push(e.name)});var i=n();i.forEach(function(e){-1==r.indexOf(e.name)&&t.push(e)});return t}},getOptionsFromUrl:function(){var e={yasqe:{sparql:{}},yasr:{}},t=n(),r=!1;t.forEach(function(t){if("query"==t.name){r=!0;e.yasqe.value=t.value}else if("outputFormat"==t.name){var n=t.value;"simpleTable"==n&&(n="table");e.yasr.output=n}else if("contentTypeConstruct"==t.name)e.yasqe.sparql.acceptHeaderGraph=t.value;else if("contentTypeSelect"==t.name)e.yasqe.sparql.acceptHeaderSelect=t.value;else if("endpoint"==t.name)e.yasqe.sparql.endpoint=t.value;else if("requestMethod"==t.name)e.yasqe.sparql.requestMethod=t.value;else if("tabTitle"==t.name)e.name=t.value;else if("namedGraph"==t.name){e.yasqe.namedGraphs||(e.yasqe.namedGraphs=[]);e.yasqe.sparql.namedGraphs.push(t)}else if("defaultGraph"==t.name){e.yasqe.defaultGraphs||(e.yasqe.defaultGraphs=[]);e.yasqe.sparql.defaultGraphs.push(t)}else{e.yasqe.args||(e.yasqe.args=[]);e.yasqe.sparql.args.push(t)}});return r?e:null}}},{}],94:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=(e("./utils.js"),e("yasgui-utils")),i=e("./main.js"),o={yasqe:{sparql:{endpoint:i.YASQE.defaults.sparql.endpoint,acceptHeaderGraph:i.YASQE.defaults.sparql.acceptHeaderGraph,acceptHeaderSelect:i.YASQE.defaults.sparql.acceptHeaderSelect,args:i.YASQE.defaults.sparql.args,defaultGraphs:i.YASQE.defaults.sparql.defaultGraphs,namedGraphs:i.YASQE.defaults.sparql.namedGraphs,requestMethod:i.YASQE.defaults.sparql.requestMethod}}};t.exports=function(t,s,a){t.persistentOptions.tabManager.tabs[s]=t.persistentOptions.tabManager.tabs[s]?n.extend(!0,{},o,t.persistentOptions.tabManager.tabs[s]):n.extend(!0,{id:s,name:a},o);var l,u=t.persistentOptions.tabManager.tabs[s],p={persistentOptions:u},c=e("./tabPaneMenu.js")(t,p),d=n("<div>",{id:u.id,style:"position:relative","class":"tab-pane",role:"tabpanel"}).appendTo(t.tabManager.$tabPanesParent),f=n("<div>",{"class":"wrapper"}).appendTo(d),h=n("<div>",{"class":"controlbar"}).appendTo(f),g=(c.initWrapper().appendTo(d),function(){n("<button>",{type:"button","class":"menuButton btn btn-default"}).on("click",function(){if(d.hasClass("menu-open")){d.removeClass("menu-open");c.store()}else{c.updateWrapper();d.addClass("menu-open");n(".menu-slide,.menuButton").onOutsideClick(function(){d.removeClass("menu-open");c.store()})}}).append(n("<span>",{"class":"icon-bar"})).append(n("<span>",{"class":"icon-bar"})).append(n("<span>",{"class":"icon-bar"})).appendTo(h);l=n("<select>").appendTo(h).endpointCombi(t,{value:u.yasqe.sparql.endpoint,onChange:function(e){u.yasqe.sparql.endpoint=e;p.refreshYasqe();t.store()}})}),m=n("<div>",{id:"yasqe_"+u.id}).appendTo(f),E=n("<div>",{id:"yasq_"+u.id}).appendTo(f),v={createShareLink:e("./shareLink").getCreateLinkHandler(p)},x=function(){u.yasqe.value=p.yasqe.getValue();var e=null;p.yasr.results.getBindings()&&(e=p.yasr.results.getBindings().length);var i={options:n.extend(!0,{},u),resultSize:e};delete i.options.name;t.history.unshift(i);var o=50;t.history.length>o&&(t.history=t.history.slice(0,o));t.persistencyPrefix&&r.storage.set(t.persistencyPrefix+"history",t.history)};p.setPersistentInYasqe=function(){if(p.yasqe){n.extend(!0,p.yasqe.options,u.yasqe);p.yasqe.setValue(u.yasqe.value)}};n.extend(v,u.yasqe);p.onShow=function(){if(!p.yasqe||!p.yasr){p.yasqe=i.YASQE(m[0],v);p.yasqe.on("blur",function(e){u.yasqe.value=e.getValue();t.store()});p.yasr=i.YASR(E[0],n.extend({getUsedPrefixes:p.yasqe.getPrefixesFromQuery},u.yasr));p.yasqe.options.sparql.callbacks.complete=function(){p.yasr.setResponse.apply(this,arguments);x()};p.yasqe.query=function(){if(t.options.api.corsProxy&&t.corsEnabled)if(t.corsEnabled[u.yasqe.sparql.endpoint])i.YASQE.executeQuery(p.yasqe);else{var e=n.extend(!0,{},p.yasqe.options.sparql);e.args.push({name:"endpoint",value:e.endpoint});e.args.push({name:"requestMethod",value:e.requestMethod});e.requestMethod="POST";e.endpoint=t.options.api.corsProxy;i.YASQE.executeQuery(p.yasqe,e)}else i.YASQE.executeQuery(p.yasqe)};g()}};p.refreshYasqe=function(){n.extend(!0,p.yasqe.options,p.persistentOptions.yasqe);p.persistentOptions.yasqe.value&&p.yasqe.setValue(p.persistentOptions.yasqe.value)};p.destroy=function(){p.yasr||(p.yasr=i.YASR(E[0],{},""));r.storage.remove(p.yasr.getPersistencyId(p.yasr.options.persistency.results.key))};return p}},{"./main.js":92,"./shareLink":93,"./tabPaneMenu.js":96,"./utils.js":97,jquery:void 0,"yasgui-utils":9}],95:[function(e,t){"use strict";{var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("yasgui-utils"),e("./imgs.js")}e("jquery-ui/position");t.exports=function(t){t.persistentOptions.tabManager||(t.persistentOptions.tabManager={});var r=t.persistentOptions.tabManager,i={};i.tabs={};var o,s=null,a=null,l=function(e,t){e||(e="Query");t||(t=0);var n=e+(t>0?" "+t:"");u(n)&&(n=l(e,t+1));return n},u=function(e){for(var t in i.tabs)if(i.tabs[t].persistentOptions.name==e)return!0;return!1},p=function(){return Math.random().toString(36).substring(7)};i.init=function(){s=n("<div>",{role:"tabpanel"}).appendTo(t.wrapperElement);o=n("<ul>",{"class":"nav nav-tabs mainTabs",role:"tablist"}).appendTo(s);var l=n("<a>",{role:"addTab"}).click(function(){f()}).text("+");o.append(n("<li>",{role:"presentation"}).append(l));i.$tabPanesParent=n("<div>",{"class":"tab-content"}).appendTo(s);if(!r||n.isEmptyObject(r)){r.tabOrder=[];r.tabs={};r.selected=null}var u=e("./shareLink.js").getOptionsFromUrl();if(u){var c=p();u.id=c;r.tabs[c]=u;r.tabOrder.push(c);r.selected=c}r.tabOrder.length>0?r.tabOrder.forEach(f):f();o.sortable({placeholder:"tab-sortable-highlight",items:'li:has([data-toggle="tab"])',forcePlaceholderSize:!0,update:function(){var e=[];o.find('a[data-toggle="tab"]').each(function(){e.push(n(this).attr("aria-controls"))});r.tabOrder=e;t.store()}});a=n("<div>",{"class":"tabDropDown"}).appendTo(t.wrapperElement);var h=n("<ul>",{"class":"dropdown-menu",role:"menu"}).appendTo(a),g=function(e,t){var r=n("<li>",{role:"presentation"}).appendTo(h);e?r.append(n("<a>",{role:"menuitem",href:"#"}).text(e)).click(function(){a.hide();event.preventDefault();t&&t(a.attr("target-tab"))}):r.addClass("divider")};g("Rename",function(e){o.find('a[href="#'+e+'"]').dblclick()});g("Copy",function(){console.log("todo")});g();g("Close",d);g("Close others",function(e){o.find('a[role="tab"]').each(function(){var t=n(this).attr("aria-controls");t!=e&&d(t)})});g("Close all",function(){o.find('a[role="tab"]').each(function(){d(n(this).attr("aria-controls"))})})};var c=function(e){o.find('a[aria-controls="'+e+'"]').tab("show")},d=function(e){i.tabs[e].destroy();delete i.tabs[e];delete r.tabs[e];var s=r.tabOrder.indexOf(e);s>-1&&r.tabOrder.splice(s,1);var a=null;r.tabOrder[s]?a=s:r.tabOrder[s-1]&&(a=s-1);null!==a&&c(r.tabOrder[a]);o.find('a[href="#'+e+'"]').closest("li").remove();n("#"+e).remove();t.store()},f=function(s){var u=!s;s||(s=p());"tabs"in r||(r.tabs={});var c=r.tabs[s]?r.tabs[s].name:l(),f=n("<a>",{href:"#"+s,"aria-controls":s,role:"tab","data-toggle":"tab"}).click(function(e){e.preventDefault();n(this).tab("show");i.tabs[s].yasqe.refresh()}).on("shown.bs.tab",function(){r.selected=n(this).attr("aria-controls");i.tabs[s].onShow();t.store()}).append(n("<span>").text(c)).append(n("<button>",{"class":"close",type:"button"}).text("x").click(function(){d(s)})),h=n('<div><input type="text"></div>').keydown(function(){27==event.which||27==event.keyCode?n(this).closest("li").removeClass("rename"):(13==event.which||13==event.keyCode)&&g(n(this).closest("li"))}),g=function(e){var n=e.find('a[role="tab"]').attr("aria-controls"),i=e.find("input").val();f.find("span").text(e.find("input").val());r.tabs[n].name=i;t.store();e.removeClass("rename")},m=n("<li>",{role:"presentation"}).append(f).append(h).dblclick(function(){var e=n(this),t=e.find("span").text();e.addClass("rename");e.find("input").val(t);e.onOutsideClick(function(){g(e)})}).bind("contextmenu",function(e){e.preventDefault();a.show().onOutsideClick(function(){a.hide()},{allowedElements:n(this).closest("li")}).addClass("open").position({my:"left top-3",at:"left bottom",of:n(this),collision:"fit"}).attr("target-tab",m.find('a[role="tab"]').attr("aria-controls"))});o.find('li:has(a[role="addTab"])').before(m);u&&r.tabOrder.push(s);i.tabs[s]=e("./tab.js")(t,s,c);(u||r.selected==s)&&f.tab("show")};i.current=function(){return i.tabs[r.selected]};return i}},{"./imgs.js":87,"./shareLink.js":93,"./tab.js":94,jquery:void 0,"jquery-ui/position":3,"yasgui-utils":9}],96:[function(e,t){"use strict";var n=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),r=e("./imgs.js"),i=e("yasgui-utils");t.exports=function(e,t){var o,s,a,l,u,p,c,d=null,f=null,h=null,g=null,m=null,E=function(){d=n("<nav>",{"class":"menu-slide",id:"navmenu"});d.append(n(i.svg.getElement(r.yasgui)).addClass("yasguiLogo").attr("title","About YASGUI").click(function(){window.open("http://about.yasgui.org","_blank")}));f=n("<div>",{role:"tabpanel"}).appendTo(d);h=n("<ul>",{"class":"nav nav-pills tabPaneMenuTabs",role:"tablist"}).appendTo(f);g=n("<div>",{"class":"tab-content"}).appendTo(f);var e=n("<li>",{role:"presentation"}).appendTo(h),E="yasgui_reqConfig_"+t.persistentOptions.id;e.append(n("<a>",{href:"#"+E,"aria-controls":E,role:"tab","data-toggle":"tab"}).text("Configure Request").click(function(e){e.preventDefault();n(this).tab("show")}));var v=n("<div>",{id:E,role:"tabpanel","class":"tab-pane requestConfig container-fluid"}).appendTo(g),x=n("<div>",{"class":"row"}).appendTo(v);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(x).append(n("<span>").text("Request Method"));o=n("<button>",{"class":"btn btn-default ","data-toggle":"button"}).text("POST").click(function(){o.addClass("active");s.removeClass("active")});s=n("<button>",{"class":"btn btn-default","data-toggle":"button"}).text("GET").click(function(){s.addClass("active");o.removeClass("active")});n("<div>",{"class":"btn-group col-md-8",role:"group"}).append(s).append(o).appendTo(x);var y=n("<div>",{"class":"row"}).appendTo(v);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(y).text("Accept Headers");a=n("<select>",{"class":"form-control"}).append(n("<option>",{value:"application/sparql-results+json"}).text("JSON")).append(n("<option>",{value:"application/sparql-results+xml"}).text("XML")).append(n("<option>",{value:"text/csv"}).text("CSV")).append(n("<option>",{value:"text/tab-separated-values"}).text("TSV"));l=n("<select>",{"class":"form-control"}).append(n("<option>",{value:"text/turtle"}).text("Turtle")).append(n("<option>",{value:"application/rdf+xml"}).text("RDF-XML")).append(n("<option>",{value:"text/csv"}).text("CSV")).append(n("<option>",{value:"text/tab-separated-values"}).text("TSV"));n("<div>",{"class":"col-md-4",role:"group"}).append(n("<label>").text("SELECT").append(a)).appendTo(y);n("<div>",{"class":"col-md-4",role:"group"}).append(n("<label>").text("Graph").append(l)).appendTo(y);var N=n("<div>",{"class":"row"}).appendTo(v);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(N).text("URL Arguments");u=n("<div>",{"class":"col-md-8",role:"group"}).appendTo(N);var I=n("<div>",{"class":"row"}).appendTo(v);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(I).text("Default graphs");p=n("<div>",{"class":"col-md-8",role:"group"}).appendTo(I);var A=n("<div>",{"class":"row"}).appendTo(v);n("<div>",{"class":"col-md-4 rowLabel"}).appendTo(A).text("Named graphs");c=n("<div>",{"class":"col-md-8",role:"group"}).appendTo(A);var e=n("<li>",{role:"presentation"}).appendTo(h),T="yasgui_history_"+t.persistentOptions.id;e.append(n("<a>",{href:"#"+T,"aria-controls":T,role:"tab","data-toggle":"tab"}).text("History").click(function(e){e.preventDefault();n(this).tab("show")}));var L=n("<div>",{id:T,role:"tabpanel","class":"tab-pane history container-fluid"}).appendTo(g);m=n("<ul>",{"class":"list-group"}).appendTo(L);var e=n("<li>",{role:"presentation"}).appendTo(h),S="yasgui_collections_"+t.persistentOptions.id;e.append(n("<a>",{href:"#"+S,"aria-controls":S,role:"tab","data-toggle":"tab"}).text("Collections").click(function(e){e.preventDefault();n(this).tab("show")}));var v=n("<div>",{id:S,role:"tabpanel","class":"tab-pane collections container-fluid"}).appendTo(g);return d},v=function(e,t,r,i){for(var o=n("<div>",{"class":"textInputsRow"}),s=0;t>s;s++){var a=i&&i[s]?i[s]:"";n("<input>",{type:"text"}).val(a).keyup(function(){var r=!1;e.find(".textInputsRow:last input").each(function(e,t){n(t).val().trim().length>0&&(r=!0)});r&&v(e,t,!0)}).css("width",92/t+"%").appendTo(o)}o.append(n("<button>",{"class":"close",type:"button"}).text("x").click(function(){n(this).closest(".textInputsRow").remove()}));r?o.hide().appendTo(e).show("fast"):o.appendTo(e)},x=function(){0==d.find(".tabPaneMenuTabs li.active").length&&d.find(".tabPaneMenuTabs a:first").tab("show");var r=t.persistentOptions.yasqe;"POST"==r.sparql.requestMethod.toUpperCase()?o.addClass("active"):s.addClass("active");l.val(r.sparql.acceptHeaderGraph);a.val(r.sparql.acceptHeaderSelect);u.empty();r.sparql.args&&r.sparql.args.length>0&&r.sparql.args.forEach(function(e){var t=[e.name,e.value];v(u,2,!1,t)});v(u,2,!1);p.empty();r.sparql.defaultGraphs&&r.sparql.defaultGraphs.length>0&&v(p,1,!1,r.sparql.defaultGraphs);v(p,1,!1);c.empty();r.sparql.namedGraphs&&r.sparql.namedGraphs.length>0&&v(c,1,!1,r.sparql.namedGraphs);v(c,1,!1);m.empty();0==e.history.length?m.append(n("<a>",{"class":"list-group-item disabled",href:"#"}).text("No items in history yet").click(function(e){e.preventDefault()})):e.history.forEach(function(t){var r=t.options.yasqe.sparql.endpoint;t.resultSize&&(r+=" ("+t.resultSize+" results)");m.append(n("<a>",{"class":"list-group-item",href:"#",title:t.options.yasqe.value}).text(r).click(function(r){var i=e.tabManager.tabs[t.options.id];n.extend(!0,i.persistentOptions,t.options);i.refreshYasqe();e.store();d.closest(".tab-pane").removeClass("menu-open");r.preventDefault()}))})},y=function(){var r=t.persistentOptions.yasqe.sparql;o.hasClass("active")?r.requestMethod="POST":s.hasClass("active")&&(r.requestMethod="GET");r.acceptHeaderGraph=l.val();r.acceptHeaderSelect=a.val();var i=[];u.find("div").each(function(e,t){var r=[];n(t).find("input").each(function(e,t){r.push(n(t).val())});r[0]&&r[0].trim().length>0&&i.push({name:r[0],value:r[1]?r[1]:""})});r.args=i;var d=[];p.find("div").each(function(e,t){var r=[];n(t).find("input").each(function(e,t){r.push(n(t).val())});r[0]&&r[0].trim().length>0&&d.push(r[0])});r.defaultGraphs=d;var f=[];c.find("div").each(function(e,t){var r=[];n(t).find("input").each(function(e,t){r.push(n(t).val())});r[0]&&r[0].trim().length>0&&f.push(r[0])});r.namedGraphs=f;e.store();t.setPersistentInYasqe()};return{initWrapper:E,updateWrapper:x,store:y}}},{"./imgs.js":87,jquery:void 0,"yasgui-utils":9}],97:[function(e,t){(function(){try{return e("jquery")}catch(t){return window.jQuery}})();t.exports={escapeHtmlEntities:function(e){var t={"&":"&","<":"<",">":">"},n=function(e){return t[e]||e};return e.replace(/[&<>]/g,n)}}},{jquery:void 0}]},{},[1])(1)});
//# sourceMappingURL=yasgui.min.js.map |
src/desktop/apps/order/client.js | xtina-starr/force | import { buildClientApp } from "reaction/Artsy/Router/client"
import { data as sd } from "sharify"
import { routes } from "reaction/Apps/Order/routes"
import mediator from "desktop/lib/mediator.coffee"
import React from "react"
import ReactDOM from "react-dom"
import styled from "styled-components"
import User from "desktop/models/user.coffee"
import Artwork from "desktop/models/artwork.coffee"
import ArtworkInquiry from "desktop/models/artwork_inquiry.coffee"
import openInquiryQuestionnaireFor from "desktop/components/inquiry_questionnaire/index.coffee"
mediator.on("openOrdersContactArtsyModal", options => {
const artworkId = options.artworkId
if (artworkId) {
const user = User.instantiate()
const inquiry = new ArtworkInquiry({ notification_delay: 600 })
const artwork = new Artwork({ id: artworkId })
artwork.fetch().then(() => {
openInquiryQuestionnaireFor({
user,
artwork,
inquiry,
ask_specialist: true,
})
})
}
})
// Track page views for order checkout flow: shipping, payment and review.
// These events are triggered from Reaction.
const orderCheckoutFlowEvents = [
"order:shipping",
"order:payment",
"order:review",
"order:status",
]
orderCheckoutFlowEvents.map(eventName => {
mediator.on(eventName, () => {
window.analytics.page(
{ path: window.location.pathname },
{ integrations: { Marketo: false } }
)
// Reset timers that track time on page since we're tracking each order
// checkout view as a separate page.
typeof window.desktopPageTimeTrackers !== "undefined" &&
window.desktopPageTimeTrackers.forEach(tracker => {
// No need to reset the tracker if we're on the same page.
if (window.location.pathname !== tracker.path)
tracker.reset(window.location.pathname)
})
})
})
buildClientApp({
routes,
context: {
user: sd.CURRENT_USER,
mediator,
},
history: {
options: {
useBeforeUnload: true,
},
},
})
.then(({ ClientApp }) => {
ReactDOM.hydrate(
<ClientApp />,
document.getElementById("react-root")
)
})
.catch(error => {
console.error(error)
})
if (module.hot) {
module.hot.accept()
}
|
src/Well.js | bvasko/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Well = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'well'
};
},
render() {
let classes = this.getBsClassSet();
return (
<div {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</div>
);
}
});
export default Well;
|
src/svg-icons/av/fiber-dvr.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvFiberDvr = (props) => (
<SvgIcon {...props}>
<path d="M17.5 10.5h2v1h-2zm-13 0h2v3h-2zM21 3H3c-1.11 0-2 .89-2 2v14c0 1.1.89 2 2 2h18c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zM8 13.5c0 .85-.65 1.5-1.5 1.5H3V9h3.5c.85 0 1.5.65 1.5 1.5v3zm4.62 1.5h-1.5L9.37 9h1.5l1 3.43 1-3.43h1.5l-1.75 6zM21 11.5c0 .6-.4 1.15-.9 1.4L21 15h-1.5l-.85-2H17.5v2H16V9h3.5c.85 0 1.5.65 1.5 1.5v1z"/>
</SvgIcon>
);
AvFiberDvr = pure(AvFiberDvr);
AvFiberDvr.displayName = 'AvFiberDvr';
AvFiberDvr.muiName = 'SvgIcon';
export default AvFiberDvr;
|
app/jsx/grading/GradingPeriodSet.js | djbender/canvas-lms | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import $ from 'jquery'
import _ from 'lodash'
import {Button} from '@instructure/ui-buttons'
import axios from 'axios'
import I18n from 'i18n!GradingPeriodSet'
import GradingPeriod from './AccountGradingPeriod'
import GradingPeriodForm from './GradingPeriodForm'
import gradingPeriodsApi from 'compiled/api/gradingPeriodsApi'
import 'jquery.instructure_misc_helpers'
const sortPeriods = function(periods) {
return _.sortBy(periods, 'startDate')
}
const anyPeriodsOverlap = function(periods) {
if (_.isEmpty(periods)) {
return false
}
const firstPeriod = _.head(periods)
const otherPeriods = _.tail(periods)
const overlapping = _.some(
otherPeriods,
otherPeriod =>
otherPeriod.startDate < firstPeriod.endDate && firstPeriod.startDate < otherPeriod.endDate
)
return overlapping || anyPeriodsOverlap(otherPeriods)
}
const isValidDate = function(date) {
return Object.prototype.toString.call(date) === '[object Date]' && !_.isNaN(date.getTime())
}
const validatePeriods = function(periods, weighted) {
if (_.some(periods, period => !(period.title || '').trim())) {
return [I18n.t('All grading periods must have a title')]
}
if (weighted && _.some(periods, period => _.isNaN(period.weight) || period.weight < 0)) {
return [I18n.t('All weights must be greater than or equal to 0')]
}
const validDates = _.every(
periods,
period =>
isValidDate(period.startDate) && isValidDate(period.endDate) && isValidDate(period.closeDate)
)
if (!validDates) {
return [I18n.t('All dates fields must be present and formatted correctly')]
}
const orderedStartAndEndDates = _.every(periods, period => period.startDate < period.endDate)
if (!orderedStartAndEndDates) {
return [I18n.t('All start dates must be before the end date')]
}
const orderedEndAndCloseDates = _.every(periods, period => period.endDate <= period.closeDate)
if (!orderedEndAndCloseDates) {
return [I18n.t('All close dates must be on or after the end date')]
}
if (anyPeriodsOverlap(periods)) {
return [I18n.t('Grading periods must not overlap')]
}
}
const isEditingPeriod = function(state) {
return !!state.editPeriod.id
}
const isActionsDisabled = function(state, props) {
return !!(props.actionsDisabled || isEditingPeriod(state) || state.newPeriod.period)
}
const getShowGradingPeriodRef = function(period) {
return `show-grading-period-${period.id}`
}
const {shape, string, array, bool, func} = PropTypes
export default class GradingPeriodSet extends React.Component {
static propTypes = {
gradingPeriods: array.isRequired,
terms: array.isRequired,
readOnly: bool.isRequired,
expanded: bool,
actionsDisabled: bool,
onEdit: func.isRequired,
onDelete: func.isRequired,
onPeriodsChange: func.isRequired,
onToggleBody: func.isRequired,
set: shape({
id: string.isRequired,
title: string.isRequired,
weighted: bool,
displayTotalsForAllGradingPeriods: bool.isRequired
}).isRequired,
urls: shape({
batchUpdateURL: string.isRequired,
deleteGradingPeriodURL: string.isRequired,
gradingPeriodSetsURL: string.isRequired
}).isRequired,
permissions: shape({
read: bool.isRequired,
create: bool.isRequired,
update: bool.isRequired,
delete: bool.isRequired
}).isRequired
}
constructor(props) {
super(props)
this.state = {
title: this.props.set.title,
weighted: !!this.props.set.weighted,
displayTotalsForAllGradingPeriods: this.props.set.displayTotalsForAllGradingPeriods,
gradingPeriods: sortPeriods(this.props.gradingPeriods),
newPeriod: {
period: null,
saving: false
},
editPeriod: {
id: null,
saving: false
}
}
this._refs = {}
}
componentDidUpdate(prevProps, prevState) {
if (prevState.newPeriod.period && !this.state.newPeriod.period) {
this._refs.addPeriodButton.focus()
} else if (isEditingPeriod(prevState) && !isEditingPeriod(this.state)) {
const period = {id: prevState.editPeriod.id}
this._refs[getShowGradingPeriodRef(period)]._refs.editButton.focus()
}
}
toggleSetBody = () => {
if (!isEditingPeriod(this.state)) {
this.props.onToggleBody()
}
}
promptDeleteSet = event => {
event.stopPropagation()
const confirmMessage = I18n.t('Are you sure you want to delete this grading period set?')
if (!window.confirm(confirmMessage)) return null
const url = `${this.props.urls.gradingPeriodSetsURL}/${this.props.set.id}`
axios
.delete(url)
.then(() => {
$.flashMessage(I18n.t('The grading period set was deleted'))
this.props.onDelete(this.props.set.id)
})
.catch(() => {
$.flashError(I18n.t('An error occured while deleting the grading period set'))
})
}
setTerms = () => _.filter(this.props.terms, {gradingPeriodGroupId: this.props.set.id})
termNames = () => {
const names = _.map(this.setTerms(), 'displayName')
if (names.length > 0) {
return I18n.t('Terms: ') + names.join(', ')
} else {
return I18n.t('No Associated Terms')
}
}
editSet = e => {
e.stopPropagation()
this.props.onEdit(this.props.set)
}
changePeriods = periods => {
const sortedPeriods = sortPeriods(periods)
this.setState({gradingPeriods: sortedPeriods})
this.props.onPeriodsChange(this.props.set.id, sortedPeriods)
}
removeGradingPeriod = idToRemove => {
this.setState(oldState => {
const gradingPeriods = _.reject(oldState.gradingPeriods, period => period.id === idToRemove)
return {gradingPeriods}
})
}
showNewPeriodForm = () => {
this.setNewPeriod({period: {}})
}
saveNewPeriod = period => {
const periods = this.state.gradingPeriods.concat([period])
const validations = validatePeriods(periods, this.state.weighted)
if (_.isEmpty(validations)) {
this.setNewPeriod({saving: true})
gradingPeriodsApi
.batchUpdate(this.props.set.id, periods)
.then(pds => {
$.flashMessage(I18n.t('All changes were saved'))
this.removeNewPeriodForm()
this.changePeriods(pds)
})
.catch(_err => {
$.flashError(I18n.t('There was a problem saving the grading period'))
this.setNewPeriod({saving: false})
})
} else {
_.each(validations, message => {
$.flashError(message)
})
}
}
removeNewPeriodForm = () => {
this.setNewPeriod({saving: false, period: null})
}
setNewPeriod = attr => {
this.setState(oldState => {
const newPeriod = $.extend(true, {}, oldState.newPeriod, attr)
return {newPeriod}
})
}
editPeriod = period => {
this.setEditPeriod({id: period.id, saving: false})
}
updatePeriod = period => {
const periods = _.reject(
this.state.gradingPeriods,
_period => period.id === _period.id
).concat([period])
const validations = validatePeriods(periods, this.state.weighted)
if (_.isEmpty(validations)) {
this.setEditPeriod({saving: true})
gradingPeriodsApi
.batchUpdate(this.props.set.id, periods)
.then(pds => {
$.flashMessage(I18n.t('All changes were saved'))
this.setEditPeriod({id: null, saving: false})
this.changePeriods(pds)
})
.catch(_err => {
$.flashError(I18n.t('There was a problem saving the grading period'))
this.setNewPeriod({saving: false})
})
} else {
_.each(validations, message => {
$.flashError(message)
})
}
}
cancelEditPeriod = () => {
this.setEditPeriod({id: null, saving: false})
}
setEditPeriod = attr => {
this.setState(oldState => {
const editPeriod = $.extend(true, {}, oldState.editPeriod, attr)
return {editPeriod}
})
}
renderEditButton = () => {
if (!this.props.readOnly && this.props.permissions.update) {
const disabled = isActionsDisabled(this.state, this.props)
return (
<Button
elementRef={ref => {
this._refs.editButton = ref
}}
variant="icon"
disabled={disabled}
onClick={this.editSet}
title={I18n.t('Edit %{title}', {title: this.props.set.title})}
>
<span className="screenreader-only">
{I18n.t('Edit %{title}', {title: this.props.set.title})}
</span>
<i className="icon-edit" />
</Button>
)
}
}
renderDeleteButton = () => {
if (!this.props.readOnly && this.props.permissions.delete) {
const disabled = isActionsDisabled(this.state, this.props)
return (
<Button
elementRef={ref => {
this._refs.deleteButton = ref
}}
variant="icon"
disabled={disabled}
onClick={this.promptDeleteSet}
title={I18n.t('Delete %{title}', {title: this.props.set.title})}
>
<span className="screenreader-only">
{I18n.t('Delete %{title}', {title: this.props.set.title})}
</span>
<i className="icon-trash" />
</Button>
)
}
}
renderEditAndDeleteButtons = () => (
<div className="ItemGroup__header__admin">
{this.renderEditButton()}
{this.renderDeleteButton()}
</div>
)
renderSetBody = () => {
if (!this.props.expanded) return null
return (
<div
ref={ref => {
this._refs.setBody = ref
}}
className="ig-body"
>
<div
className="GradingPeriodList"
ref={ref => {
this._refs.gradingPeriodList = ref
}}
>
{this.renderGradingPeriods()}
</div>
{this.renderNewPeriod()}
</div>
)
}
renderGradingPeriods = () => {
const actionsDisabled = isActionsDisabled(this.state, this.props)
return _.map(this.state.gradingPeriods, period => {
if (period.id === this.state.editPeriod.id) {
return (
<div
key={`edit-grading-period-${period.id}`}
className="GradingPeriodList__period--editing pad-box"
>
<GradingPeriodForm
ref={ref => {
this._refs.editPeriodForm = ref
}}
period={period}
weighted={this.state.weighted}
disabled={this.state.editPeriod.saving}
onSave={this.updatePeriod}
onCancel={this.cancelEditPeriod}
/>
</div>
)
} else {
return (
<GradingPeriod
key={`show-grading-period-${period.id}`}
ref={ref => {
this._refs[getShowGradingPeriodRef(period)] = ref
}}
period={period}
weighted={this.state.weighted}
actionsDisabled={actionsDisabled}
onEdit={this.editPeriod}
readOnly={this.props.readOnly}
onDelete={this.removeGradingPeriod}
deleteGradingPeriodURL={this.props.urls.deleteGradingPeriodURL}
permissions={this.props.permissions}
/>
)
}
})
}
renderNewPeriod = () => {
if (this.props.permissions.create && !this.props.readOnly) {
if (this.state.newPeriod.period) {
return this.renderNewPeriodForm()
} else {
return this.renderNewPeriodButton()
}
}
}
renderNewPeriodButton = () => {
const disabled = isActionsDisabled(this.state, this.props)
return (
<div className="GradingPeriodList__new-period center-xs border-rbl border-round-b">
<Button
variant="link"
elementRef={ref => {
this._refs.addPeriodButton = ref
}}
disabled={disabled}
aria-label={I18n.t('Add Grading Period')}
onClick={this.showNewPeriodForm}
>
<i className="icon-plus GradingPeriodList__new-period__add-icon" />
{I18n.t('Grading Period')}
</Button>
</div>
)
}
renderNewPeriodForm = () => (
<div className="GradingPeriodList__new-period--editing border border-rbl border-round-b pad-box">
<GradingPeriodForm
key="new-grading-period"
ref={ref => {
this._refs.newPeriodForm = ref
}}
weighted={this.state.weighted}
disabled={this.state.newPeriod.saving}
onSave={this.saveNewPeriod}
onCancel={this.removeNewPeriodForm}
/>
</div>
)
render() {
const setStateSuffix = this.props.expanded ? 'expanded' : 'collapsed'
const arrow = this.props.expanded ? 'down' : 'right'
return (
<div className={`GradingPeriodSet--${setStateSuffix}`}>
<div
className="ItemGroup__header"
ref={ref => {
this._refs.toggleSetBody = ref
}}
onClick={this.toggleSetBody}
>
<div>
<div className="ItemGroup__header__title">
<button
className="Button Button--icon-action GradingPeriodSet__toggle"
aria-expanded={this.props.expanded}
aria-label={I18n.t('Toggle %{title} grading period visibility', {
title: this.props.set.title
})}
>
<i className={`icon-mini-arrow-${arrow}`} />
</button>
<h2
ref={ref => {
this._refs.title = ref
}}
className="GradingPeriodSet__title"
>
{this.props.set.title}
</h2>
</div>
{this.renderEditAndDeleteButtons()}
</div>
<div className="EnrollmentTerms__list">{this.termNames()}</div>
</div>
{this.renderSetBody()}
</div>
)
}
}
|
test/src/label-group/index.js | yummies/core-components | import TestUtils from 'react-addons-test-utils';
import React from 'react';
import ReactDOM from 'react-dom';
import { expect } from 'chai';
import { renderOnce } from 'test/helpers/render';
import LabelGroup from '#label-group';
describe('labelGroup', () => {
describe('basic', () => {
it('exists', () => {
expect(LabelGroup).to.exist;
});
it('is a component', () => {
expect(TestUtils.isCompositeComponent(renderOnce(LabelGroup()))).to.be.true;
});
});
describe('render', () => {
beforeEach(function() {
this.renderWithProps = props => {
this.rootComponent = renderOnce(LabelGroup(props));
this.rootComponentDOMNode = ReactDOM.findDOMNode(this.rootComponent);
};
});
describe('DOM', () => {
it('initial', function() {
this.renderWithProps({
labelText: 'test label',
children: React.createElement('div', {
key: 'test',
className: 'test-children'
})
});
const labelDOMNode = this.rootComponentDOMNode.children[0];
const controlDOMNode = this.rootComponentDOMNode.children[1];
expect(this.rootComponentDOMNode.tagName).to.be.equal('LABEL');
expect(this.rootComponentDOMNode).to.be.a.block('label-group');
expect(this.rootComponentDOMNode).to.has.mods({
'control-position': 'right'
});
expect(labelDOMNode).to.be.an.elem({
block: 'label-group',
elem: 'label'
});
expect(labelDOMNode.textContent).to.be.equal('test label');
expect(controlDOMNode).to.be.an.elem({
block: 'label-group',
elem: 'control'
});
expect(controlDOMNode.children[0]).to.be.block('test-children');
});
it('control-position_left', function() {
this.renderWithProps({
labelText: 'test label',
controlPosition: 'left',
children: React.createElement('div', {
key: 'test',
className: 'test-children'
})
});
const controlDOMNode = this.rootComponentDOMNode.children[0];
const labelDOMNode = this.rootComponentDOMNode.children[1];
expect(controlDOMNode).to.be.an.elem({
block: 'label-group',
elem: 'control'
});
expect(controlDOMNode.children[0]).to.be.block('test-children');
expect(labelDOMNode).to.be.an.elem({
block: 'label-group',
elem: 'label'
});
expect(labelDOMNode.textContent).to.be.equal('test label');
});
});
});
});
|
src/index.js | rhodiumlabs/rhodium-website | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'
import { configureStore } from './store/configureStore';
import routes from './routes';
import './styles/index.scss';
import { RoutingContext, match } from 'react-router';
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store)
ReactDOM.render(
<Provider store={store}>
<Router history={history} routes={routes}>
</Router>
</Provider>,
document.getElementById('root')
);
|
ajax/libs/primeui/3.0.0/primeui.js | sajochiu/cdnjs | /*
* PrimeUI 3.0.0
*
* Copyright 2009-2016 PrimeTek.
*
* 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.
*/
/**
* PUI Object
*/
var PUI = {
zindex : 1000,
gridColumns: {
'1': 'pui-grid-col-12',
'2': 'pui-grid-col-6',
'3': 'pui-grid-col-4',
'4': 'pui-grid-col-3',
'6': 'pui-grid-col-2',
'12': 'pui-grid-col-11'
},
/**
* Aligns container scrollbar to keep item in container viewport, algorithm copied from jquery-ui menu widget
*/
scrollInView: function(container, item) {
var borderTop = parseFloat(container.css('borderTopWidth')) || 0,
paddingTop = parseFloat(container.css('paddingTop')) || 0,
offset = item.offset().top - container.offset().top - borderTop - paddingTop,
scroll = container.scrollTop(),
elementHeight = container.height(),
itemHeight = item.outerHeight(true);
if(offset < 0) {
container.scrollTop(scroll + offset);
}
else if((offset + itemHeight) > elementHeight) {
container.scrollTop(scroll + offset - elementHeight + itemHeight);
}
},
isIE: function(version) {
return (this.browser.msie && parseInt(this.browser.version, 10) === version);
},
escapeRegExp: function(text) {
return text.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
},
escapeHTML: function(value) {
return value.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
},
escapeClientId: function(id) {
return "#" + id.replace(/:/g,"\\:");
},
clearSelection: function() {
if(window.getSelection) {
if(window.getSelection().empty) {
window.getSelection().empty();
} else if(window.getSelection().removeAllRanges) {
window.getSelection().removeAllRanges();
}
} else if(document.selection && document.selection.empty) {
document.selection.empty();
}
},
inArray: function(arr, item) {
for(var i = 0; i < arr.length; i++) {
if(arr[i] === item) {
return true;
}
}
return false;
},
calculateScrollbarWidth: function() {
if(!this.scrollbarWidth) {
if(this.browser.msie) {
var $textarea1 = $('<textarea cols="10" rows="2"></textarea>')
.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'),
$textarea2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>')
.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body');
this.scrollbarWidth = $textarea1.width() - $textarea2.width();
$textarea1.add($textarea2).remove();
}
else {
var $div = $('<div />')
.css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: -1000 })
.prependTo('body').append('<div />').find('div')
.css({ width: '100%', height: 200 });
this.scrollbarWidth = 100 - $div.width();
$div.parent().remove();
}
}
return this.scrollbarWidth;
},
//adapted from jquery browser plugin
resolveUserAgent: function() {
var matched, browser;
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(opr)[\/]([\w.]+)/.exec( ua ) ||
/(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
var platform_match = /(ipad)/.exec( ua ) ||
/(iphone)/.exec( ua ) ||
/(android)/.exec( ua ) ||
/(windows phone)/.exec( ua ) ||
/(win)/.exec( ua ) ||
/(mac)/.exec( ua ) ||
/(linux)/.exec( ua ) ||
/(cros)/i.exec( ua ) ||
[];
return {
browser: match[ 3 ] || match[ 1 ] || "",
version: match[ 2 ] || "0",
platform: platform_match[ 0 ] || ""
};
};
matched = jQuery.uaMatch( window.navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
browser.versionNumber = parseInt(matched.version);
}
if ( matched.platform ) {
browser[ matched.platform ] = true;
}
// These are all considered mobile platforms, meaning they run a mobile browser
if ( browser.android || browser.ipad || browser.iphone || browser[ "windows phone" ] ) {
browser.mobile = true;
}
// These are all considered desktop platforms, meaning they run a desktop browser
if ( browser.cros || browser.mac || browser.linux || browser.win ) {
browser.desktop = true;
}
// Chrome, Opera 15+ and Safari are webkit based browsers
if ( browser.chrome || browser.opr || browser.safari ) {
browser.webkit = true;
}
// IE11 has a new token so we will assign it msie to avoid breaking changes
if ( browser.rv )
{
var ie = "msie";
matched.browser = ie;
browser[ie] = true;
}
// Opera 15+ are identified as opr
if ( browser.opr )
{
var opera = "opera";
matched.browser = opera;
browser[opera] = true;
}
// Stock Android browsers are marked as Safari on Android.
if ( browser.safari && browser.android )
{
var android = "android";
matched.browser = android;
browser[android] = true;
}
// Assign the name and platform variable
browser.name = matched.browser;
browser.platform = matched.platform;
this.browser = browser;
$.browser = browser;
},
getGridColumn: function(number) {
return this.gridColumns[number + ''];
},
executeFunctionByName: function(functionName /*, args */) {
var args = [].slice.call(arguments).splice(1),
context = window,
namespaces = functionName.split("."),
func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(this, args);
},
resolveObjectByName: function(name) {
if(name) {
var parts = name.split(".");
for(var i = 0, len = parts.length, obj = window; i < len; ++i) {
obj = obj[parts[i]];
}
return obj;
}
else {
return null;
}
}
};
PUI.resolveUserAgent();/**
* PrimeUI Accordion widget
*/
(function() {
$.widget("primeui.puiaccordion", {
options: {
activeIndex: 0,
multiple: false
},
_create: function() {
if(this.options.multiple) {
this.options.activeIndex = [];
}
var $this = this;
this.element.addClass('pui-accordion ui-widget ui-helper-reset');
this.element.children('h3').addClass('pui-accordion-header ui-helper-reset ui-state-default').each(function(i) {
var header = $(this),
title = header.html(),
headerClass = (i == $this.options.activeIndex) ? 'ui-state-active ui-corner-top' : 'ui-corner-all',
iconClass = (i == $this.options.activeIndex) ? 'pui-icon fa fa-fw fa-caret-down' : 'pui-icon fa fa-fw fa-caret-right';
header.addClass(headerClass).html('<span class="' + iconClass + '"></span><a href="#">' + title + '</a>');
});
this.element.children('div').each(function(i) {
var content = $(this);
content.addClass('pui-accordion-content ui-helper-reset ui-widget-content');
if(i != $this.options.activeIndex) {
content.addClass('ui-helper-hidden');
}
});
this.headers = this.element.children('.pui-accordion-header');
this.panels = this.element.children('.pui-accordion-content');
this.headers.children('a').disableSelection();
this._bindEvents();
},
_bindEvents: function() {
var $this = this;
this.headers.mouseover(function() {
var element = $(this);
if(!element.hasClass('ui-state-active')&&!element.hasClass('ui-state-disabled')) {
element.addClass('ui-state-hover');
}
}).mouseout(function() {
var element = $(this);
if(!element.hasClass('ui-state-active')&&!element.hasClass('ui-state-disabled')) {
element.removeClass('ui-state-hover');
}
}).click(function(e) {
var element = $(this);
if(!element.hasClass('ui-state-disabled')) {
var tabIndex = element.index() / 2;
if(element.hasClass('ui-state-active')) {
$this.unselect(tabIndex);
}
else {
$this.select(tabIndex);
}
}
e.preventDefault();
});
},
/**
* Activates a tab with given index
*/
select: function(index) {
var panel = this.panels.eq(index);
this._trigger('change', panel);
//update state
if(this.options.multiple) {
this._addToSelection(index);
}
else {
this.options.activeIndex = index;
}
this._show(panel);
},
/**
* Deactivates a tab with given index
*/
unselect: function(index) {
var panel = this.panels.eq(index),
header = panel.prev();
header.attr('aria-expanded', false).children('.pui-icon').removeClass('fa-caret-down').addClass('fa-caret-right');
header.removeClass('ui-state-active ui-corner-top').addClass('ui-corner-all');
panel.attr('aria-hidden', true).slideUp();
this._removeFromSelection(index);
},
_show: function(panel) {
//deactivate current
if(!this.options.multiple) {
var oldHeader = this.headers.filter('.ui-state-active');
oldHeader.children('.pui-icon').removeClass('fa-caret-down').addClass('fa-caret-right');
oldHeader.attr('aria-expanded', false).removeClass('ui-state-active ui-corner-top').addClass('ui-corner-all').next().attr('aria-hidden', true).slideUp();
}
//activate selected
var newHeader = panel.prev();
newHeader.attr('aria-expanded', true).addClass('ui-state-active ui-corner-top').removeClass('ui-state-hover ui-corner-all')
.children('.pui-icon').removeClass('fa-caret-right').addClass('fa-caret-down');
panel.attr('aria-hidden', false).slideDown('normal');
},
_addToSelection: function(nodeId) {
this.options.activeIndex.push(nodeId);
},
_removeFromSelection: function(index) {
this.options.activeIndex = $.grep(this.options.activeIndex, function(r) {
return r != index;
});
}
});
})();
/**
* PrimeUI autocomplete widget
*/
(function() {
$.widget("primeui.puiautocomplete", {
options: {
delay: 300,
minQueryLength: 1,
multiple: false,
dropdown: false,
scrollHeight: 200,
forceSelection: false,
effect:null,
effectOptions: {},
effectSpeed: 'normal',
content: null,
caseSensitive: false
},
_create: function() {
this.element.wrap('<span class="pui-autocomplete ui-widget" />');
this.element.puiinputtext();
this.panel = $('<div class="pui-autocomplete-panel ui-widget-content ui-corner-all ui-helper-hidden pui-shadow"></div>').appendTo('body');
if(this.options.multiple) {
this.element.wrap('<ul class="pui-autocomplete-multiple ui-widget pui-inputtext ui-state-default ui-corner-all">' +
'<li class="pui-autocomplete-input-token"></li></ul>');
this.inputContainer = this.element.parent();
this.multiContainer = this.inputContainer.parent();
}
else {
if(this.options.dropdown) {
this.dropdown = $('<button type="button" class="pui-autocomplete-dropdown pui-button ui-widget ui-state-default ui-corner-right pui-button-icon-only">' +
'<span class="pui-icon fa fa-fw fa-caret-down"></span><span class="pui-button-text"> </span></button>')
.insertAfter(this.element);
this.element.removeClass('ui-corner-all').addClass('ui-corner-left');
}
}
this._bindEvents();
},
_bindEvents: function() {
var $this = this;
this._bindKeyEvents();
if(this.options.dropdown) {
this.dropdown.on('mouseenter.puiautocomplete', function() {
if(!$this.element.prop('disabled')) {
$this.dropdown.addClass('ui-state-hover');
}
})
.on('mouseleave.puiautocomplete', function() {
$this.dropdown.removeClass('ui-state-hover');
})
.on('mousedown.puiautocomplete', function() {
if(!$this.element.prop('disabled')) {
$this.dropdown.addClass('ui-state-active');
}
})
.on('mouseup.puiautocomplete', function() {
if(!$this.element.prop('disabled')) {
$this.dropdown.removeClass('ui-state-active');
$this.search('');
$this.element.focus();
}
})
.on('focus.puiautocomplete', function() {
$this.dropdown.addClass('ui-state-focus');
})
.on('blur.puiautocomplete', function() {
$this.dropdown.removeClass('ui-state-focus');
})
.on('keydown.puiautocomplete', function(e) {
var keyCode = $.ui.keyCode;
if(e.which == keyCode.ENTER || e.which == keyCode.NUMPAD_ENTER) {
$this.search('');
$this.input.focus();
e.preventDefault();
}
});
}
if(this.options.multiple) {
this.multiContainer.on('hover.puiautocomplete', function() {
$(this).toggleClass('ui-state-hover');
})
.on('click.puiautocomplete', function() {
$this.element.trigger('focus');
});
this.element.on('focus.pui-autocomplete', function() {
$this.multiContainer.addClass('ui-state-focus');
})
.on('blur.pui-autocomplete', function(e) {
$this.multiContainer.removeClass('ui-state-focus');
});
}
if(this.options.forceSelection) {
this.currentItems = [this.element.val()];
this.element.on('blur.puiautocomplete', function() {
var value = $(this).val(),
valid = false;
for(var i = 0; i < $this.currentItems.length; i++) {
if($this.currentItems[i] === value) {
valid = true;
break;
}
}
if(!valid) {
$this.element.val('');
}
});
}
$(document.body).bind('mousedown.puiautocomplete', function (e) {
if($this.panel.is(":hidden")) {
return;
}
if(e.target === $this.element.get(0)) {
return;
}
var offset = $this.panel.offset();
if (e.pageX < offset.left ||
e.pageX > offset.left + $this.panel.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.panel.height()) {
$this.hide();
}
});
$(window).bind('resize.' + this.element.id, function() {
if($this.panel.is(':visible')) {
$this._alignPanel();
}
});
},
_bindKeyEvents: function() {
var $this = this;
this.element.on('keyup.puiautocomplete', function(e) {
var keyCode = $.ui.keyCode,
key = e.which,
shouldSearch = true;
if(key == keyCode.UP ||
key == keyCode.LEFT ||
key == keyCode.DOWN ||
key == keyCode.RIGHT ||
key == keyCode.TAB ||
key == keyCode.SHIFT ||
key == keyCode.ENTER ||
key == keyCode.NUMPAD_ENTER) {
shouldSearch = false;
}
if(shouldSearch) {
var value = $this.element.val();
if(!value.length) {
$this.hide();
}
if(value.length >= $this.options.minQueryLength) {
if($this.timeout) {
window.clearTimeout($this.timeout);
}
$this.timeout = window.setTimeout(function() {
$this.search(value);
},
$this.options.delay);
}
}
}).on('keydown.puiautocomplete', function(e) {
if($this.panel.is(':visible')) {
var keyCode = $.ui.keyCode,
highlightedItem = $this.items.filter('.ui-state-highlight');
switch(e.which) {
case keyCode.UP:
case keyCode.LEFT:
var prev = highlightedItem.prev();
if(prev.length == 1) {
highlightedItem.removeClass('ui-state-highlight');
prev.addClass('ui-state-highlight');
if($this.options.scrollHeight) {
PUI.scrollInView($this.panel, prev);
}
}
e.preventDefault();
break;
case keyCode.DOWN:
case keyCode.RIGHT:
var next = highlightedItem.next();
if(next.length == 1) {
highlightedItem.removeClass('ui-state-highlight');
next.addClass('ui-state-highlight');
if($this.options.scrollHeight) {
PUI.scrollInView($this.panel, next);
}
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
highlightedItem.trigger('click');
e.preventDefault();
break;
case keyCode.ALT:
case 224:
break;
case keyCode.TAB:
highlightedItem.trigger('click');
$this.hide();
break;
}
}
});
},
_bindDynamicEvents: function() {
var $this = this;
this.items.on('mouseover.puiautocomplete', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight')) {
$this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight');
item.addClass('ui-state-highlight');
}
})
.on('click.puiautocomplete', function(event) {
var item = $(this);
if($this.options.multiple) {
var tokenMarkup = '<li class="pui-autocomplete-token ui-state-active ui-corner-all ui-helper-hidden">';
tokenMarkup += '<span class="pui-autocomplete-token-icon fa fa-fw fa-close" />';
tokenMarkup += '<span class="pui-autocomplete-token-label">' + item.data('label') + '</span></li>';
$(tokenMarkup).data(item.data())
.insertBefore($this.inputContainer).fadeIn()
.children('.pui-autocomplete-token-icon').on('click.pui-autocomplete', function(e) {
var token = $(this).parent();
$this._removeItem(token);
$this._trigger('unselect', e, token);
});
$this.element.val('').trigger('focus');
}
else {
$this.element.val(item.data('label')).focus();
}
$this._trigger('select', event, item);
$this.hide();
});
},
search: function(q) {
this.query = this.options.caseSensitive ? q : q.toLowerCase();
var request = {
query: this.query
};
if(this.options.completeSource) {
if($.isArray(this.options.completeSource)) {
var sourceArr = this.options.completeSource,
data = [],
emptyQuery = ($.trim(q) === '');
for(var i = 0 ; i < sourceArr.length; i++) {
var item = sourceArr[i],
itemLabel = item.label||item;
if(!this.options.caseSensitive) {
itemLabel = itemLabel.toLowerCase();
}
if(emptyQuery||itemLabel.indexOf(this.query) === 0) {
data.push({label:sourceArr[i], value: item});
}
}
this._handleData(data);
}
else {
this.options.completeSource.call(this, request, this._handleData);
}
}
},
_handleData: function(data) {
var $this = this;
this.panel.html('');
this.listContainer = $('<ul class="pui-autocomplete-items pui-autocomplete-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>').appendTo(this.panel);
for(var i = 0; i < data.length; i++) {
var item = $('<li class="pui-autocomplete-item pui-autocomplete-list-item ui-corner-all"></li>');
item.data(data[i]);
if(this.options.content)
item.html(this.options.content.call(this, data[i]));
else
item.text(data[i].label);
this.listContainer.append(item);
}
this.items = this.listContainer.children('.pui-autocomplete-item');
this._bindDynamicEvents();
if(this.items.length > 0) {
var firstItem = $this.items.eq(0),
hidden = this.panel.is(':hidden');
firstItem.addClass('ui-state-highlight');
if($this.query.length > 0 && !$this.options.content) {
$this.items.each(function() {
var item = $(this),
text = item.html(),
re = new RegExp(PUI.escapeRegExp($this.query), 'gi'),
highlighedText = text.replace(re, '<span class="pui-autocomplete-query">$&</span>');
item.html(highlighedText);
});
}
if(this.options.forceSelection) {
this.currentItems = [];
$.each(data, function(i, item) {
$this.currentItems.push(item.label);
});
}
//adjust height
if($this.options.scrollHeight) {
var heightConstraint = hidden ? $this.panel.height() : $this.panel.children().height();
if(heightConstraint > $this.options.scrollHeight)
$this.panel.height($this.options.scrollHeight);
else
$this.panel.css('height', 'auto');
}
if(hidden) {
$this.show();
}
else {
$this._alignPanel();
}
}
else {
this.panel.hide();
}
},
show: function() {
this._alignPanel();
if(this.options.effect)
this.panel.show(this.options.effect, {}, this.options.effectSpeed);
else
this.panel.show();
},
hide: function() {
this.panel.hide();
this.panel.css('height', 'auto');
},
_removeItem: function(item) {
item.fadeOut('fast', function() {
var token = $(this);
token.remove();
});
},
_alignPanel: function() {
var panelWidth = null;
if(this.options.multiple) {
panelWidth = this.multiContainer.innerWidth() - (this.element.position().left - this.multiContainer.position().left);
}
else {
if(this.panel.is(':visible')) {
panelWidth = this.panel.children('.pui-autocomplete-items').outerWidth();
}
else {
this.panel.css({'visibility':'hidden','display':'block'});
panelWidth = this.panel.children('.pui-autocomplete-items').outerWidth();
this.panel.css({'visibility':'visible','display':'none'});
}
var inputWidth = this.element.outerWidth();
if(panelWidth < inputWidth) {
panelWidth = inputWidth;
}
}
this.panel.css({
'left':'',
'top':'',
'width': panelWidth,
'z-index': ++PUI.zindex
})
.position({
my: 'left top',
at: 'left bottom',
of: this.element
});
}
});
})();/**
* PrimeFaces Button Widget
*/
(function() {
$.widget("primeui.puibutton", {
options: {
value: null,
icon: null,
iconPos: 'left',
click: null
},
_create: function() {
var element = this.element,
elementText = element.text(),
value = this.options.value||(elementText === '' ? 'pui-button' : elementText),
disabled = element.prop('disabled'),
styleClass = null;
if(this.options.icon) {
styleClass = (value === 'pui-button') ? 'pui-button-icon-only' : 'pui-button-text-icon-' + this.options.iconPos;
}
else {
styleClass = 'pui-button-text-only';
}
if(disabled) {
styleClass += ' ui-state-disabled';
}
this.element.addClass('pui-button ui-widget ui-state-default ui-corner-all ' + styleClass).text('');
if(this.options.icon) {
this.element.append('<span class="pui-button-icon-' + this.options.iconPos + ' pui-icon pui-c fa fa-fw ' + this.options.icon + '" />');
}
this.element.append('<span class="pui-button-text pui-c">' + value + '</span>');
//aria
element.attr('role', 'button').attr('aria-disabled', disabled);
if(!disabled) {
this._bindEvents();
}
},
_bindEvents: function() {
var element = this.element,
$this = this;
element.on('mouseover.puibutton', function(){
if(!element.prop('disabled')) {
element.addClass('ui-state-hover');
}
}).on('mouseout.puibutton', function() {
$(this).removeClass('ui-state-active ui-state-hover');
}).on('mousedown.puibutton', function() {
if(!element.hasClass('ui-state-disabled')) {
element.addClass('ui-state-active').removeClass('ui-state-hover');
}
}).on('mouseup.puibutton', function(e) {
element.removeClass('ui-state-active').addClass('ui-state-hover');
$this._trigger('click', e);
}).on('focus.puibutton', function() {
element.addClass('ui-state-focus');
}).on('blur.puibutton', function() {
element.removeClass('ui-state-focus');
}).on('keydown.puibutton',function(e) {
if(e.keyCode == $.ui.keyCode.SPACE || e.keyCode == $.ui.keyCode.ENTER || e.keyCode == $.ui.keyCode.NUMPAD_ENTER) {
element.addClass('ui-state-active');
}
}).on('keyup.puibutton', function() {
element.removeClass('ui-state-active');
});
return this;
},
_unbindEvents: function() {
this.element.off('mouseover.puibutton mouseout.puibutton mousedown.puibutton mouseup.puibutton focus.puibutton blur.puibutton keydown.puibutton keyup.puibutton');
},
disable: function() {
this._unbindEvents();
this.element.attr({
'disabled':'disabled',
'aria-disabled': true
}).addClass('ui-state-disabled');
},
enable: function() {
if(this.element.prop('disabled')) {
this._bindEvents();
this.element.removeAttr('disabled').attr('aria-disabled', false).removeClass('ui-state-disabled');
}
}
});
})();/**
* PrimeUI Carousel widget
*/
(function() {
$.widget("primeui.puicarousel", {
options: {
datasource: null,
numVisible: 3,
firstVisible: 0,
headerText: null,
effectDuration: 500,
circular :false,
breakpoint: 560,
itemContent: null,
responsive: true,
autoplayInterval: 0,
easing: 'easeInOutCirc',
pageLinks: 3,
styleClass: null,
template: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
//create elements
this.element.wrap('<div class="pui-carousel ui-widget ui-widget-content ui-corner-all"><div class="pui-carousel-viewport"></div></div>');
this.container = this.element.parent().parent();
this.element.addClass('pui-carousel-items');
this.container.prepend('<div class="pui-carousel-header ui-widget-header"><div class="pui-carousel-header-title"></div></div>');
this.viewport = this.element.parent();
this.header = this.container.children('.pui-carousel-header');
this.header.append('<span class="pui-carousel-button pui-carousel-next-button fa fa-arrow-circle-right"></span>' +
'<span class="pui-carousel-button pui-carousel-prev-button fa fa-arrow-circle-left"></span>');
if(this.options.headerText) {
this.header.children('.pui-carousel-header-title').html(this.options.headerText);
}
if(this.options.styleClass) {
this.container.addClass(this.options.styleClass);
}
if(this.options.datasource)
this._loadData();
else
this._render();
},
_loadData: function() {
if($.isArray(this.options.datasource))
this._render(this.options.datasource);
else if($.type(this.options.datasource) === 'function')
this.options.datasource.call(this, this._render);
},
_updateDatasource: function(value) {
this.options.datasource = value;
this.element.children().remove();
this.header.children('.pui-carousel-page-links').remove();
this.header.children('select').remove();
this._loadData();
},
_render: function(data) {
this.data = data;
if(this.data) {
for(var i = 0; i < data.length; i++) {
var itemContent = this._createItemContent(data[i]);
if($.type(itemContent) === 'string')
this.element.append('<li>' + itemContent + '</li>');
else
this.element.append($('<li></li>').wrapInner(itemContent));
}
}
this.items = this.element.children('li');
this.items.addClass('pui-carousel-item ui-widget-content ui-corner-all');
this.itemsCount = this.items.length;
this.columns = this.options.numVisible;
this.first = this.options.firstVisible;
this.page = parseInt(this.first/this.columns);
this.totalPages = Math.ceil(this.itemsCount/this.options.numVisible);
this._renderPageLinks();
this.prevNav = this.header.children('.pui-carousel-prev-button');
this.nextNav = this.header.children('.pui-carousel-next-button');
this.pageLinks = this.header.find('> .pui-carousel-page-links > .pui-carousel-page-link');
this.dropdown = this.header.children('.pui-carousel-dropdown');
this.mobileDropdown = this.header.children('.pui-carousel-mobiledropdown');
this._bindEvents();
if(this.options.responsive) {
this.refreshDimensions();
}
else {
this.calculateItemWidths();
this.container.width(this.container.width());
this.updateNavigators();
}
},
_renderPageLinks: function() {
if(this.totalPages <= this.options.pageLinks) {
this.pageLinksContainer = $('<div class="pui-carousel-page-links"></div>');
for(var i = 0; i < this.totalPages; i++) {
this.pageLinksContainer.append('<a href="#" class="pui-carousel-page-link fa fa-circle-o"></a>');
}
this.header.append(this.pageLinksContainer);
}
else {
this.dropdown = $('<select class="pui-carousel-dropdown ui-widget ui-state-default ui-corner-left"></select>');
for(var i = 0; i < this.totalPages; i++) {
var pageNumber = (i+1);
this.dropdown.append('<option value="' + pageNumber + '">' + pageNumber + '</option>');
}
this.header.append(this.dropdown);
}
if(this.options.responsive) {
this.mobileDropdown = $('<select class="pui-carousel-mobiledropdown ui-widget ui-state-default ui-corner-left"></select>');
for(var i = 0; i < this.itemsCount; i++) {
var pageNumber = (i+1);
this.mobileDropdown.append('<option value="' + pageNumber + '">' + pageNumber + '</option>');
}
this.header.append(this.mobileDropdown);
}
},
calculateItemWidths: function() {
var firstItem = this.items.eq(0);
if(firstItem.length) {
var itemFrameWidth = firstItem.outerWidth(true) - firstItem.width(); //sum of margin, border and padding
this.items.width((this.viewport.innerWidth() - itemFrameWidth * this.columns) / this.columns);
}
},
refreshDimensions: function() {
var win = $(window);
if(win.width() <= this.options.breakpoint) {
this.columns = 1;
this.calculateItemWidths(this.columns);
this.totalPages = this.itemsCount;
this.mobileDropdown.show();
this.pageLinks.hide();
}
else {
this.columns = this.options.numVisible;
this.calculateItemWidths();
this.totalPages = Math.ceil(this.itemsCount / this.options.numVisible);
this.mobileDropdown.hide();
this.pageLinks.show();
}
this.page = parseInt(this.first / this.columns);
this.updateNavigators();
this.element.css('left', (-1 * (this.viewport.innerWidth() * this.page)));
},
_bindEvents: function() {
var $this = this;
if(this.eventsBound) {
return;
}
this.prevNav.on('click.puicarousel', function() {
if($this.page !== 0) {
$this.setPage($this.page - 1);
}
else if($this.options.circular) {
$this.setPage($this.totalPages - 1);
}
});
this.nextNav.on('click.puicarousel', function() {
var lastPage = ($this.page === ($this.totalPages - 1));
if(!lastPage) {
$this.setPage($this.page + 1);
}
else if($this.options.circular) {
$this.setPage(0);
}
});
this.element.swipe({
swipe:function(event, direction) {
if(direction === 'left') {
if($this.page === ($this.totalPages - 1)) {
if($this.options.circular)
$this.setPage(0);
}
else {
$this.setPage($this.page + 1);
}
}
else if(direction === 'right') {
if($this.page === 0) {
if($this.options.circular)
$this.setPage($this.totalPages - 1);
}
else {
$this.setPage($this.page - 1);
}
}
}
});
if(this.pageLinks.length) {
this.pageLinks.on('click', function(e) {
$this.setPage($(this).index());
e.preventDefault();
});
}
this.header.children('select').on('change', function() {
$this.setPage(parseInt($(this).val()) - 1);
});
if(this.options.autoplayInterval) {
this.options.circular = true;
this.startAutoplay();
}
if(this.options.responsive) {
var resizeNS = 'resize.' + this.id;
$(window).off(resizeNS).on(resizeNS, function() {
$this.refreshDimensions();
});
}
this.eventsBound = true;
},
updateNavigators: function() {
if(!this.options.circular) {
if(this.page === 0) {
this.prevNav.addClass('ui-state-disabled');
this.nextNav.removeClass('ui-state-disabled');
}
else if(this.page === (this.totalPages - 1)) {
this.prevNav.removeClass('ui-state-disabled');
this.nextNav.addClass('ui-state-disabled');
}
else {
this.prevNav.removeClass('ui-state-disabled');
this.nextNav.removeClass('ui-state-disabled');
}
}
if(this.pageLinks.length) {
this.pageLinks.filter('.fa-dot-circle-o').removeClass('fa-dot-circle-o');
this.pageLinks.eq(this.page).addClass('fa-dot-circle-o');
}
if(this.dropdown.length) {
this.dropdown.val(this.page + 1);
}
if(this.mobileDropdown.length) {
this.mobileDropdown.val(this.page + 1);
}
},
setPage: function(p) {
if(p !== this.page && !this.element.is(':animated')) {
var $this = this;
this.element.animate({
left: -1 * (this.viewport.innerWidth() * p)
,easing: this.options.easing
},
{
duration: this.options.effectDuration,
easing: this.options.easing,
complete: function() {
$this.page = p;
$this.first = $this.page * $this.columns;
$this.updateNavigators();
$this._trigger('pageChange', null, {'page':p});
}
});
}
},
startAutoplay: function() {
var $this = this;
this.interval = setInterval(function() {
if($this.page === ($this.totalPages - 1))
$this.setPage(0);
else
$this.setPage($this.page + 1);
}, this.options.autoplayInterval);
},
stopAutoplay: function() {
clearInterval(this.interval);
},
_setOption: function(key, value) {
if(key === 'datasource')
this._updateDatasource(value);
else
$.Widget.prototype._setOption.apply(this, arguments);
},
_createItemContent: function(obj) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, obj);
}
else {
return this.options.itemContent.call(this, obj);
}
}
});
})();/**
* PrimeUI checkbox widget
*/
(function() {
$.widget("primeui.puicheckbox", {
_create: function() {
this.element.wrap('<div class="pui-chkbox ui-widget"><div class="ui-helper-hidden-accessible"></div></div>');
this.container = this.element.parent().parent();
this.box = $('<div class="pui-chkbox-box ui-widget ui-corner-all ui-state-default">').appendTo(this.container);
this.icon = $('<span class="pui-chkbox-icon pui-c"></span>').appendTo(this.box);
this.disabled = this.element.prop('disabled');
this.label = $('label[for="' + this.element.attr('id') + '"]');
if(this.isChecked()) {
this.box.addClass('ui-state-active');
this.icon.addClass('fa fa-fw fa-check');
}
if(this.disabled) {
this.box.addClass('ui-state-disabled');
} else {
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.box.on('mouseover.puicheckbox', function() {
if(!$this.isChecked())
$this.box.addClass('ui-state-hover');
})
.on('mouseout.puicheckbox', function() {
$this.box.removeClass('ui-state-hover');
})
.on('click.puicheckbox', function() {
$this.toggle();
});
this.element.focus(function() {
if($this.isChecked()) {
$this.box.removeClass('ui-state-active');
}
$this.box.addClass('ui-state-focus');
})
.blur(function() {
if($this.isChecked()) {
$this.box.addClass('ui-state-active');
}
$this.box.removeClass('ui-state-focus');
})
.keydown(function(e) {
var keyCode = $.ui.keyCode;
if(e.which == keyCode.SPACE) {
e.preventDefault();
}
})
.keyup(function(e) {
var keyCode = $.ui.keyCode;
if(e.which == keyCode.SPACE) {
$this.toggle(true);
e.preventDefault();
}
});
this.label.on('click.puicheckbox', function(e) {
$this.toggle();
e.preventDefault();
});
},
toggle: function(keypress) {
if(this.isChecked()) {
this.uncheck(keypress);
} else {
this.check(keypress);
}
this._trigger('change', null, this.isChecked());
},
isChecked: function() {
return this.element.prop('checked');
},
check: function(activate, silent) {
if(!this.isChecked()) {
this.element.prop('checked', true);
this.icon.addClass('fa fa-fw fa-check');
if(!activate) {
this.box.addClass('ui-state-active');
}
if(!silent) {
this.element.trigger('change');
}
}
},
uncheck: function() {
if(this.isChecked()) {
this.element.prop('checked', false);
this.box.removeClass('ui-state-active');
this.icon.removeClass('fa fa-fw fa-check');
this.element.trigger('change');
}
},
_unbindEvents: function() {
this.box.off();
this.element.off('focus blur keydown keyup');
this.label.off();
},
disable: function() {
this.box.prop('disabled', true);
this.box.attr('aria-disabled', true);
this.box.addClass('ui-state-disabled').removeClass('ui-state-hover');
this._unbindEvents();
},
enable: function() {
this.box.prop('disabled', false);
this.box.attr('aria-disabled', false);
this.box.removeClass('ui-state-disabled');
this._bindEvents();
}
});
})();/**
* PrimeUI Datatable Widget
*/
(function() {
$.widget("primeui.puidatatable", {
options: {
columns: null,
datasource: null,
paginator: null,
selectionMode: null,
caption: null,
footer: null,
sortField: null,
sortOrder: null,
keepSelectionInLazyMode: false,
scrollable: false,
scrollHeight: null,
scrollWidth: null,
responsive: false,
expandableRows: false,
expandedRowContent: null,
rowExpandMode: 'multiple',
draggableColumns: false,
resizableColumns: false,
columnResizeMode: 'fit',
draggableRows: false,
filterDelay: 300,
stickyHeader: false,
editMode: null,
tabindex: 0,
emptyMessage: 'No records found',
sort: null,
rowSelect: null,
rowUnselect: null,
rowSelectContextMenu: null,
rowCollapse: null,
rowExpand: null,
colReorder: null,
colResize: null,
rowReorder: null,
cellEdit: null,
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.addClass('pui-datatable ui-widget');
if(this.options.responsive) {
this.element.addClass('pui-datatable-reflow');
}
if(this.options.scrollable) {
this._createScrollableDatatable();
}
else {
this._createRegularDatatable();
}
if(this.options.datasource) {
if($.isArray(this.options.datasource)) {
this._onDataInit(this.options.datasource);
}
else {
if($.type(this.options.datasource) === 'string') {
var $this = this,
dataURL = this.options.datasource;
this.options.datasource = function() {
$.ajax({
type: 'GET',
url: dataURL,
dataType: "json",
context: $this,
success: function (response) {
this._onDataInit(response);
}
});
};
}
if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onDataInit, {first:0, sortField:this.options.sortField, sortOrder:this.options.sortOrder});
else
this.options.datasource.call(this, this._onDataInit);
}
}
}
},
_createRegularDatatable: function() {
this.tableWrapper = $('<div class="pui-datatable-tablewrapper" />').appendTo(this.element);
this.table = $('<table><thead></thead><tbody></tbody></table>').appendTo(this.tableWrapper);
this.thead = this.table.children('thead');
this.tbody = this.table.children('tbody').addClass('pui-datatable-data');
if(this.containsFooter()) {
this.tfoot = this.thead.after('<tfoot></tfoot>').next();
}
},
_createScrollableDatatable: function() {
this.element.append('<div class="ui-widget-header pui-datatable-scrollable-header"><div class="pui-datatable-scrollable-header-box"><table><thead></thead></table></div></div>')
.append('<div class="pui-datatable-scrollable-body"><table><tbody></tbody></table></div>');
this.thead = this.element.find('> .pui-datatable-scrollable-header > .pui-datatable-scrollable-header-box > table > thead');
this.tbody = this.element.find('> .pui-datatable-scrollable-body > table > tbody');
if(this.containsFooter()) {
this.element.append('<div class="ui-widget-header pui-datatable-scrollable-footer"><div class="pui-datatable-scrollable-footer-box"><table><tfoot></tfoot></table></div></div>');
this.tfoot = this.element.find('> .pui-datatable-scrollable-footer > .pui-datatable-scrollable-footer-box > table > tfoot');
}
},
_initialize: function() {
var $this = this;
this._initHeader();
this._initFooter();
if(this.options.caption) {
this.element.prepend('<div class="pui-datatable-caption ui-widget-header">' + this.options.caption + '</div>');
}
if(this.options.paginator) {
this.options.paginator.paginate = function(event, state) {
$this.paginate();
};
this.options.paginator.totalRecords = this.options.lazy ? this.options.paginator.totalRecords : this.data.length;
this.paginator = $('<div></div>').insertAfter(this.tableWrapper).puipaginator(this.options.paginator);
}
if(this.options.footer) {
this.element.append('<div class="pui-datatable-footer ui-widget-header">' + this.options.footer + '</div>');
}
if(this._isSortingEnabled()) {
this._initSorting();
}
if(this.hasFiltering) {
this._initFiltering();
}
if(this.options.selectionMode) {
this._initSelection();
}
if(this.options.expandableRows) {
this._initExpandableRows();
}
if(this.options.draggableColumns) {
this._initDraggableColumns();
}
if(this.options.stickyHeader) {
this._initStickyHeader();
}
if (this.options.sortField && this.options.sortOrder) {
this._indicateInitialSortColumn();
this.sort(this.options.sortField, this.options.sortOrder);
}
else {
this._renderData();
}
if(this.options.scrollable) {
this._initScrolling();
}
if(this.options.resizableColumns) {
this._initResizableColumns();
}
if(this.options.draggableRows) {
this._initDraggableRows();
}
if(this.options.editMode) {
this._initEditing();
}
},
_initHeader: function() {
if(this.options.headerRows) {
for(var i = 0; i < this.options.headerRows.length; i++) {
this._initHeaderColumns(this.options.headerRows[i].columns);
}
}
else if(this.options.columns) {
this._initHeaderColumns(this.options.columns);
}
},
_initFooter: function() {
if(this.containsFooter()) {
if(this.options.footerRows) {
for(var i = 0; i < this.options.footerRows.length; i++) {
this._initFooterColumns(this.options.footerRows[i].columns);
}
}
else if(this.options.columns) {
this._initFooterColumns(this.options.columns);
}
}
},
_initHeaderColumns: function(columns) {
var headerRow = $('<tr></tr>').appendTo(this.thead),
$this = this;
$.each(columns, function(i, col) {
var cell = $('<th class="ui-state-default"><span class="pui-column-title"></span></th>').data('field', col.field).uniqueId().appendTo(headerRow);
if(col.headerClass) {
cell.addClass(col.headerClass);
}
if(col.headerStyle) {
cell.attr('style', col.headerStyle);
}
if(col.headerText)
cell.children('.pui-column-title').text(col.headerText);
else if(col.headerContent)
cell.children('.pui-column-title').append(col.headerContent.call(this, col));
if(col.rowspan) {
cell.attr('rowspan', col.rowspan);
}
if(col.colspan) {
cell.attr('colspan', col.colspan);
}
if(col.sortable) {
cell.addClass('pui-sortable-column')
.data('order', 0)
.append('<span class="pui-sortable-column-icon fa fa-fw fa-sort"></span>');
}
if(col.filter) {
$this.hasFiltering = true;
var filterElement = $('<input type="text" class="pui-column-filter" />').puiinputtext().data({
'field': col.field,
'filtermatchmode': col.filterMatchMode||'startsWith'
}).appendTo(cell);
if(col.filterFunction) {
filterElement.on('filter', function(event, dataValue, filterValue) {
return col.filterFunction.call($this, dataValue, filterValue);
});
}
}
});
},
_initFooterColumns: function(columns) {
var footerRow = $('<tr></tr>').appendTo(this.tfoot);
$.each(columns, function(i, col) {
var cell = $('<td class="ui-state-default"></td>');
if(col.footerText) {
cell.text(col.footerText);
}
if(col.rowspan) {
cell.attr('rowspan', col.rowspan);
}
if(col.colspan) {
cell.attr('colspan', col.colspan);
}
cell.appendTo(footerRow);
});
},
_indicateInitialSortColumn: function() {
this.sortableColumns = this.thead.find('> tr > th.pui-sortable-column');
var $this = this;
$.each(this.sortableColumns, function(i, column) {
var $column = $(column),
data = $column.data();
if ($this.options.sortField === data.field) {
var sortIcon = $column.children('.pui-sortable-column-icon');
$column.data('order', $this.options.sortOrder).removeClass('ui-state-hover').addClass('ui-state-active');
if($this.options.sortOrder === -1)
sortIcon.removeClass('fa-sort fa-sort-asc').addClass('fa-sort-desc');
else if($this.options.sortOrder === 1)
sortIcon.removeClass('fa-sort fa-sort-desc').addClass('fa-sort-asc');
}
});
},
_onDataInit: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this._initialize();
},
_onDataUpdate: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this.reset();
this._renderData();
},
_onLazyLoad: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this._renderData();
},
reset: function() {
if(this.options.selectionMode) {
this.selection = [];
}
if(this.paginator) {
this.paginator.puipaginator('setState', {
page: 0,
totalRecords: this.options.lazy ? this.options.paginator.totalRecords : this.data.length
});
}
this.thead.children('th.pui-sortable-column').data('order', 0).filter('.ui-state-active').removeClass('ui-state-active')
.children('span.pui-sortable-column-icon').removeClass('fa-sort-asc fa-sort-desc').addClass('fa-sort');
},
_initSorting: function() {
var $this = this,
sortableColumns = this.thead.find('> tr > th.pui-sortable-column');
sortableColumns.on('mouseover.puidatatable', function() {
var column = $(this);
if(!column.hasClass('ui-state-active'))
column.addClass('ui-state-hover');
})
.on('mouseout.puidatatable', function() {
var column = $(this);
if(!column.hasClass('ui-state-active'))
column.removeClass('ui-state-hover');
})
.on('click.puidatatable', function(event) {
if(!$(event.target).is('th,span')) {
return;
}
var column = $(this),
sortField = column.data('field'),
order = column.data('order'),
sortOrder = (order === 0) ? 1 : (order * -1),
sortIcon = column.children('.pui-sortable-column-icon');
//clean previous sort state
column.siblings().filter('.ui-state-active').data('order', 0).removeClass('ui-state-active').children('span.pui-sortable-column-icon')
.removeClass('fa-sort-asc fa-sort-desc').addClass('fa-sort');
//update state
$this.options.sortField = sortField;
$this.options.sortOrder = sortOrder;
$this.sort(sortField, sortOrder);
column.data('order', sortOrder).removeClass('ui-state-hover').addClass('ui-state-active');
if(sortOrder === -1)
sortIcon.removeClass('fa-sort fa-sort-asc').addClass('fa-sort-desc');
else if(sortOrder === 1)
sortIcon.removeClass('fa-sort fa-sort-desc').addClass('fa-sort-asc');
$this._trigger('sort', event, {'sortOrder' : sortOrder, 'sortField' : sortField});
});
},
paginate: function() {
if(this.options.lazy) {
if(this.options.selectionMode && ! this.options.keepSelectionInLazyMode) {
this.selection = [];
}
this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta());
}
else {
this._renderData();
}
},
sort: function(field, order) {
if(this.options.selectionMode) {
this.selection = [];
}
if(this.options.lazy) {
this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta());
}
else {
this.data.sort(function(data1, data2) {
var value1 = data1[field], value2 = data2[field],
result = null;
if (typeof value1 == 'string' || value1 instanceof String) {
if ( value1.localeCompare ) {
return (order * value1.localeCompare(value2));
}
else {
if (value1.toLowerCase) {
value1 = value1.toLowerCase();
}
if (value2.toLowerCase) {
value2 = value2.toLowerCase();
}
result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
}
}
else {
result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
}
return (order * result);
});
if(this.options.selectionMode) {
this.selection = [];
}
if(this.paginator) {
this.paginator.puipaginator('option', 'page', 0);
}
this._renderData();
}
},
sortByField: function(a, b) {
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
},
_renderData: function() {
this.tbody.html('');
var dataToRender = this.filteredData||this.data;
if(dataToRender && dataToRender.length) {
var firstNonLazy = this._getFirst(),
first = this.options.lazy ? 0 : firstNonLazy,
rows = this._getRows();
for(var i = first; i < (first + rows); i++) {
var rowData = dataToRender[i];
if(rowData) {
var row = $('<tr class="ui-widget-content" />').appendTo(this.tbody),
zebraStyle = (i%2 === 0) ? 'pui-datatable-even' : 'pui-datatable-odd',
rowIndex = i;
row.addClass(zebraStyle);
if(this.options.lazy) {
rowIndex += firstNonLazy; // Selection is kept as it is non lazy data
}
if(this.options.selectionMode && PUI.inArray(this.selection, rowIndex)) {
row.addClass("ui-state-highlight");
}
row.data('rowindex', rowIndex);
for(var j = 0; j < this.options.columns.length; j++) {
var column = $('<td />').appendTo(row),
columnOptions = this.options.columns[j];
if(columnOptions.bodyClass) {
column.addClass(columnOptions.bodyClass);
}
if(columnOptions.bodyStyle) {
column.attr('style', columnOptions.bodyStyle);
}
if(columnOptions.editor) {
column.addClass('pui-editable-column').data({
'editor': columnOptions.editor,
'rowdata': rowData,
'field': columnOptions.field
});
}
if(columnOptions.content) {
var content = columnOptions.content.call(this, rowData);
if($.type(content) === 'string')
column.html(content);
else
column.append(content);
}
else if(columnOptions.rowToggler) {
column.append('<div class="pui-row-toggler fa fa-fw fa-chevron-circle-right pui-c"></div>');
}
else if(columnOptions.field) {
column.text(rowData[columnOptions.field]);
}
if(this.options.responsive && columnOptions.headerText) {
column.prepend('<span class="pui-column-title">' + columnOptions.headerText + '</span>');
}
}
}
}
}
else {
var emptyRow = $('<tr class="ui-widget-content"></tr>').appendTo(this.tbody);
var emptyColumn = $('<td></td>').attr('colspan',this.options.columns.length).appendTo(emptyRow);
emptyColumn.html(this.options.emptyMessage);
}
},
_getFirst: function() {
if(this.paginator) {
var page = this.paginator.puipaginator('option', 'page'),
rows = this.paginator.puipaginator('option', 'rows');
return (page * rows);
}
else {
return 0;
}
},
_getRows: function() {
return this.paginator ? this.paginator.puipaginator('option', 'rows') : this.data.length;
},
_isSortingEnabled: function() {
var cols = this.options.columns;
if(cols) {
for(var i = 0; i < cols.length; i++) {
if(cols[i].sortable) {
return true;
}
}
}
return false;
},
_initSelection: function() {
var $this = this;
this.selection = [];
this.rowSelector = '> tr.ui-widget-content:not(.pui-datatable-empty-message,.pui-datatable-unselectable)';
//shift key based range selection
if(this._isMultipleSelection()) {
this.originRowIndex = 0;
this.cursorIndex = null;
}
this.tbody.off('mouseover.puidatatable mouseout.puidatatable mousedown.puidatatable click.puidatatable', this.rowSelector)
.on('mouseover.datatable', this.rowSelector, null, function() {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.addClass('ui-state-hover');
}
})
.on('mouseout.datatable', this.rowSelector, null, function() {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.removeClass('ui-state-hover');
}
})
.on('mousedown.datatable', this.rowSelector, null, function() {
$this.mousedownOnRow = true;
})
.on('click.datatable', this.rowSelector, null, function(e) {
$this._onRowClick(e, this);
$this.mousedownOnRow = false;
});
this._bindSelectionKeyEvents();
},
_onRowClick: function(event, rowElement) {
if(!$(event.target).is(':input,:button,a,.pui-c')) {
var row = $(rowElement),
selected = row.hasClass('ui-state-highlight'),
metaKey = event.metaKey||event.ctrlKey,
shiftKey = event.shiftKey;
this.focusedRow = row;
//unselect a selected row if metakey is on
if(selected && metaKey) {
this.unselectRow(row);
}
else {
//unselect previous selection if this is single selection or multiple one with no keys
if(this._isSingleSelection() || (this._isMultipleSelection() && !metaKey && !shiftKey)) {
if (this._isMultipleSelection()) {
var selections = this.getSelection();
for (var i = 0; i < selections.length; i++) {
this._trigger('rowUnselect', null, selections[i]);
}
}
this.unselectAllRows();
}
this.selectRow(row, false, event);
}
PUI.clearSelection();
}
},
onRowRightClick: function(event, rowElement) {
var row = $(rowElement),
rowIndex = this._getRowIndex(row),
selectedData = this.data[rowIndex],
selected = row.hasClass('ui-state-highlight');
if(this._isSingleSelection() || !selected) {
this.unselectAllRows();
}
this.selectRow(row, true);
this.dataSelectedByContextMenu = selectedData;
this._trigger('rowSelectContextMenu', event, selectedData);
PUI.clearSelection();
},
_bindSelectionKeyEvents: function() {
var $this = this;
this.tbody.attr('tabindex', this.options.tabindex).on('focus', function(e) {
//ignore mouse click on row
if(!$this.mousedownOnRow) {
$this.focusedRow = $this.tbody.children('tr.ui-widget-content').eq(0);
$this.focusedRow.addClass('ui-state-hover');
}
})
.on('blur', function() {
if($this.focusedRow) {
$this.focusedRow.removeClass('ui-state-hover');
$this.focusedRow = null;
}
})
.on('keydown', function(e) {
var keyCode = $.ui.keyCode,
key = e.which;
if($this.focusedRow) {
switch(key) {
case keyCode.UP:
var prevRow = $this.focusedRow.prev('tr.ui-widget-content');
if(prevRow.length) {
$this.focusedRow.removeClass('ui-state-hover');
$this.focusedRow = prevRow;
$this.focusedRow.addClass('ui-state-hover');
}
e.preventDefault();
break;
case keyCode.DOWN:
var nextRow = $this.focusedRow.next('tr.ui-widget-content');
if(nextRow.length) {
$this.focusedRow.removeClass('ui-state-hover');
$this.focusedRow = nextRow;
$this.focusedRow.addClass('ui-state-hover');
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
case keyCode.SPACE:
e.target = $this.focusedRow.children().eq(0).get(0);
$this._onRowClick(e, $this.focusedRow.get(0));
e.preventDefault();
break;
default:
break;
};
}
});
},
_isSingleSelection: function() {
return this.options.selectionMode === 'single';
},
_isMultipleSelection: function() {
return this.options.selectionMode === 'multiple';
},
unselectAllRows: function() {
this.tbody.children('tr.ui-state-highlight').removeClass('ui-state-highlight').attr('aria-selected', false);
this.selection = [];
},
unselectRow: function(row, silent) {
var rowIndex = this._getRowIndex(row);
row.removeClass('ui-state-highlight').attr('aria-selected', false);
this._removeSelection(rowIndex);
if(!silent) {
this._trigger('rowUnselect', null, this.data[rowIndex]);
}
},
selectRow: function(row, silent, event) {
var rowIndex = this._getRowIndex(row),
selectedData = this.data[rowIndex];
row.removeClass('ui-state-hover').addClass('ui-state-highlight').attr('aria-selected', true);
this._addSelection(rowIndex);
if(!silent) {
if (this.options.lazy) {
selectedData = this.data[rowIndex - this._getFirst()];
}
this._trigger('rowSelect', event, selectedData);
}
},
getSelection: function() {
var first = this.options.lazy ? this._getFirst() : 0,
selections = [];
for(var i = 0; i < this.selection.length; i++) {
if(this.data.length > this.selection[i]-first && this.selection[i]-first > 0) {
selections.push(this.data[this.selection[i]-first]);
}
}
return selections;
},
_removeSelection: function(rowIndex) {
this.selection = $.grep(this.selection, function(value) {
return value !== rowIndex;
});
},
_addSelection: function(rowIndex) {
if(!this._isSelected(rowIndex)) {
this.selection.push(rowIndex);
}
},
_isSelected: function(rowIndex) {
return PUI.inArray(this.selection, rowIndex);
},
_getRowIndex: function(row) {
return row.data('rowindex');
},
_initExpandableRows: function() {
var $this = this,
togglerSelector = '> tr > td > div.pui-row-toggler';
this.tbody.off('click', togglerSelector)
.on('click', togglerSelector, null, function() {
$this.toggleExpansion($(this));
})
.on('keydown', togglerSelector, null, function(e) {
var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) {
$this.toggleExpansion($(this));
e.preventDefault();
}
});
},
toggleExpansion: function(toggler) {
var row = toggler.closest('tr'),
expanded = toggler.hasClass('fa-chevron-circle-down');
if(expanded) {
toggler.addClass('fa-chevron-circle-right').removeClass('fa-chevron-circle-down').attr('aria-expanded', false);
this.collapseRow(row);
this._trigger('rowCollapse', null, this.data[this._getRowIndex(row)]);
}
else {
if(this.options.rowExpandMode === 'single') {
this.collapseAllRows();
}
toggler.addClass('fa-chevron-circle-down').removeClass('fa-chevron-circle-right').attr('aria-expanded', true);
this.loadExpandedRowContent(row);
}
},
loadExpandedRowContent: function(row) {
var rowIndex = this._getRowIndex(row),
expandedRow = $('<tr class="pui-expanded-row-content pui-datatable-unselectable ui-widget-content"><td colspan="' + this.options.columns.length + '"></td></tr>');
expandedRow.children('td').append(this.options.expandedRowContent.call(this, this.data[rowIndex]));
row.addClass('pui-expanded-row').after(expandedRow);
this._trigger('rowExpand', null, this.data[this._getRowIndex(row)]);
},
collapseRow: function(row) {
row.removeClass('pui-expanded-row').next('.pui-expanded-row-content').remove();
},
collapseAllRows: function() {
var $this = this;
this.getExpandedRows().each(function () {
var expandedRow = $(this);
$this.collapseRow(expandedRow);
var columns = expandedRow.children('td');
for (var i = 0; i < columns.length; i++) {
var column = columns.eq(i),
toggler = column.children('.pui-row-toggler');
if (toggler.length) {
toggler.addClass('fa-chevron-circle-right').removeClass('fa-chevron-circle-down');
}
}
});
},
getExpandedRows: function () {
return this.tbody.children('.pui-expanded-row');
},
_createStateMeta: function() {
var state = {
first: this._getFirst(),
rows: this._getRows(),
sortField: this.options.sortField,
sortOrder: this.options.sortOrder,
filters: this.filterMetaMap
};
return state;
},
_updateDatasource: function(datasource) {
this.options.datasource = datasource;
if($.isArray(this.options.datasource)) {
this._onDataUpdate(this.options.datasource);
}
else if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onDataUpdate, {first:0, sortField:this.options.sortField, sortorder:this.options.sortOrder});
else
this.options.datasource.call(this, this._onDataUpdate);
}
},
_setOption: function(key, value) {
if(key === 'datasource') {
this._updateDatasource(value);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_initScrolling: function() {
this.scrollHeader = this.element.children('.pui-datatable-scrollable-header');
this.scrollBody = this.element.children('.pui-datatable-scrollable-body');
this.scrollHeaderBox = this.scrollHeader.children('.pui-datatable-scrollable-header-box');
this.headerTable = this.scrollHeaderBox.children('table');
this.bodyTable = this.scrollBody.children('table');
this.percentageScrollHeight = this.options.scrollHeight && (this.options.scrollHeight.indexOf('%') !== -1);
this.percentageScrollWidth = this.options.scrollWidth && (this.options.scrollWidth.indexOf('%') !== -1);
var $this = this,
scrollBarWidth = this.getScrollbarWidth() + 'px';
if(this.options.scrollHeight) {
if(this.percentageScrollHeight)
this.adjustScrollHeight();
else
this.scrollBody.css('max-height', this.options.scrollHeight + 'px');
if(this.hasVerticalOverflow()) {
this.scrollHeaderBox.css('margin-right', scrollBarWidth);
}
}
this.fixColumnWidths();
if(this.options.scrollWidth) {
if(this.percentageScrollWidth)
this.adjustScrollWidth();
else
this.setScrollWidth(parseInt(this.options.scrollWidth));
}
this.cloneHead();
this.scrollBody.on('scroll.dataTable', function() {
var scrollLeft = $this.scrollBody.scrollLeft();
$this.scrollHeaderBox.css('margin-left', -scrollLeft);
});
this.scrollHeader.on('scroll.dataTable', function() {
$this.scrollHeader.scrollLeft(0);
});
var resizeNS = 'resize.' + this.id;
$(window).off(resizeNS).on(resizeNS, function() {
if($this.element.is(':visible')) {
if($this.percentageScrollHeight)
$this.adjustScrollHeight();
if($this.percentageScrollWidth)
$this.adjustScrollWidth();
}
});
},
cloneHead: function() {
this.theadClone = this.thead.clone();
this.theadClone.find('th').each(function() {
var header = $(this);
header.attr('id', header.attr('id') + '_clone');
$(this).children().not('.pui-column-title').remove();
});
this.theadClone.removeAttr('id').addClass('pui-datatable-scrollable-theadclone').height(0).prependTo(this.bodyTable);
//align horizontal scroller on keyboard tab
if(this.options.scrollWidth) {
var clonedSortableColumns = this.theadClone.find('> tr > th.pui-sortable-column');
clonedSortableColumns.each(function() {
$(this).data('original', $(this).attr('id').split('_clone')[0]);
});
clonedSortableColumns.on('blur.dataTable', function() {
$(PUI.escapeClientId($(this).data('original'))).removeClass('ui-state-focus');
})
.on('focus.dataTable', function() {
$(PUI.escapeClientId($(this).data('original'))).addClass('ui-state-focus');
})
.on('keydown.dataTable', function(e) {
var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER) && $(e.target).is(':not(:input)')) {
$(PUI.escapeClientId($(this).data('original'))).trigger('click.dataTable', (e.metaKey||e.ctrlKey));
e.preventDefault();
}
});
}
},
adjustScrollHeight: function() {
var relativeHeight = this.element.parent().innerHeight() * (parseInt(this.options.scrollHeight) / 100),
tableHeaderHeight = this.element.children('.pui-datatable-header').outerHeight(true),
tableFooterHeight = this.element.children('.pui-datatable-footer').outerHeight(true),
scrollersHeight = (this.scrollHeader.outerHeight(true) + this.scrollFooter.outerHeight(true)),
paginatorsHeight = this.paginator ? this.paginator.getContainerHeight(true) : 0,
height = (relativeHeight - (scrollersHeight + paginatorsHeight + tableHeaderHeight + tableFooterHeight));
this.scrollBody.css('max-height', height + 'px');
},
adjustScrollWidth: function() {
var width = parseInt((this.element.parent().innerWidth() * (parseInt(this.options.scrollWidth) / 100)));
this.setScrollWidth(width);
},
setOuterWidth: function(element, width) {
var diff = element.outerWidth() - element.width();
element.width(width - diff);
},
setScrollWidth: function(width) {
var $this = this;
this.element.children('.ui-widget-header').each(function() {
$this.setOuterWidth($(this), width);
});
this.scrollHeader.width(width);
this.scrollBody.css('margin-right', 0).width(width);
},
alignScrollBody: function() {
var marginRight = this.hasVerticalOverflow() ? this.getScrollbarWidth() + 'px' : '0px';
this.scrollHeaderBox.css('margin-right', marginRight);
},
getScrollbarWidth: function() {
if(!this.scrollbarWidth) {
this.scrollbarWidth = PUI.browser.webkit ? '15' : PUI.calculateScrollbarWidth();
}
return this.scrollbarWidth;
},
hasVerticalOverflow: function() {
return (this.options.scrollHeight && this.bodyTable.outerHeight() > this.scrollBody.outerHeight())
},
restoreScrollState: function() {
var scrollState = this.scrollStateHolder.val(),
scrollValues = scrollState.split(',');
this.scrollBody.scrollLeft(scrollValues[0]);
this.scrollBody.scrollTop(scrollValues[1]);
},
saveScrollState: function() {
var scrollState = this.scrollBody.scrollLeft() + ',' + this.scrollBody.scrollTop();
this.scrollStateHolder.val(scrollState);
},
clearScrollState: function() {
this.scrollStateHolder.val('0,0');
},
fixColumnWidths: function() {
if(!this.columnWidthsFixed) {
if(this.options.scrollable) {
this.scrollHeaderBox.find('> table > thead > tr > th').each(function() {
var headerCol = $(this),
width = headerCol.width();
headerCol.width(width);
});
}
else {
this.element.find('> .pui-datatable-tablewrapper > table > thead > tr > th').each(function() {
var col = $(this);
col.width(col.width());
});
}
this.columnWidthsFixed = true;
}
},
_initDraggableColumns: function() {
var $this = this;
this.dragIndicatorTop = $('<span class="fa fa-arrow-down" style="position:absolute"/></span>').hide().appendTo(this.element);
this.dragIndicatorBottom = $('<span class="fa fa-arrow-up" style="position:absolute"/></span>').hide().appendTo(this.element);
this.thead.find('> tr > th').draggable({
appendTo: 'body',
opacity: 0.75,
cursor: 'move',
scope: this.id,
cancel: ':input,.ui-column-resizer',
drag: function(event, ui) {
var droppable = ui.helper.data('droppable-column');
if(droppable) {
var droppableOffset = droppable.offset(),
topArrowY = droppableOffset.top - 10,
bottomArrowY = droppableOffset.top + droppable.height() + 8,
arrowX = null;
//calculate coordinates of arrow depending on mouse location
if(event.originalEvent.pageX >= droppableOffset.left + (droppable.width() / 2)) {
var nextDroppable = droppable.next();
if(nextDroppable.length == 1)
arrowX = nextDroppable.offset().left - 9;
else
arrowX = droppable.offset().left + droppable.innerWidth() - 9;
ui.helper.data('drop-location', 1); //right
}
else {
arrowX = droppableOffset.left - 9;
ui.helper.data('drop-location', -1); //left
}
$this.dragIndicatorTop.offset({
'left': arrowX,
'top': topArrowY - 3
}).show();
$this.dragIndicatorBottom.offset({
'left': arrowX,
'top': bottomArrowY - 3
}).show();
}
},
stop: function(event, ui) {
//hide dnd arrows
$this.dragIndicatorTop.css({
'left':0,
'top':0
}).hide();
$this.dragIndicatorBottom.css({
'left':0,
'top':0
}).hide();
},
helper: function() {
var header = $(this),
helper = $('<div class="ui-widget ui-state-default" style="padding:4px 10px;text-align:center;"></div>');
helper.width(header.width());
helper.height(header.height());
helper.html(header.html());
return helper.get(0);
}
}).droppable({
hoverClass:'ui-state-highlight',
tolerance:'pointer',
scope: this.id,
over: function(event, ui) {
ui.helper.data('droppable-column', $(this));
},
drop: function(event, ui) {
var draggedColumnHeader = ui.draggable,
dropLocation = ui.helper.data('drop-location'),
droppedColumnHeader = $(this),
draggedColumnFooter = null,
droppedColumnFooter = null;
var draggedCells = $this.tbody.find('> tr:not(.ui-expanded-row-content) > td:nth-child(' + (draggedColumnHeader.index() + 1) + ')'),
droppedCells = $this.tbody.find('> tr:not(.ui-expanded-row-content) > td:nth-child(' + (droppedColumnHeader.index() + 1) + ')');
if($this.containsFooter()) {
var footerColumns = $this.tfoot.find('> tr > td'),
draggedColumnFooter = footerColumns.eq(draggedColumnHeader.index()),
droppedColumnFooter = footerColumns.eq(droppedColumnHeader.index());
}
//drop right
if(dropLocation > 0) {
/* TODO :Resizable columns
* if($this.options.resizableColumns) {
if(droppedColumnHeader.next().length) {
droppedColumnHeader.children('span.ui-column-resizer').show();
draggedColumnHeader.children('span.ui-column-resizer').hide();
}
}*/
draggedColumnHeader.insertAfter(droppedColumnHeader);
draggedCells.each(function(i, item) {
$(this).insertAfter(droppedCells.eq(i));
});
if(draggedColumnFooter && droppedColumnFooter) {
draggedColumnFooter.insertAfter(droppedColumnFooter);
}
//sync clone
if($this.options.scrollable) {
var draggedColumnClone = $(document.getElementById(draggedColumnHeader.attr('id') + '_clone')),
droppedColumnClone = $(document.getElementById(droppedColumnHeader.attr('id') + '_clone'));
draggedColumnClone.insertAfter(droppedColumnClone);
}
}
//drop left
else {
draggedColumnHeader.insertBefore(droppedColumnHeader);
draggedCells.each(function(i, item) {
$(this).insertBefore(droppedCells.eq(i));
});
if(draggedColumnFooter && droppedColumnFooter) {
draggedColumnFooter.insertBefore(droppedColumnFooter);
}
//sync clone
if($this.options.scrollable) {
var draggedColumnClone = $(document.getElementById(draggedColumnHeader.attr('id') + '_clone')),
droppedColumnClone = $(document.getElementById(droppedColumnHeader.attr('id') + '_clone'));
draggedColumnClone.insertBefore(droppedColumnClone);
}
}
//fire colReorder event
$this._trigger('colReorder', null, {
dragIndex: draggedColumnHeader.index(),
dropIndex: droppedColumnHeader.index()
});
}
});
},
containsFooter: function() {
if(this.hasFooter === undefined) {
this.hasFooter = this.options.footerRows !== undefined;
if(!this.hasFooter) {
if(this.options.columns) {
for(var i = 0; i < this.options.columns.length; i++) {
if(this.options.columns[i].footerText !== undefined) {
this.hasFooter = true;
break;
}
}
}
}
}
return this.hasFooter;
},
_initResizableColumns: function() {
this.element.addClass('pui-datatable-resizable');
this.thead.find('> tr > th').addClass('pui-resizable-column');
this.resizerHelper = $('<div class="pui-column-resizer-helper ui-state-highlight"></div>').appendTo(this.element);
this.addResizers();
var resizers = this.thead.find('> tr > th > span.pui-column-resizer'),
$this = this;
setTimeout(function() {
$this.fixColumnWidths();
}, 5);
resizers.draggable({
axis: 'x',
start: function(event, ui) {
ui.helper.data('originalposition', ui.helper.offset());
var height = $this.options.scrollable ? $this.scrollBody.height() : $this.thead.parent().height() - $this.thead.height() - 1;
$this.resizerHelper.height(height);
$this.resizerHelper.show();
},
drag: function(event, ui) {
$this.resizerHelper.offset({
left: ui.helper.offset().left + ui.helper.width() / 2,
top: $this.thead.offset().top + $this.thead.height()
});
},
stop: function(event, ui) {
ui.helper.css({
'left': '',
'top': '0px',
'right': '0px'
});
$this.resize(event, ui);
$this.resizerHelper.hide();
if($this.options.columnResizeMode === 'expand') {
setTimeout(function() {
$this._trigger('colResize', null, {element: ui.helper.parent()});
}, 5);
}
else {
$this._trigger('colResize', null, {element: ui.helper.parent()});
}
if($this.options.stickyHeader) {
$this.thead.find('.pui-column-filter').prop('disabled', false);
$this.clone = $this.thead.clone(true);
$this.cloneContainer.find('thead').remove();
$this.cloneContainer.children('table').append($this.clone);
$this.thead.find('.ui-column-filter').prop('disabled', true);
}
},
containment: this.element
});
},
resize: function(event, ui) {
var columnHeader, nextColumnHeader, change = null, newWidth = null, nextColumnWidth = null,
expandMode = (this.options.columnResizeMode === 'expand'),
table = this.thead.parent(),
columnHeader = ui.helper.parent(),
nextColumnHeader = columnHeader.next();
change = (ui.position.left - ui.originalPosition.left),
newWidth = (columnHeader.width() + change),
nextColumnWidth = (nextColumnHeader.width() - change);
if((newWidth > 15 && nextColumnWidth > 15) || (expandMode && newWidth > 15)) {
if(expandMode) {
table.width(table.width() + change);
setTimeout(function() {
columnHeader.width(newWidth);
}, 1);
}
else {
columnHeader.width(newWidth);
nextColumnHeader.width(nextColumnWidth);
}
if(this.options.scrollable) {
var cloneTable = this.theadClone.parent(),
colIndex = columnHeader.index();
if(expandMode) {
var $this = this;
//body
cloneTable.width(cloneTable.width() + change);
//footer
this.footerTable.width(this.footerTable.width() + change);
setTimeout(function() {
if($this.hasColumnGroup) {
$this.theadClone.find('> tr:first').children('th').eq(colIndex).width(newWidth); //body
$this.footerTable.find('> tfoot > tr:first').children('th').eq(colIndex).width(newWidth); //footer
}
else {
$this.theadClone.find(PUI.escapeClientId(columnHeader.attr('id') + '_clone')).width(newWidth); //body
$this.footerCols.eq(colIndex).width(newWidth); //footer
}
}, 1);
}
else {
//body
this.theadClone.find(PUI.escapeClientId(columnHeader.attr('id') + '_clone')).width(newWidth);
this.theadClone.find(PUI.escapeClientId(nextColumnHeader.attr('id') + '_clone')).width(nextColumnWidth);
//footer
/*if(this.footerCols.length > 0) {
var footerCol = this.footerCols.eq(colIndex),
nextFooterCol = footerCol.next();
footerCol.width(newWidth);
nextFooterCol.width(nextColumnWidth);
}*/
}
}
}
},
addResizers: function() {
var resizableColumns = this.thead.find('> tr > th.pui-resizable-column');
resizableColumns.prepend('<span class="pui-column-resizer"> </span>');
if(this.options.columnResizeMode === 'fit') {
resizableColumns.filter(':last-child').children('span.pui-column-resizer').hide();
}
},
_initDraggableRows: function() {
var $this = this;
this.tbody.sortable({
placeholder: 'pui-datatable-rowordering ui-state-active',
cursor: 'move',
handle: 'td,span:not(.ui-c)',
appendTo: document.body,
helper: function(event, ui) {
var cells = ui.children(),
helper = $('<div class="pui-datatable ui-widget"><table><tbody></tbody></table></div>'),
helperRow = ui.clone(),
helperCells = helperRow.children();
for(var i = 0; i < helperCells.length; i++) {
helperCells.eq(i).width(cells.eq(i).width());
}
helperRow.appendTo(helper.find('tbody'));
return helper;
},
update: function(event, ui) {
$this.syncRowParity();
$this._trigger('rowReorder', null, {
fromIndex: ui.item.data('ri'),
toIndex: $this._getFirst() + ui.item.index()
});
},
change: function(event, ui) {
if($this.options.scrollable) {
PUI.scrollInView($this.scrollBody, ui.placeholder);
}
}
});
},
syncRowParity: function() {
var rows = this.tbody.children('tr.ui-widget-content');
for(var i = this._getFirst(); i < rows.length; i++) {
var row = rows.eq(i);
row.data('ri', i).removeClass('pui-datatable-even pui-datatable-odd');
if(i % 2 === 0)
row.addClass('pui-datatable-even');
else
row.addClass('pui-datatable-odd');
}
},
getContextMenuSelection: function(data) {
return this.dataSelectedByContextMenu;
},
_initFiltering: function() {
var $this = this;
this.filterElements = this.thead.find('.pui-column-filter');
this.filterElements.on('keyup', function() {
if($this.filterTimeout) {
clearTimeout($this.filterTimeout);
}
$this.filterTimeout = setTimeout(function() {
$this.filter();
$this.filterTimeout = null;
},
$this.options.filterDelay);
});
},
filter: function() {
this.filterMetaMap = [];
for(var i = 0; i < this.filterElements.length; i++) {
var filterElement = this.filterElements.eq(i),
filterElementValue = filterElement.val();
if(filterElementValue && $.trim(filterElementValue) !== '') {
this.filterMetaMap.push({
field: filterElement.data('field'),
filterMatchMode: filterElement.data('filtermatchmode'),
value: filterElementValue.toLowerCase(),
element: filterElement
});
}
}
if(this.options.lazy) {
this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta());
}
else {
if(this.filterMetaMap.length) {
this.filteredData = [];
for(var i = 0; i < this.data.length; i++) {
var localMatch = true;
for(var j = 0; j < this.filterMetaMap.length; j++) {
var filterMeta = this.filterMetaMap[j],
filterValue = filterMeta.value,
filterField = filterMeta.field,
dataFieldValue = this.data[i][filterField];
if(filterMeta.filterMatchMode === 'custom') {
localMatch = filterMeta.element.triggerHandler('filter', [dataFieldValue, filterValue]);
}
else {
var filterConstraint = this.filterConstraints[filterMeta.filterMatchMode];
if(!filterConstraint(dataFieldValue, filterValue)) {
localMatch = false;
}
}
if(!localMatch) {
break;
}
}
if(localMatch) {
this.filteredData.push(this.data[i]);
}
}
}
else {
this.filteredData = null;
}
if(this.paginator) {
this.paginator.puipaginator('option', 'totalRecords', this.filteredData ? this.filteredData.length : this.data ? this.data.length : 0);
}
this._renderData();
}
},
filterConstraints: {
startsWith: function(value, filter) {
if(filter === undefined || filter === null || $.trim(filter) === '') {
return true;
}
if(value === undefined || value === null) {
return false;
}
return value.toString().toLowerCase().slice(0, filter.length) === filter;
},
contains: function(value, filter) {
if(filter === undefined || filter === null || $.trim(filter) === '') {
return true;
}
if(value === undefined || value === null) {
return false;
}
return value.toString().toLowerCase().indexOf(filter) !== -1;
}
},
_initStickyHeader: function() {
var table = this.thead.parent(),
offset = table.offset(),
win = $(window),
$this = this,
stickyNS = 'scroll.' + this.id,
resizeNS = 'resize.sticky-' + this.id;
this.cloneContainer = $('<div class="pui-datatable pui-datatable-sticky ui-widget"><table></table></div>');
this.clone = this.thead.clone(true);
this.cloneContainer.children('table').append(this.clone);
this.cloneContainer.css({
position: 'absolute',
width: table.outerWidth(),
top: offset.top,
left: offset.left,
'z-index': ++PUI.zindex
})
.appendTo(this.element);
win.off(stickyNS).on(stickyNS, function() {
var scrollTop = win.scrollTop(),
tableOffset = table.offset();
if(scrollTop > tableOffset.top) {
$this.cloneContainer.css({
'position': 'fixed',
'top': '0px'
})
.addClass('pui-shadow pui-sticky');
if(scrollTop >= (tableOffset.top + $this.tbody.height()))
$this.cloneContainer.hide();
else
$this.cloneContainer.show();
}
else {
$this.cloneContainer.css({
'position': 'absolute',
'top': tableOffset.top
})
.removeClass('pui-shadow pui-sticky');
}
})
.off(resizeNS).on(resizeNS, function() {
$this.cloneContainer.width(table.outerWidth());
});
//filter support
this.thead.find('.pui-column-filter').prop('disabled', true);
},
_initEditing: function() {
var cellSelector = '> tr > td.pui-editable-column',
$this = this;
this.tbody.off('click', cellSelector)
.on('click', cellSelector, null, function(e) {
var cell = $(this);
if(!cell.hasClass('pui-cell-editing')) {
$this._showCellEditor(cell);
e.stopPropagation();
}
});
},
_showCellEditor: function(cell) {
var editor = this.editors[cell.data('editor')].call(),
$this = this;
editor.val(cell.data('rowdata')[cell.data('field')]);
cell.addClass('pui-cell-editing').html('').append(editor);
editor.focus().on('change', function() {
$this._onCellEditorChange(cell);
})
.on('blur', function() {
$this._onCellEditorBlur(cell);
})
.on('keydown', function(e) {
var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) {
$(this).trigger('change').trigger('blur');
e.preventDefault();
}
else if(key === keyCode.TAB) {
if(e.shiftKey) {
var prevCell = cell.prevAll('td.pui-editable-column').eq(0);
if(!prevCell.length) {
prevCell = cell.parent().prev('tr').children('td.pui-editable-column:last');
}
if(prevCell.length) {
$this._showCellEditor(prevCell);
}
}
else {
var nextCell = cell.nextAll('td.pui-editable-column').eq(0);
if(!nextCell.length) {
nextCell = cell.parent().next('tr').children('td.pui-editable-column').eq(0);
}
if(nextCell.length) {
$this._showCellEditor(nextCell);
}
}
e.preventDefault();
} else if(key === keyCode.ESCAPE) {
$this._onCellEditorBlur(cell);
}
});
},
_onCellEditorChange: function(cell) {
var newCellValue = cell.children('.pui-cell-editor').val();
var retVal = this._trigger('cellEdit', null, {
oldValue: cell.data('rowdata')[cell.data('field')],
newValue: newCellValue,
data: cell.data('rowdata'),
field: cell.data('field')
});
if(retVal !== false) {
cell.data('rowdata')[cell.data('field')] = newCellValue;
}
},
_onCellEditorBlur: function(cell) {
cell.removeClass('pui-cell-editing').text(cell.data('rowdata')[cell.data('field')])
.children('.pui-cell-editor').remove();
},
editors: {
'input': function() {
return $('<input type="text" class="pui-cell-editor"/>');
}
}
});
})();
/**
* PrimeUI Datagrid Widget
*/
(function() {
$.widget("primeui.puidatagrid", {
options: {
columns: 3,
datasource: null,
paginator: null,
header: null,
footer: null,
content: null,
lazy: false,
template: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.addClass('pui-datagrid ui-widget');
//header
if(this.options.header) {
this.element.append('<div class="pui-datagrid-header ui-widget-header ui-corner-top">' + this.options.header + '</div>');
}
//content
this.content = $('<div class="pui-datagrid-content ui-widget-content pui-grid pui-grid-responsive"></div>').appendTo(this.element);
//footer
if(this.options.footer) {
this.element.append('<div class="pui-datagrid-footer ui-widget-header ui-corner-top">' + this.options.footer + '</div>');
}
//data
if(this.options.datasource) {
this._initDatasource();
}
},
_onDataInit: function(data) {
this._onDataUpdate(data);
this._initPaginator();
},
_onDataUpdate: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this.reset();
this._renderData();
},
_onLazyLoad: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this._renderData();
},
reset: function() {
if(this.paginator) {
this.paginator.puipaginator('setState', {
page: 0,
totalRecords: this.options.lazy ? this.options.paginator.totalRecords : this.data.length
});
}
},
paginate: function() {
if(this.options.lazy) {
this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta());
}
else {
this._renderData();
}
},
_renderData: function() {
if(this.data) {
this.content.html('');
var firstNonLazy = this._getFirst(),
first = this.options.lazy ? 0 : firstNonLazy,
rows = this._getRows(),
gridRow = null;
for(var i = first; i < (first + rows); i++) {
var dataValue = this.data[i];
if(dataValue) {
if(i % this.options.columns === 0) {
gridRow = $('<div class="pui-grid-row"></div>').appendTo(this.content);
}
var gridColumn = $('<div class="pui-datagrid-column ' + PUI.getGridColumn(this.options.columns) + '"></div>').appendTo(gridRow),
markup = this._createItemContent(dataValue);
gridColumn.append(markup);
}
}
}
},
_getFirst: function() {
if(this.paginator) {
var page = this.paginator.puipaginator('option', 'page'),
rows = this.paginator.puipaginator('option', 'rows');
return (page * rows);
}
else {
return 0;
}
},
_getRows: function() {
if(this.options.paginator)
return this.paginator ? this.paginator.puipaginator('option', 'rows') : this.options.paginator.rows;
else
return this.data ? this.data.length : 0;
},
_createStateMeta: function() {
var state = {
first: this._getFirst(),
rows: this._getRows()
};
return state;
},
_initPaginator: function() {
var $this = this;
if(this.options.paginator) {
this.options.paginator.paginate = function(event, state) {
$this.paginate();
};
this.options.paginator.totalRecords = this.options.lazy ? this.options.paginator.totalRecords : this.data.length;
this.paginator = $('<div></div>').insertAfter(this.content).puipaginator(this.options.paginator);
}
},
_initDatasource: function() {
if($.isArray(this.options.datasource)) {
this._onDataInit(this.options.datasource);
}
else {
if($.type(this.options.datasource) === 'string') {
var $this = this,
dataURL = this.options.datasource;
this.options.datasource = function() {
$.ajax({
type: 'GET',
url: dataURL,
dataType: "json",
context: $this,
success: function (response) {
this._onDataInit(response);
}
});
};
}
if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onDataInit, {first:0, rows: this._getRows()});
else
this.options.datasource.call(this, this._onDataInit);
}
}
},
_updateDatasource: function(datasource) {
this.options.datasource = datasource;
if($.isArray(this.options.datasource)) {
this._onDataUpdate(this.options.datasource);
}
else if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onDataUpdate, {first:0, rows: this._getRows()});
else
this.options.datasource.call(this, this._onDataUpdate);
}
},
_setOption: function(key, value) {
if(key === 'datasource') {
this._updateDatasource(value);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_createItemContent: function(obj) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, obj);
}
else {
return this.options.content.call(this, obj);
}
}
});
})();/**
* PrimeUI Datascroller Widget
*/
(function() {
$.widget("primeui.puidatascroller", {
options: {
header: null,
buffer: 0.9,
chunkSize: 10,
datasource: null,
lazy: false,
content: null,
template: null,
mode: 'document',
loader: null,
scrollHeight: null,
totalSize: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.addClass('pui-datascroller ui-widget');
if(this.options.header) {
this.header = this.element.append('<div class="pui-datascroller-header ui-widget-header ui-corner-top">' + this.options.header + '</div>').children('.pui-datascroller-header');
}
this.content = this.element.append('<div class="pui-datascroller-content ui-widget-content ui-corner-bottom"></div>').children('.pui-datascroller-content');
this.list = this.content.append('<ul class="pui-datascroller-list"></ul>').children('.pui-datascroller-list');
this.loaderContainer = this.content.append('<div class="pui-datascroller-loader"></div>').children('.pui-datascroller-loader');
this.loadStatus = $('<div class="pui-datascroller-loading"></div>');
this.loading = false;
this.allLoaded = false;
this.offset = 0;
if(this.options.mode === 'self') {
this.element.addClass('pui-datascroller-inline');
if(this.options.scrollHeight) {
this.content.css('height', this.options.scrollHeight);
}
}
if(this.options.loader) {
this.bindManualLoader();
}
else {
this.bindScrollListener();
}
if(this.options.datasource) {
if($.isArray(this.options.datasource)) {
this._onDataInit(this.options.datasource);
}
else {
if($.type(this.options.datasource) === 'string') {
var $this = this,
dataURL = this.options.datasource;
this.options.datasource = function() {
$.ajax({
type: 'GET',
url: dataURL,
dataType: "json",
context: $this,
success: function (response) {
this._onDataInit(response);
}
});
};
}
if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onLazyLoad, {first:this.offset});
else
this.options.datasource.call(this, this._onDataInit);
}
}
}
},
_onDataInit: function(data) {
this.data = data||[];
this.options.totalSize = this.data.length;
this._load();
},
_onLazyLoad: function(data) {
this._renderData(data, 0, this.options.chunkSize);
this._onloadComplete();
},
bindScrollListener: function() {
var $this = this;
if(this.options.mode === 'document') {
var win = $(window),
doc = $(document),
$this = this,
NS = 'scroll.' + this.id;
win.off(NS).on(NS, function () {
if(win.scrollTop() >= ((doc.height() * $this.options.buffer) - win.height()) && $this.shouldLoad()) {
$this._load();
}
});
}
else {
this.content.on('scroll', function () {
var scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
viewportHeight = this.clientHeight;
if((scrollTop >= ((scrollHeight * $this.options.buffer) - (viewportHeight))) && $this.shouldLoad()) {
$this._load();
}
});
}
},
bindManualLoader: function() {
var $this = this;
this.options.loader.on('click.dataScroller', function(e) {
$this._load();
e.preventDefault();
});
},
_load: function() {
this.loading = true;
this.loadStatus.appendTo(this.loaderContainer);
if(this.options.loader) {
this.options.loader.hide();
}
if(this.options.lazy) {
this.options.datasource.call(this, this._onLazyLoad, {first: this.offset});
}
else {
this._renderData(this.data, this.offset, (this.offset + this.options.chunkSize));
this._onloadComplete();
}
},
_renderData: function(data, start, end) {
if(data && data.length) {
for(var i = start; i < end; i++) {
var listItem = $('<li class="pui-datascroller-item"></li>'),
content = this._createItemContent(data[i]);
listItem.append(content);
this.list.append(listItem);
}
}
},
shouldLoad: function() {
return (!this.loading && !this.allLoaded);
},
_createItemContent: function(obj) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, obj);
}
else {
return this.options.content.call(this, obj);
}
},
_onloadComplete: function() {
this.offset += this.options.chunkSize;
this.loading = false;
this.allLoaded = this.offset >= this.options.totalSize;
this.loadStatus.remove();
if(this.options.loader && !this.allLoaded) {
this.options.loader.show();
}
}
});
})();/**
* PrimeUI Dialog Widget
*/
(function() {
$.widget("primeui.puidialog", {
options: {
draggable: true,
resizable: true,
location: 'center',
minWidth: 150,
minHeight: 25,
height: 'auto',
width: '300px',
visible: false,
modal: false,
showEffect: null,
hideEffect: null,
effectOptions: {},
effectSpeed: 'normal',
closeOnEscape: true,
rtl: false,
closable: true,
minimizable: false,
maximizable: false,
appendTo: null,
buttons: null,
responsive: false,
title: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
//container
this.element.addClass('pui-dialog ui-widget ui-widget-content ui-helper-hidden ui-corner-all pui-shadow')
.contents().wrapAll('<div class="pui-dialog-content ui-widget-content" />');
//header
var title = this.options.title||this.element.attr('title');
this.element.prepend('<div class="pui-dialog-titlebar ui-widget-header ui-helper-clearfix ui-corner-top">' +
'<span id="' + this.element.attr('id') + '_label" class="pui-dialog-title">' + title + '</span>')
.removeAttr('title');
//footer
if(this.options.buttons) {
this.footer = $('<div class="pui-dialog-buttonpane ui-widget-content ui-helper-clearfix"></div>').appendTo(this.element);
for(var i = 0; i < this.options.buttons.length; i++) {
var buttonMeta = this.options.buttons[i],
button = $('<button type="button"></button>').appendTo(this.footer);
if(buttonMeta.text) {
button.text(buttonMeta.text);
}
button.puibutton(buttonMeta);
}
}
if(this.options.rtl) {
this.element.addClass('pui-dialog-rtl');
}
//elements
this.content = this.element.children('.pui-dialog-content');
this.titlebar = this.element.children('.pui-dialog-titlebar');
if(this.options.closable) {
this._renderHeaderIcon('pui-dialog-titlebar-close', 'fa-close');
}
if(this.options.maximizable) {
this._renderHeaderIcon('pui-dialog-titlebar-maximize', 'fa-sort');
}
if(this.options.minimizable) {
this._renderHeaderIcon('pui-dialog-titlebar-minimize', 'fa-minus');
}
//icons
this.icons = this.titlebar.children('.pui-dialog-titlebar-icon');
this.closeIcon = this.titlebar.children('.pui-dialog-titlebar-close');
this.minimizeIcon = this.titlebar.children('.pui-dialog-titlebar-minimize');
this.maximizeIcon = this.titlebar.children('.pui-dialog-titlebar-maximize');
this.blockEvents = 'focus.puidialog mousedown.puidialog mouseup.puidialog keydown.puidialog keyup.puidialog';
this.parent = this.element.parent();
//size
this.element.css({'width': this.options.width, 'height': 'auto'});
this.content.height(this.options.height);
//events
this._bindEvents();
if(this.options.draggable) {
this._setupDraggable();
}
if(this.options.resizable) {
this._setupResizable();
}
if(this.options.appendTo) {
this.element.appendTo(this.options.appendTo);
}
if(this.options.responsive) {
this.resizeNS = 'resize.' + this.id;
}
//docking zone
if($(document.body).children('.pui-dialog-docking-zone').length === 0) {
$(document.body).append('<div class="pui-dialog-docking-zone"></div>');
}
//aria
this._applyARIA();
if(this.options.visible) {
this.show();
}
},
_renderHeaderIcon: function(styleClass, icon) {
this.titlebar.append('<a class="pui-dialog-titlebar-icon ' + styleClass + ' ui-corner-all" href="#" role="button">' +
'<span class="pui-icon fa fa-fw ' + icon + '"></span></a>');
},
_enableModality: function() {
var $this = this,
doc = $(document);
this.modality = $('<div id="' + this.element.attr('id') + '_modal" class="ui-widget-overlay pui-dialog-mask"></div>').appendTo(document.body)
.css('z-index', this.element.css('z-index') - 1);
//Disable tabbing out of modal dialog and stop events from targets outside of dialog
doc.bind('keydown.puidialog',
function(event) {
if(event.keyCode == $.ui.keyCode.TAB) {
var tabbables = $this.content.find(':tabbable'),
first = tabbables.filter(':first'),
last = tabbables.filter(':last');
if(event.target === last[0] && !event.shiftKey) {
first.focus(1);
return false;
}
else if (event.target === first[0] && event.shiftKey) {
last.focus(1);
return false;
}
}
})
.bind(this.blockEvents, function(event) {
if ($(event.target).zIndex() < $this.element.zIndex()) {
return false;
}
});
},
_disableModality: function(){
this.modality.remove();
this.modality = null;
$(document).unbind(this.blockEvents).unbind('keydown.dialog');
},
show: function() {
if(this.element.is(':visible')) {
return;
}
if(!this.positionInitialized) {
this._initPosition();
}
this._trigger('beforeShow', null);
if(this.options.showEffect) {
var $this = this;
this.element.show(this.options.showEffect, this.options.effectOptions, this.options.effectSpeed, function() {
$this._postShow();
});
}
else {
this.element.show();
this._postShow();
}
this._moveToTop();
if(this.options.modal) {
this._enableModality();
}
},
_postShow: function() {
//execute user defined callback
this._trigger('afterShow', null);
this.element.attr({
'aria-hidden': false,
'aria-live': 'polite'
});
this._applyFocus();
if(this.options.responsive) {
this._bindResizeListener();
}
},
hide: function() {
if(this.element.is(':hidden')) {
return;
}
this._trigger('beforeHide', null);
if(this.options.hideEffect) {
var _self = this;
this.element.hide(this.options.hideEffect, this.options.effectOptions, this.options.effectSpeed, function() {
_self._postHide();
});
}
else {
this.element.hide();
this._postHide();
}
if(this.options.modal) {
this._disableModality();
}
},
_postHide: function() {
//execute user defined callback
this._trigger('afterHide', null);
this.element.attr({
'aria-hidden': true,
'aria-live': 'off'
});
if(this.options.responsive) {
this._unbindResizeListener();
}
},
_applyFocus: function() {
this.element.find(':not(:submit):not(:button):input:visible:enabled:first').focus();
},
_bindEvents: function() {
var $this = this;
this.element.mousedown(function(e) {
if(!$(e.target).data('ui-widget-overlay')) {
$this._moveToTop();
}
});
this.icons.mouseover(function() {
$(this).addClass('ui-state-hover');
}).mouseout(function() {
$(this).removeClass('ui-state-hover');
});
this.closeIcon.on('click.puidialog', function(e) {
$this.hide();
e.preventDefault();
});
this.maximizeIcon.click(function(e) {
$this.toggleMaximize();
e.preventDefault();
});
this.minimizeIcon.click(function(e) {
$this.toggleMinimize();
e.preventDefault();
});
if(this.options.closeOnEscape) {
$(document).on('keydown.dialog_' + this.element.attr('id'), function(e) {
var keyCode = $.ui.keyCode,
active = parseInt($this.element.css('z-index'), 10) === PUI.zindex;
if(e.which === keyCode.ESCAPE && $this.element.is(':visible') && active) {
$this.hide();
}
});
}
},
_setupDraggable: function() {
this.element.draggable({
cancel: '.pui-dialog-content, .pui-dialog-titlebar-close',
handle: '.pui-dialog-titlebar',
containment : 'document'
});
},
_setupResizable: function() {
var $this = this;
this.element.resizable({
minWidth : this.options.minWidth,
minHeight : this.options.minHeight,
alsoResize : this.content,
containment: 'document',
start: function(event, ui) {
$this.element.data('offset', $this.element.offset());
},
stop: function(event, ui) {
var offset = $this.element.data('offset');
$this.element.css('position', 'fixed');
$this.element.offset(offset);
}
});
this.resizers = this.element.children('.ui-resizable-handle');
},
_initPosition: function() {
//reset
this.element.css({left:0,top:0});
if(/(center|left|top|right|bottom)/.test(this.options.location)) {
this.options.location = this.options.location.replace(',', ' ');
this.element.position({
my: 'center',
at: this.options.location,
collision: 'fit',
of: window,
//make sure dialog stays in viewport
using: function(pos) {
var l = pos.left < 0 ? 0 : pos.left,
t = pos.top < 0 ? 0 : pos.top;
$(this).css({
left: l,
top: t
});
}
});
}
else {
var coords = this.options.position.split(','),
x = $.trim(coords[0]),
y = $.trim(coords[1]);
this.element.offset({
left: x,
top: y
});
}
this.positionInitialized = true;
},
_moveToTop: function() {
this.element.css('z-index',++PUI.zindex);
},
toggleMaximize: function() {
if(this.minimized) {
this.toggleMinimize();
}
if(this.maximized) {
this.element.removeClass('pui-dialog-maximized');
this._restoreState();
this.maximizeIcon.removeClass('ui-state-hover');//.children('.ui-icon').removeClass('ui-icon-newwin').addClass('ui-icon-extlink');
this.maximized = false;
}
else {
this._saveState();
var win = $(window);
this.element.addClass('pui-dialog-maximized').css({
'width': win.width() - 6,
'height': win.height()
}).offset({
top: win.scrollTop(),
left: win.scrollLeft()
});
//maximize content
this.content.css({
width: 'auto',
height: 'auto'
});
this.maximizeIcon.removeClass('ui-state-hover');//.children('.ui-icon').removeClass('ui-icon-extlink').addClass('ui-icon-newwin');
this.maximized = true;
this._trigger('maximize');
}
},
toggleMinimize: function() {
var animate = true,
dockingZone = $(document.body).children('.pui-dialog-docking-zone');
if(this.maximized) {
this.toggleMaximize();
animate = false;
}
var $this = this;
if(this.minimized) {
this.element.appendTo(this.parent).removeClass('pui-dialog-minimized').css({'position':'fixed', 'float':'none'});
this._restoreState();
this.content.show();
this.minimizeIcon.removeClass('ui-state-hover');//.children('.ui-icon').removeClass('ui-icon-plus').addClass('ui-icon-minus');
this.minimized = false;
if(this.options.resizable) {
this.resizers.show();
}
if(this.footer) {
this.footer.show();
}
}
else {
this._saveState();
if(animate) {
this.element.effect('transfer', {
to: dockingZone,
className: 'pui-dialog-minimizing'
}, 500,
function() {
$this._dock(dockingZone);
$this.element.addClass('pui-dialog-minimized');
});
}
else {
this._dock(dockingZone);
}
}
},
_dock: function(zone) {
this.element.appendTo(zone).css('position', 'static');
this.element.css({'height':'auto', 'width':'auto', 'float': 'left'});
this.content.hide();
this.minimizeIcon.removeClass('ui-state-hover').children('.ui-icon').removeClass('ui-icon-minus').addClass('ui-icon-plus');
this.minimized = true;
if(this.options.resizable) {
this.resizers.hide();
}
if(this.footer) {
this.footer.hide();
}
zone.css('z-index',++PUI.zindex);
this._trigger('minimize');
},
_saveState: function() {
this.state = {
width: this.element.width(),
height: this.element.height()
};
var win = $(window);
this.state.offset = this.element.offset();
this.state.windowScrollLeft = win.scrollLeft();
this.state.windowScrollTop = win.scrollTop();
},
_restoreState: function() {
this.element.width(this.state.width).height(this.state.height);
var win = $(window);
this.element.offset({
top: this.state.offset.top + (win.scrollTop() - this.state.windowScrollTop),
left: this.state.offset.left + (win.scrollLeft() - this.state.windowScrollLeft)
});
},
_applyARIA: function() {
this.element.attr({
'role': 'dialog',
'aria-labelledby': this.element.attr('id') + '_title',
'aria-hidden': !this.options.visible
});
this.titlebar.children('a.pui-dialog-titlebar-icon').attr('role', 'button');
},
_bindResizeListener: function() {
var $this = this;
$(window).on(this.resizeNS, function(e) {
if(e.target === window) {
$this._initPosition();
}
});
},
_unbindResizeListener: function() {
$(window).off(this.resizeNS);
}
});
})();/**
* PrimeUI dropdown widget
*/
(function() {
$.widget("primeui.puidropdown", {
options: {
effect: 'fade',
effectSpeed: 'normal',
filter: false,
filterMatchMode: 'startsWith',
caseSensitiveFilter: false,
filterFunction: null,
data: null,
content: null,
scrollHeight: 200,
appendTo: 'body',
editable:false
},
_create: function() {
if(this.options.data) {
for(var i = 0; i < this.options.data.length; i++) {
var choice = this.options.data[i];
if(choice.label)
this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>');
else
this.element.append('<option value="' + choice + '">' + choice + '</option>');
}
}
this.element.wrap('<div class="pui-dropdown ui-widget ui-state-default ui-corner-all ui-helper-clearfix" />')
.wrap('<div class="ui-helper-hidden-accessible" />');
this.container = this.element.closest('.pui-dropdown');
this.focusElementContainer = $('<div class="ui-helper-hidden-accessible"><input type="text" /></div>').appendTo(this.container);
this.focusElement = this.focusElementContainer.children('input');
this.label = this.options.editable ? $('<input type="text" class="pui-dropdown-label pui-inputtext ui-corner-all"">')
: $('<label class="pui-dropdown-label pui-inputtext ui-corner-all"/>');
this.label.appendTo(this.container);
this.menuIcon = $('<div class="pui-dropdown-trigger ui-state-default ui-corner-right"><span class="pui-icon fa fa-fw fa-caret-down"></span></div>')
.appendTo(this.container);
//panel
this.panel = $('<div class="pui-dropdown-panel ui-widget-content ui-corner-all ui-helper-hidden pui-shadow" />');
if(this.options.appendTo === 'self')
this.panel.appendTo(this.container);
else
this.panel.appendTo(this.options.appendTo);
this.itemsWrapper = $('<div class="pui-dropdown-items-wrapper" />').appendTo(this.panel);
this.itemsContainer = $('<ul class="pui-dropdown-items pui-dropdown-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>')
.appendTo(this.itemsWrapper);
this.disabled = this.element.prop('disabled');
this.choices = this.element.children('option');
this.optGroupsSize = this.itemsContainer.children('li.puiselectonemenu-item-group').length;
if(this.options.filter) {
this.filterContainer = $('<div class="pui-dropdown-filter-container" />').prependTo(this.panel);
this.filterInput = $('<input type="text" autocomplete="off" class="pui-dropdown-filter pui-inputtext ui-widget ui-state-default ui-corner-all" />')
.appendTo(this.filterContainer);
this.filterContainer.append('<span class="pui-icon fa fa-search"></span>');
}
this._generateItems();
if(this.options.scrollHeight && this.panel.outerHeight() > this.options.scrollHeight) {
this.itemsWrapper.height(this.options.scrollHeight);
}
var $this = this,
selectedOption = this.choices.filter(':selected');
//disable options
this.choices.filter(':disabled').each(function() {
$this.items.eq($(this).index()).addClass('ui-state-disabled');
});
//triggers
this.triggers = this.options.editable ? this.menuIcon : this.container.children('.pui-dropdown-trigger, .pui-dropdown-label');
//activate selected
if(this.options.editable) {
var customInputVal = this.label.val();
//predefined input
if(customInputVal === selectedOption.text()) {
this._highlightItem(this.items.eq(selectedOption.index()));
}
//custom input
else {
this.items.eq(0).addClass('ui-state-highlight');
this.customInput = true;
this.customInputVal = customInputVal;
}
}
else {
this._highlightItem(this.items.eq(selectedOption.index()));
}
if(!this.disabled) {
this._bindEvents();
this._bindConstantEvents();
}
},
_generateItems: function() {
for(var i = 0; i < this.choices.length; i++) {
var option = this.choices.eq(i),
optionLabel = option.text(),
content = this.options.content ? this.options.content.call(this, this.options.data[i]) : optionLabel;
this.itemsContainer.append('<li data-label="' + optionLabel + '" class="pui-dropdown-item pui-dropdown-list-item ui-corner-all">' + content + '</li>');
}
this.items = this.itemsContainer.children('.pui-dropdown-item');
},
_bindEvents: function() {
var $this = this;
this.items.filter(':not(.ui-state-disabled)').each(function(i, item) {
$this._bindItemEvents($(item));
});
this.triggers.on('mouseenter.puidropdown', function() {
if(!$this.container.hasClass('ui-state-focus')) {
$this.container.addClass('ui-state-hover');
$this.menuIcon.addClass('ui-state-hover');
}
})
.on('mouseleave.puidropdown', function() {
$this.container.removeClass('ui-state-hover');
$this.menuIcon.removeClass('ui-state-hover');
})
.on('click.puidropdown', function(e) {
if($this.panel.is(":hidden")) {
$this._show();
}
else {
$this._hide();
$this._revert();
}
$this.container.removeClass('ui-state-hover');
$this.menuIcon.removeClass('ui-state-hover');
$this.focusElement.trigger('focus.puidropdown');
e.preventDefault();
});
this.focusElement.on('focus.puidropdown', function() {
$this.container.addClass('ui-state-focus');
$this.menuIcon.addClass('ui-state-focus');
})
.on('blur.puidropdown', function() {
$this.container.removeClass('ui-state-focus');
$this.menuIcon.removeClass('ui-state-focus');
});
if(this.options.editable) {
this.label.on('change.pui-dropdown', function() {
$this._triggerChange(true);
$this.customInput = true;
$this.customInputVal = $(this).val();
$this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight');
$this.items.eq(0).addClass('ui-state-highlight');
});
}
this._bindKeyEvents();
if(this.options.filter) {
this._setupFilterMatcher();
this.filterInput.puiinputtext();
this.filterInput.on('keyup.pui-dropdown', function() {
$this._filter($(this).val());
});
}
},
_bindItemEvents: function(item) {
var $this = this;
item.on('mouseover.puidropdown', function() {
var el = $(this);
if(!el.hasClass('ui-state-highlight'))
$(this).addClass('ui-state-hover');
})
.on('mouseout.puidropdown', function() {
$(this).removeClass('ui-state-hover');
})
.on('click.puidropdown', function() {
$this._selectItem($(this));
});
},
_bindConstantEvents: function() {
var $this = this;
$(document.body).bind('mousedown.pui-dropdown', function (e) {
if($this.panel.is(":hidden")) {
return;
}
var offset = $this.panel.offset();
if (e.target === $this.label.get(0) ||
e.target === $this.menuIcon.get(0) ||
e.target === $this.menuIcon.children().get(0)) {
return;
}
if (e.pageX < offset.left ||
e.pageX > offset.left + $this.panel.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.panel.height()) {
$this._hide();
$this._revert();
}
});
this.resizeNS = 'resize.' + this.id;
this._unbindResize();
this._bindResize();
},
_bindKeyEvents: function() {
var $this = this;
this.focusElement.on('keydown.puiselectonemenu', function(e) {
var keyCode = $.ui.keyCode,
key = e.which,
activeItem;
switch(key) {
case keyCode.UP:
case keyCode.LEFT:
activeItem = $this._getActiveItem();
var prev = activeItem.prevAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):first');
if(prev.length == 1) {
if($this.panel.is(':hidden')) {
$this._selectItem(prev);
}
else {
$this._highlightItem(prev);
PUI.scrollInView($this.itemsWrapper, prev);
}
}
e.preventDefault();
break;
case keyCode.DOWN:
case keyCode.RIGHT:
activeItem = $this._getActiveItem();
var next = activeItem.nextAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):first');
if(next.length == 1) {
if($this.panel.is(':hidden')) {
if(e.altKey) {
$this._show();
} else {
$this._selectItem(next);
}
}
else {
$this._highlightItem(next);
PUI.scrollInView($this.itemsWrapper, next);
}
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
if($this.panel.is(':hidden')) {
$this._show();
}
else {
$this._selectItem($this._getActiveItem());
}
e.preventDefault();
break;
case keyCode.TAB:
if($this.panel.is(':visible')) {
$this._revert();
$this._hide();
}
break;
case keyCode.ESCAPE:
if($this.panel.is(':visible')) {
$this._revert();
$this._hide();
}
break;
default:
var k = String.fromCharCode((96 <= key && key <= 105)? key-48 : key),
currentItem = $this.items.filter('.ui-state-highlight');
//Search items forward from current to end and on no result, search from start until current
var highlightItem = $this._search(k, currentItem.index() + 1, $this.options.length);
if(!highlightItem) {
highlightItem = $this._search(k, 0, currentItem.index());
}
if(highlightItem) {
if($this.panel.is(':hidden')) {
$this._selectItem(highlightItem);
}
else {
$this._highlightItem(highlightItem);
PUI.scrollInView($this.itemsWrapper, highlightItem);
}
}
break;
}
});
},
_selectItem: function(item, silent) {
var selectedOption = this.choices.eq(this._resolveItemIndex(item)),
currentOption = this.choices.filter(':selected'),
sameOption = selectedOption.val() == currentOption.val(),
shouldChange = null;
if(this.options.editable) {
shouldChange = (!sameOption)||(selectedOption.text() != this.label.val());
}
else {
shouldChange = !sameOption;
}
if(shouldChange) {
this._highlightItem(item);
this.element.val(selectedOption.val());
this._triggerChange();
if(this.options.editable) {
this.customInput = false;
}
}
if(!silent) {
this.focusElement.trigger('focus.puidropdown');
}
if(this.panel.is(':visible')) {
this._hide();
}
},
_highlightItem: function(item) {
this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight');
item.addClass('ui-state-highlight');
this._setLabel(item.data('label'));
},
_triggerChange: function(edited) {
this.changed = false;
if(this.options.change) {
this._trigger('change');
}
if(!edited) {
this.value = this.choices.filter(':selected').val();
}
},
_resolveItemIndex: function(item) {
if(this.optGroupsSize === 0) {
return item.index();
}
else {
return item.index() - item.prevAll('li.pui-dropdown-item-group').length;
}
},
_setLabel: function(value) {
if(this.options.editable) {
this.label.val(value);
}
else {
if(value === ' ') {
this.label.html(' ');
}
else {
this.label.text(value);
}
}
},
_bindResize: function() {
var $this = this;
$(window).bind(this.resizeNS, function(e) {
if($this.panel.is(':visible')) {
$this._alignPanel();
}
});
},
_unbindResize: function() {
$(window).unbind(this.resizeNS);
},
_unbindEvents: function() {
this.items.off();
this.triggers.off();
this.label.off();
},
_alignPanelWidth: function() {
if(!this.panelWidthAdjusted) {
var jqWidth = this.container.outerWidth();
if(this.panel.outerWidth() < jqWidth) {
this.panel.width(jqWidth);
}
this.panelWidthAdjusted = true;
}
},
_alignPanel: function() {
if(this.panel.parent().is(this.container)) {
this.panel.css({
left: '0px',
top: this.container.outerHeight() + 'px'
})
.width(this.container.outerWidth());
}
else {
this._alignPanelWidth();
this.panel.css({left:'', top:''}).position({
my: 'left top',
at: 'left bottom',
of: this.container,
collision: 'flipfit'
});
}
},
_show: function() {
this._alignPanel();
this.panel.css('z-index', ++PUI.zindex);
if(this.options.effect !== 'none') {
this.panel.show(this.options.effect, {}, this.options.effectSpeed);
}
else {
this.panel.show();
}
this.preShowValue = this.choices.filter(':selected');
},
_hide: function() {
this.panel.hide();
},
_revert: function() {
if(this.options.editable && this.customInput) {
this._setLabel(this.customInputVal);
this.items.filter('.ui-state-active').removeClass('ui-state-active');
this.items.eq(0).addClass('ui-state-active');
}
else {
this._highlightItem(this.items.eq(this.preShowValue.index()));
}
},
_getActiveItem: function() {
return this.items.filter('.ui-state-highlight');
},
_setupFilterMatcher: function() {
this.filterMatchers = {
'startsWith': this._startsWithFilter,
'contains': this._containsFilter,
'endsWith': this._endsWithFilter,
'custom': this.options.filterFunction
};
this.filterMatcher = this.filterMatchers[this.options.filterMatchMode];
},
_startsWithFilter: function(value, filter) {
return value.indexOf(filter) === 0;
},
_containsFilter: function(value, filter) {
return value.indexOf(filter) !== -1;
},
_endsWithFilter: function(value, filter) {
return value.indexOf(filter, value.length - filter.length) !== -1;
},
_filter: function(value) {
this.initialHeight = this.initialHeight||this.itemsWrapper.height();
var filterValue = this.options.caseSensitiveFilter ? $.trim(value) : $.trim(value).toLowerCase();
if(filterValue === '') {
this.items.filter(':hidden').show();
}
else {
for(var i = 0; i < this.choices.length; i++) {
var option = this.choices.eq(i),
itemLabel = this.options.caseSensitiveFilter ? option.text() : option.text().toLowerCase(),
item = this.items.eq(i);
if(this.filterMatcher(itemLabel, filterValue))
item.show();
else
item.hide();
}
}
if(this.itemsContainer.height() < this.initialHeight) {
this.itemsWrapper.css('height', 'auto');
}
else {
this.itemsWrapper.height(this.initialHeight);
}
},
_search: function(text, start, end) {
for(var i = start; i < end; i++) {
var option = this.choices.eq(i);
if(option.text().indexOf(text) === 0) {
return this.items.eq(i);
}
}
return null;
},
getSelectedValue: function() {
return this.element.val();
},
getSelectedLabel: function() {
return this.choices.filter(':selected').text();
},
selectValue : function(value) {
var option = this.choices.filter('[value="' + value + '"]');
this._selectItem(this.items.eq(option.index()), true);
},
addOption: function(option) {
var value = (option.value !== undefined || option.value !== null) ? option.value : option,
label = (option.label !== undefined || option.label !== null) ? option.label : option,
content = this.options.content ? this.options.content.call(this, option) : label,
item = $('<li data-label="' + label + '" class="pui-dropdown-item pui-dropdown-list-item ui-corner-all">' + content + '</li>'),
optionElement = $('<option value="' + value + '">' + label + '</option>');
optionElement.appendTo(this.element);
this._bindItemEvents(item);
item.appendTo(this.itemsContainer);
this.items.push(item[0]);
//this.choices.push(choice); There is an issue when this form is used when selecting an option.
this.choices = this.element.children('option');
// If this is the first option, it is the default selected one
if (this.items.length === 1) {
this.selectValue(value);
this._highlightItem(item);
}
},
removeAllOptions: function() {
this.element.empty();
this.itemsContainer.empty();
this.items.length = 0;
this.choices.length = 0;
this.element.val('');
this.label.text('');
},
_setOption: function (key, value) {
$.Widget.prototype._setOption.apply(this, arguments);
if (key === 'data') {
this.removeAllOptions();
for(var i = 0; i < this.options.data.length; i++) {
this.addOption(this.options.data[i]);
}
if(this.options.scrollHeight && this.panel.outerHeight() > this.options.scrollHeight) {
this.itemsWrapper.height(this.options.scrollHeight);
}
}
},
disable: function() {
this._unbindEvents();
this.label.addClass('ui-state-disabled');
this.menuIcon.addClass('ui-state-disabled');
},
enable: function() {
this._bindEvents();
this.label.removeClass('ui-state-disabled');
this.menuIcon.removeClass('ui-state-disabled');
},
getEditableText: function() {
return this.label.val();
}
});
})();/**
* PrimeFaces Fieldset Widget
*/
(function() {
$.widget("primeui.puifieldset", {
options: {
toggleable: false,
toggleDuration: 'normal',
collapsed: false
},
_create: function() {
this.element.addClass('pui-fieldset ui-widget ui-widget-content ui-corner-all').
children('legend').addClass('pui-fieldset-legend ui-corner-all ui-state-default');
this.element.contents().wrapAll('<div class="pui-fieldset-content" />');
this.content = this.element.children('div.pui-fieldset-content');
this.legend = this.content.children('legend.pui-fieldset-legend');
this.legend.prependTo(this.element);
if(this.options.toggleable) {
this.element.addClass('pui-fieldset-toggleable');
this.toggler = $('<span class="pui-fieldset-toggler fa fa-fw" />').prependTo(this.legend);
this._bindEvents();
if(this.options.collapsed) {
this.content.hide();
this.toggler.addClass('fa-plus');
} else {
this.toggler.addClass('fa-minus');
}
}
},
_bindEvents: function() {
var $this = this;
this.legend.on('click.puifieldset', function(e) {$this.toggle(e);})
.on('mouseover.puifieldset', function() {$this.legend.addClass('ui-state-hover');})
.on('mouseout.puifieldset', function() {$this.legend.removeClass('ui-state-hover ui-state-active');})
.on('mousedown.puifieldset', function() {$this.legend.removeClass('ui-state-hover').addClass('ui-state-active');})
.on('mouseup.puifieldset', function() {$this.legend.removeClass('ui-state-active').addClass('ui-state-hover');});
},
toggle: function(e) {
var $this = this;
this._trigger('beforeToggle', e);
if(this.options.collapsed) {
this.toggler.removeClass('fa-plus').addClass('fa-minus');
}
else {
this.toggler.removeClass('fa-minus').addClass('fa-plus');
}
this.content.slideToggle(this.options.toggleSpeed, 'easeInOutCirc', function() {
$this._trigger('afterToggle', e);
$this.options.collapsed = !$this.options.collapsed;
});
}
});
})();/**
* PrimeUI Lightbox Widget
*/
(function() {
$.widget("primeui.puigalleria", {
options: {
panelWidth: 600,
panelHeight: 400,
frameWidth: 60,
frameHeight: 40,
activeIndex: 0,
showFilmstrip: true,
autoPlay: true,
transitionInterval: 4000,
effect: 'fade',
effectSpeed: 250,
effectOptions: {},
showCaption: true,
customContent: false
},
_create: function() {
this.element.addClass('pui-galleria ui-widget ui-widget-content ui-corner-all');
this.panelWrapper = this.element.children('ul');
this.panelWrapper.addClass('pui-galleria-panel-wrapper');
this.panels = this.panelWrapper.children('li');
this.panels.addClass('pui-galleria-panel ui-helper-hidden');
this.element.width(this.options.panelWidth);
this.panelWrapper.width(this.options.panelWidth).height(this.options.panelHeight);
this.panels.width(this.options.panelWidth).height(this.options.panelHeight);
if(this.options.showFilmstrip) {
this._renderStrip();
this._bindEvents();
}
if(this.options.customContent) {
this.panels.children('img').remove();
this.panels.children('div').addClass('pui-galleria-panel-content');
}
//show first
var activePanel = this.panels.eq(this.options.activeIndex);
activePanel.removeClass('ui-helper-hidden');
if(this.options.showCaption) {
this._showCaption(activePanel);
}
this.element.css('visibility', 'visible');
if(this.options.autoPlay) {
this.startSlideshow();
}
},
_renderStrip: function() {
var frameStyle = 'style="width:' + this.options.frameWidth + "px;height:" + this.options.frameHeight + 'px;"';
this.stripWrapper = $('<div class="pui-galleria-filmstrip-wrapper"></div>')
.width(this.element.width() - 50)
.height(this.options.frameHeight)
.appendTo(this.element);
this.strip = $('<ul class="pui-galleria-filmstrip"></div>').appendTo(this.stripWrapper);
for(var i = 0; i < this.panels.length; i++) {
var image = this.panels.eq(i).children('img'),
frameClass = (i == this.options.activeIndex) ? 'pui-galleria-frame pui-galleria-frame-active' : 'pui-galleria-frame',
frameMarkup = '<li class="'+ frameClass + '" ' + frameStyle + '>' +
'<div class="pui-galleria-frame-content" ' + frameStyle + '>' +
'<img src="' + image.attr('src') + '" class="pui-galleria-frame-image" ' + frameStyle + '/>' +
'</div></li>';
this.strip.append(frameMarkup);
}
this.frames = this.strip.children('li.pui-galleria-frame');
//navigators
this.element.append('<div class="pui-galleria-nav-prev fa fa-fw fa-chevron-circle-left" style="bottom:' + (this.options.frameHeight / 2) + 'px"></div>' +
'<div class="pui-galleria-nav-next fa fa-fw fa-chevron-circle-right" style="bottom:' + (this.options.frameHeight / 2) + 'px"></div>');
//caption
if(this.options.showCaption) {
this.caption = $('<div class="pui-galleria-caption"></div>').css({
'bottom': this.stripWrapper.outerHeight() + 10,
'width': this.panelWrapper.width()
}).appendTo(this.element);
}
},
_bindEvents: function() {
var $this = this;
this.element.children('div.pui-galleria-nav-prev').on('click.puigalleria', function() {
if($this.slideshowActive) {
$this.stopSlideshow();
}
if(!$this.isAnimating()) {
$this.prev();
}
});
this.element.children('div.pui-galleria-nav-next').on('click.puigalleria', function() {
if($this.slideshowActive) {
$this.stopSlideshow();
}
if(!$this.isAnimating()) {
$this.next();
}
});
this.strip.children('li.pui-galleria-frame').on('click.puigalleria', function() {
if($this.slideshowActive) {
$this.stopSlideshow();
}
$this.select($(this).index(), false);
});
},
startSlideshow: function() {
var $this = this;
this.interval = window.setInterval(function() {
$this.next();
}, this.options.transitionInterval);
this.slideshowActive = true;
},
stopSlideshow: function() {
window.clearInterval(this.interval);
this.slideshowActive = false;
},
isSlideshowActive: function() {
return this.slideshowActive;
},
select: function(index, reposition) {
if(index !== this.options.activeIndex) {
if(this.options.showCaption) {
this._hideCaption();
}
var oldPanel = this.panels.eq(this.options.activeIndex),
newPanel = this.panels.eq(index);
//content
oldPanel.hide(this.options.effect, this.options.effectOptions, this.options.effectSpeed);
newPanel.show(this.options.effect, this.options.effectOptions, this.options.effectSpeed);
if (this.options.showFilmstrip) {
var oldFrame = this.frames.eq(this.options.activeIndex),
newFrame = this.frames.eq(index);
//frame
oldFrame.removeClass('pui-galleria-frame-active').css('opacity', '');
newFrame.animate({opacity:1.0}, this.options.effectSpeed, null, function() {
$(this).addClass('pui-galleria-frame-active');
});
//viewport
if( (reposition === undefined || reposition === true) ) {
var frameLeft = newFrame.position().left,
stepFactor = this.options.frameWidth + parseInt(newFrame.css('margin-right'), 10),
stripLeft = this.strip.position().left,
frameViewportLeft = frameLeft + stripLeft,
frameViewportRight = frameViewportLeft + this.options.frameWidth;
if(frameViewportRight > this.stripWrapper.width()) {
this.strip.animate({left: '-=' + stepFactor}, this.options.effectSpeed, 'easeInOutCirc');
} else if(frameViewportLeft < 0) {
this.strip.animate({left: '+=' + stepFactor}, this.options.effectSpeed, 'easeInOutCirc');
}
}
}
//caption
if(this.options.showCaption) {
this._showCaption(newPanel);
}
this.options.activeIndex = index;
}
},
_hideCaption: function() {
this.caption.slideUp(this.options.effectSpeed);
},
_showCaption: function(panel) {
var image = panel.children('img');
this.caption.html('<h4>' + image.attr('title') + '</h4><p>' + image.attr('alt') + '</p>').slideDown(this.options.effectSpeed);
},
prev: function() {
if(this.options.activeIndex !== 0) {
this.select(this.options.activeIndex - 1);
}
},
next: function() {
if(this.options.activeIndex !== (this.panels.length - 1)) {
this.select(this.options.activeIndex + 1);
}
else {
this.select(0, false);
this.strip.animate({left: 0}, this.options.effectSpeed, 'easeInOutCirc');
}
},
isAnimating: function() {
return this.strip.is(':animated');
}
});
})();/**
* PrimeFaces Growl Widget
*/
(function() {
$.widget("primeui.puigrowl", {
options: {
sticky: false,
life: 3000
},
_create: function() {
var container = this.element;
container.addClass("pui-growl ui-widget").appendTo(document.body);
},
show: function(msgs) {
var $this = this;
//this.jq.css('z-index', ++PrimeFaces.zindex);
this.clear();
$.each(msgs, function(i, msg) {
$this._renderMessage(msg);
});
},
clear: function() {
this.element.children('div.pui-growl-item-container').remove();
},
_renderMessage: function(msg) {
var markup = '<div class="pui-growl-item-container ui-state-highlight ui-corner-all ui-helper-hidden" aria-live="polite">';
markup += '<div class="pui-growl-item pui-shadow">';
markup += '<div class="pui-growl-icon-close fa fa-close" style="display:none"></div>';
markup += '<span class="pui-growl-image fa fa-2x ' + this._getIcon(msg.severity) + ' pui-growl-image-' + msg.severity + '"/>';
markup += '<div class="pui-growl-message">';
markup += '<span class="pui-growl-title">' + msg.summary + '</span>';
markup += '<p>' + (msg.detail||'') + '</p>';
markup += '</div><div style="clear: both;"></div></div></div>';
var message = $(markup);
this._bindMessageEvents(message);
message.appendTo(this.element).fadeIn();
},
_removeMessage: function(message) {
message.fadeTo('normal', 0, function() {
message.slideUp('normal', 'easeInOutCirc', function() {
message.remove();
});
});
},
_bindMessageEvents: function(message) {
var $this = this,
sticky = this.options.sticky;
message.on('mouseover.puigrowl', function() {
var msg = $(this);
if(!msg.is(':animated')) {
msg.find('div.pui-growl-icon-close:first').show();
}
})
.on('mouseout.puigrowl', function() {
$(this).find('div.pui-growl-icon-close:first').hide();
});
//remove message on click of close icon
message.find('div.pui-growl-icon-close').on('click.puigrowl',function() {
$this._removeMessage(message);
if(!sticky) {
window.clearTimeout(message.data('timeout'));
}
});
if(!sticky) {
this._setRemovalTimeout(message);
}
},
_setRemovalTimeout: function(message) {
var $this = this;
var timeout = window.setTimeout(function() {
$this._removeMessage(message);
}, this.options.life);
message.data('timeout', timeout);
},
_getIcon: function(severity) {
switch(severity) {
case 'info':
return 'fa-info-circle';
break;
case 'warn':
return 'fa-warning';
break;
case 'error':
return 'fa-close';
break;
default:
return 'fa-info-circle';
break;
}
}
});
})();/**
* PrimeUI inputtext widget
*/
(function() {
$.widget("primeui.puiinputtext", {
_create: function() {
var input = this.element,
disabled = input.prop('disabled');
//visuals
input.addClass('pui-inputtext ui-widget ui-state-default ui-corner-all');
if(disabled) {
input.addClass('ui-state-disabled');
}
else {
this._enableMouseEffects();
}
//aria
input.attr('role', 'textbox').attr('aria-disabled', disabled)
.attr('aria-readonly', input.prop('readonly'))
.attr('aria-multiline', input.is('textarea'));
},
_destroy: function() {
},
_enableMouseEffects: function () {
var input = this.element;
input.hover(function () {
input.toggleClass('ui-state-hover');
}).focus(function () {
input.addClass('ui-state-focus');
}).blur(function () {
input.removeClass('ui-state-focus');
});
},
_disableMouseEffects: function () {
var input = this.element;
input.off( "mouseenter mouseleave focus blur" );
},
disable: function () {
this.element.prop('disabled', true);
this.element.attr('aria-disabled', true);
this.element.addClass('ui-state-disabled');
this.element.removeClass('ui-state-focus ui-state-hover');
this._disableMouseEffects();
},
enable: function () {
this.element.prop('disabled', false);
this.element.attr('aria-disabled', false);
this.element.removeClass('ui-state-disabled');
this._enableMouseEffects();
}
});
})();/**
* PrimeUI inputtextarea widget
*/
(function() {
$.widget("primeui.puiinputtextarea", {
options: {
autoResize: false,
autoComplete: false,
maxlength: null,
counter: null,
counterTemplate: '{0}',
minQueryLength: 3,
queryDelay: 700,
completeSource: null
},
_create: function() {
var $this = this;
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.puiinputtext();
if(this.options.autoResize) {
this.options.rowsDefault = this.element.attr('rows');
this.options.colsDefault = this.element.attr('cols');
this.element.addClass('pui-inputtextarea-resizable');
this.element.keyup(function() {
$this._resize();
}).focus(function() {
$this._resize();
}).blur(function() {
$this._resize();
});
}
if(this.options.maxlength) {
this.element.keyup(function(e) {
var value = $this.element.val(),
length = value.length;
if(length > $this.options.maxlength) {
$this.element.val(value.substr(0, $this.options.maxlength));
}
if($this.options.counter) {
$this._updateCounter();
}
});
}
if(this.options.counter) {
this._updateCounter();
}
if(this.options.autoComplete) {
this._initAutoComplete();
}
},
_updateCounter: function() {
var value = this.element.val(),
length = value.length;
if(this.options.counter) {
var remaining = this.options.maxlength - length,
remainingText = this.options.counterTemplate.replace('{0}', remaining);
this.options.counter.text(remainingText);
}
},
_resize: function() {
var linesCount = 0,
lines = this.element.val().split('\n');
for(var i = lines.length-1; i >= 0 ; --i) {
linesCount += Math.floor((lines[i].length / this.options.colsDefault) + 1);
}
var newRows = (linesCount >= this.options.rowsDefault) ? (linesCount + 1) : this.options.rowsDefault;
this.element.attr('rows', newRows);
},
_initAutoComplete: function() {
var panelMarkup = '<div id="' + this.id + '_panel" class="pui-autocomplete-panel ui-widget-content ui-corner-all ui-helper-hidden pui-shadow"></div>',
$this = this;
this.panel = $(panelMarkup).appendTo(document.body);
this.element.keyup(function(e) {
var keyCode = $.ui.keyCode;
switch(e.which) {
case keyCode.UP:
case keyCode.LEFT:
case keyCode.DOWN:
case keyCode.RIGHT:
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
case keyCode.TAB:
case keyCode.SPACE:
case keyCode.CONTROL:
case keyCode.ALT:
case keyCode.ESCAPE:
case 224: //mac command
//do not search
break;
default:
var query = $this._extractQuery();
if(query && query.length >= $this.options.minQueryLength) {
//Cancel the search request if user types within the timeout
if($this.timeout) {
$this._clearTimeout($this.timeout);
}
$this.timeout = window.setTimeout(function() {
$this.search(query);
}, $this.options.queryDelay);
}
break;
}
}).keydown(function(e) {
var overlayVisible = $this.panel.is(':visible'),
keyCode = $.ui.keyCode,
highlightedItem;
switch(e.which) {
case keyCode.UP:
case keyCode.LEFT:
if(overlayVisible) {
highlightedItem = $this.items.filter('.ui-state-highlight');
var prev = highlightedItem.length === 0 ? $this.items.eq(0) : highlightedItem.prev();
if(prev.length == 1) {
highlightedItem.removeClass('ui-state-highlight');
prev.addClass('ui-state-highlight');
if($this.options.scrollHeight) {
PUI.scrollInView($this.panel, prev);
}
}
e.preventDefault();
}
else {
$this._clearTimeout();
}
break;
case keyCode.DOWN:
case keyCode.RIGHT:
if(overlayVisible) {
highlightedItem = $this.items.filter('.ui-state-highlight');
var next = highlightedItem.length === 0 ? _self.items.eq(0) : highlightedItem.next();
if(next.length == 1) {
highlightedItem.removeClass('ui-state-highlight');
next.addClass('ui-state-highlight');
if($this.options.scrollHeight) {
PUI.scrollInView($this.panel, next);
}
}
e.preventDefault();
}
else {
$this._clearTimeout();
}
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
if(overlayVisible) {
$this.items.filter('.ui-state-highlight').trigger('click');
e.preventDefault();
}
else {
$this._clearTimeout();
}
break;
case keyCode.SPACE:
case keyCode.CONTROL:
case keyCode.ALT:
case keyCode.BACKSPACE:
case keyCode.ESCAPE:
case 224: //mac command
$this._clearTimeout();
if(overlayVisible) {
$this._hide();
}
break;
case keyCode.TAB:
$this._clearTimeout();
if(overlayVisible) {
$this.items.filter('.ui-state-highlight').trigger('click');
$this._hide();
}
break;
}
});
//hide panel when outside is clicked
$(document.body).bind('mousedown.puiinputtextarea', function (e) {
if($this.panel.is(":hidden")) {
return;
}
var offset = $this.panel.offset();
if(e.target === $this.element.get(0)) {
return;
}
if (e.pageX < offset.left ||
e.pageX > offset.left + $this.panel.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.panel.height()) {
$this._hide();
}
});
//Hide overlay on resize
var resizeNS = 'resize.' + this.id;
$(window).unbind(resizeNS).bind(resizeNS, function() {
if($this.panel.is(':visible')) {
$this._hide();
}
});
},
_bindDynamicEvents: function() {
var $this = this;
//visuals and click handler for items
this.items.bind('mouseover', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight')) {
$this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight');
item.addClass('ui-state-highlight');
}
})
.bind('click', function(event) {
var item = $(this),
itemValue = item.attr('data-item-value'),
insertValue = itemValue.substring($this.query.length);
$this.element.focus();
$this.element.insertText(insertValue, $this.element.getSelection().start, true);
$this._hide();
$this._trigger("itemselect", event, item);
});
},
_clearTimeout: function() {
if(this.timeout) {
window.clearTimeout(this.timeout);
}
this.timeout = null;
},
_extractQuery: function() {
var end = this.element.getSelection().end,
result = /\S+$/.exec(this.element.get(0).value.slice(0, end)),
lastWord = result ? result[0] : null;
return lastWord;
},
search: function(q) {
this.query = q;
var request = {
query: q
};
if(this.options.completeSource) {
this.options.completeSource.call(this, request, this._handleResponse);
}
},
_handleResponse: function(data) {
this.panel.html('');
var listContainer = $('<ul class="pui-autocomplete-items pui-autocomplete-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>');
for(var i = 0; i < data.length; i++) {
var item = $('<li class="pui-autocomplete-item pui-autocomplete-list-item ui-corner-all"></li>');
item.attr('data-item-value', data[i].value);
item.text(data[i].label);
listContainer.append(item);
}
this.panel.append(listContainer);
this.items = this.panel.find('.pui-autocomplete-item');
this._bindDynamicEvents();
if(this.items.length > 0) {
//highlight first item
this.items.eq(0).addClass('ui-state-highlight');
//adjust height
if(this.options.scrollHeight && this.panel.height() > this.options.scrollHeight) {
this.panel.height(this.options.scrollHeight);
}
if(this.panel.is(':hidden')) {
this._show();
}
else {
this._alignPanel(); //with new items
}
}
else {
this.panel.hide();
}
},
_alignPanel: function() {
var pos = this.element.getCaretPosition(),
offset = this.element.offset();
this.panel.css({
'left': offset.left + pos.left,
'top': offset.top + pos.top,
'width': this.element.innerWidth()
});
},
_show: function() {
this._alignPanel();
this.panel.show();
},
_hide: function() {
this.panel.hide();
},
disable: function () {
this.element.puiinputtext('disable');
},
enable: function () {
this.element.puiinputtext('enable');
}
});
})();/**
* PrimeUI Lightbox Widget
*/
(function() {
$.widget("primeui.puilightbox", {
options: {
iframeWidth: 640,
iframeHeight: 480,
iframe: false
},
_create: function() {
this.options.mode = this.options.iframe ? 'iframe' : (this.element.children('div').length == 1) ? 'inline' : 'image';
var dom = '<div class="pui-lightbox ui-widget ui-helper-hidden ui-corner-all pui-shadow">';
dom += '<div class="pui-lightbox-content-wrapper">';
dom += '<a class="ui-state-default pui-lightbox-nav-left ui-corner-right ui-helper-hidden"><span class="fa fa-fw fa-caret-left"></span></a>';
dom += '<div class="pui-lightbox-content ui-corner-all"></div>';
dom += '<a class="ui-state-default pui-lightbox-nav-right ui-corner-left ui-helper-hidden"><span class="fa fa-fw fa-caret-right"></span></a>';
dom += '</div>';
dom += '<div class="pui-lightbox-caption ui-widget-header"><span class="pui-lightbox-caption-text"></span>';
dom += '<a class="pui-lightbox-close ui-corner-all" href="#"><span class="fa fa-fw fa-close"></span></a><div style="clear:both" /></div>';
dom += '</div>';
this.panel = $(dom).appendTo(document.body);
this.contentWrapper = this.panel.children('.pui-lightbox-content-wrapper');
this.content = this.contentWrapper.children('.pui-lightbox-content');
this.caption = this.panel.children('.pui-lightbox-caption');
this.captionText = this.caption.children('.pui-lightbox-caption-text');
this.closeIcon = this.caption.children('.pui-lightbox-close');
if(this.options.mode === 'image') {
this._setupImaging();
}
else if(this.options.mode === 'inline') {
this._setupInline();
}
else if(this.options.mode === 'iframe') {
this._setupIframe();
}
this._bindCommonEvents();
this.links.data('puilightbox-trigger', true).find('*').data('puilightbox-trigger', true);
this.closeIcon.data('puilightbox-trigger', true).find('*').data('puilightbox-trigger', true);
},
_bindCommonEvents: function() {
var $this = this;
this.closeIcon.hover(function() {
$(this).toggleClass('ui-state-hover');
}).click(function(e) {
$this.hide();
e.preventDefault();
});
//hide when outside is clicked
$(document.body).bind('click.pui-lightbox', function (e) {
if($this.isHidden()) {
return;
}
//do nothing if target is the link
var target = $(e.target);
if(target.data('puilightbox-trigger')) {
return;
}
//hide if mouse is outside of lightbox
var offset = $this.panel.offset();
if(e.pageX < offset.left ||
e.pageX > offset.left + $this.panel.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.panel.height()) {
$this.hide();
}
});
//sync window resize
$(window).resize(function() {
if(!$this.isHidden()) {
$(document.body).children('.ui-widget-overlay').css({
'width': $(document).width(),
'height': $(document).height()
});
}
});
},
_setupImaging: function() {
var $this = this;
this.links = this.element.children('a');
this.content.append('<img class="ui-helper-hidden"></img>');
this.imageDisplay = this.content.children('img');
this.navigators = this.contentWrapper.children('a');
this.imageDisplay.load(function() {
var image = $(this);
$this._scaleImage(image);
//coordinates to center overlay
var leftOffset = ($this.panel.width() - image.width()) / 2,
topOffset = ($this.panel.height() - image.height()) / 2;
//resize content for new image
$this.content.removeClass('pui-lightbox-loading').animate({
width: image.width(),
height: image.height()
},
500,
function() {
//show image
image.fadeIn();
$this._showNavigators();
$this.caption.slideDown();
});
$this.panel.animate({
left: '+=' + leftOffset,
top: '+=' + topOffset
}, 500);
});
this.navigators.hover(function() {
$(this).toggleClass('ui-state-hover');
})
.click(function(e) {
var nav = $(this),
index;
$this._hideNavigators();
if(nav.hasClass('pui-lightbox-nav-left')) {
index = $this.current === 0 ? $this.links.length - 1 : $this.current - 1;
$this.links.eq(index).trigger('click');
}
else {
index = $this.current == $this.links.length - 1 ? 0 : $this.current + 1;
$this.links.eq(index).trigger('click');
}
e.preventDefault();
});
this.links.click(function(e) {
var link = $(this);
if($this.isHidden()) {
$this.content.addClass('pui-lightbox-loading').width(32).height(32);
$this.show();
}
else {
$this.imageDisplay.fadeOut(function() {
//clear for onload scaling
$(this).css({
'width': 'auto',
'height': 'auto'
});
$this.content.addClass('pui-lightbox-loading');
});
$this.caption.slideUp();
}
window.setTimeout(function() {
$this.imageDisplay.attr('src', link.attr('href'));
$this.current = link.index();
var title = link.attr('title');
if(title) {
$this.captionText.html(title);
}
}, 1000);
e.preventDefault();
});
},
_scaleImage: function(image) {
var win = $(window),
winWidth = win.width(),
winHeight = win.height(),
imageWidth = image.width(),
imageHeight = image.height(),
ratio = imageHeight / imageWidth;
if(imageWidth >= winWidth && ratio <= 1){
imageWidth = winWidth * 0.75;
imageHeight = imageWidth * ratio;
}
else if(imageHeight >= winHeight){
imageHeight = winHeight * 0.75;
imageWidth = imageHeight / ratio;
}
image.css({
'width':imageWidth + 'px',
'height':imageHeight + 'px'
});
},
_setupInline: function() {
this.links = this.element.children('a');
this.inline = this.element.children('div').addClass('pui-lightbox-inline');
this.inline.appendTo(this.content).show();
var $this = this;
this.links.click(function(e) {
$this.show();
var title = $(this).attr('title');
if(title) {
$this.captionText.html(title);
$this.caption.slideDown();
}
e.preventDefault();
});
},
_setupIframe: function() {
var $this = this;
this.links = this.element;
this.iframe = $('<iframe frameborder="0" style="width:' + this.options.iframeWidth + 'px;height:' +
this.options.iframeHeight + 'px;border:0 none; display: block;"></iframe>').appendTo(this.content);
if(this.options.iframeTitle) {
this.iframe.attr('title', this.options.iframeTitle);
}
this.element.click(function(e) {
if(!$this.iframeLoaded) {
$this.content.addClass('pui-lightbox-loading').css({
width: $this.options.iframeWidth,
height: $this.options.iframeHeight
});
$this.show();
$this.iframe.on('load', function() {
$this.iframeLoaded = true;
$this.content.removeClass('pui-lightbox-loading');
})
.attr('src', $this.element.attr('href'));
}
else {
$this.show();
}
var title = $this.element.attr('title');
if(title) {
$this.caption.html(title);
$this.caption.slideDown();
}
e.preventDefault();
});
},
show: function() {
this.center();
this.panel.css('z-index', ++PUI.zindex).show();
if(!this.modality) {
this._enableModality();
}
this._trigger('show');
},
hide: function() {
this.panel.fadeOut();
this._disableModality();
this.caption.hide();
if(this.options.mode === 'image') {
this.imageDisplay.hide().attr('src', '').removeAttr('style');
this._hideNavigators();
}
this._trigger('hide');
},
center: function() {
var win = $(window),
left = (win.width() / 2 ) - (this.panel.width() / 2),
top = (win.height() / 2 ) - (this.panel.height() / 2);
this.panel.css({
'left': left,
'top': top
});
},
_enableModality: function() {
this.modality = $('<div class="ui-widget-overlay"></div>')
.css({
'width': $(document).width(),
'height': $(document).height(),
'z-index': this.panel.css('z-index') - 1
})
.appendTo(document.body);
},
_disableModality: function() {
this.modality.remove();
this.modality = null;
},
_showNavigators: function() {
this.navigators.zIndex(this.imageDisplay.zIndex() + 1).show();
},
_hideNavigators: function() {
this.navigators.hide();
},
isHidden: function() {
return this.panel.is(':hidden');
},
showURL: function(opt) {
if(opt.width) {
this.iframe.attr('width', opt.width);
}
if(opt.height) {
this.iframe.attr('height', opt.height);
}
this.iframe.attr('src', opt.src);
this.show();
}
});
})();/**
* PrimeUI listvox widget
*/
(function() {
$.widget("primeui.puilistbox", {
options: {
scrollHeight: 200,
content: null,
data: null,
template: null,
style: null,
styleClass: null
},
_create: function() {
this.element.wrap('<div class="pui-listbox pui-inputtext ui-widget ui-widget-content ui-corner-all"><div class="ui-helper-hidden-accessible"></div></div>');
this.container = this.element.parent().parent();
this.listContainer = $('<ul class="pui-listbox-list"></ul>').appendTo(this.container);
this.options.multiple = this.element.prop("multiple");
if(this.options.style) {
this.container.attr('style', this.options.style);
}
if(this.options.styleClass) {
this.container.addClass(this.options.styleClass);
}
if(this.options.data) {
this._populateInputFromData();
}
this._populateContainerFromOptions();
this._restrictHeight();
this._bindEvents();
},
_populateInputFromData: function() {
for(var i = 0; i < this.options.data.length; i++) {
var choice = this.options.data[i];
if(choice.label) {
this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>');
} else {
this.element.append('<option value="' + choice + '">' + choice + '</option>');
}
}
},
_populateContainerFromOptions: function() {
this.choices = this.element.children('option');
for(var i = 0; i < this.choices.length; i++) {
var choice = this.choices.eq(i);
this.listContainer.append('<li class="pui-listbox-item ui-corner-all">' + this._createItemContent(choice.get(0)) + '</li>');
}
this.items = this.listContainer.find('.pui-listbox-item:not(.ui-state-disabled)');
},
_restrictHeight: function() {
if(this.container.height() > this.options.scrollHeight) {
this.container.height(this.options.scrollHeight);
}
},
_bindEvents: function() {
var $this = this;
//items
this.items.on('mouseover.puilistbox', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight')) {
item.addClass('ui-state-hover');
}
})
.on('mouseout.puilistbox', function() {
$(this).removeClass('ui-state-hover');
})
.on('dblclick.puilistbox', function(e) {
$this.element.trigger('dblclick');
PUI.clearSelection();
e.preventDefault();
})
.on('click.puilistbox', function(e) {
if($this.options.multiple)
$this._clickMultiple(e, $(this));
else
$this._clickSingle(e, $(this));
});
//input
this.element.on('focus.puilistbox', function() {
$this.container.addClass('ui-state-focus');
}).on('blur.puilistbox', function() {
$this.container.removeClass('ui-state-focus');
});
},
_clickSingle: function(event, item) {
var selectedItem = this.items.filter('.ui-state-highlight');
if(item.index() !== selectedItem.index()) {
if(selectedItem.length) {
this.unselectItem(selectedItem);
}
this.selectItem(item);
this.element.trigger('change');
}
this.element.trigger('click');
PUI.clearSelection();
event.preventDefault();
},
_clickMultiple: function(event, item) {
var selectedItems = this.items.filter('.ui-state-highlight'),
metaKey = (event.metaKey||event.ctrlKey),
unchanged = (!metaKey && selectedItems.length === 1 && selectedItems.index() === item.index());
if(!event.shiftKey) {
if(!metaKey) {
this.unselectAll();
}
if(metaKey && item.hasClass('ui-state-highlight')) {
this.unselectItem(item);
}
else {
this.selectItem(item);
this.cursorItem = item;
}
}
else {
//range selection
if(this.cursorItem) {
this.unselectAll();
var currentItemIndex = item.index(),
cursorItemIndex = this.cursorItem.index(),
startIndex = (currentItemIndex > cursorItemIndex) ? cursorItemIndex : currentItemIndex,
endIndex = (currentItemIndex > cursorItemIndex) ? (currentItemIndex + 1) : (cursorItemIndex + 1);
for(var i = startIndex ; i < endIndex; i++) {
this.selectItem(this.items.eq(i));
}
}
else {
this.selectItem(item);
this.cursorItem = item;
}
}
if(!unchanged) {
this.element.trigger('change');
}
this.element.trigger('click');
PUI.clearSelection();
event.preventDefault();
},
unselectAll: function() {
this.items.removeClass('ui-state-highlight ui-state-hover');
this.choices.filter(':selected').prop('selected', false);
},
selectItem: function(value) {
var item = null;
if($.type(value) === 'number') {
item = this.items.eq(value);
}
else {
item = value;
}
item.addClass('ui-state-highlight').removeClass('ui-state-hover');
this.choices.eq(item.index()).prop('selected', true);
this._trigger('itemSelect', null, this.choices.eq(item.index()));
},
unselectItem: function(value) {
var item = null;
if($.type(value) === 'number') {
item = this.items.eq(value);
}
else {
item = value;
}
item.removeClass('ui-state-highlight');
this.choices.eq(item.index()).prop('selected', false);
this._trigger('itemUnselect', null, this.choices.eq(item.index()));
},
_setOption: function (key, value) {
$.Widget.prototype._setOption.apply(this, arguments);
if (key === 'data') {
this.element.empty();
this.listContainer.empty();
this._populateInputFromData();
this._populateContainerFromOptions();
this._restrictHeight();
this._bindEvents();
}
},
_unbindEvents: function() {
this.items.off('mouseover.puilistbox click.puilistbox dblclick.puilistbox');
},
disable: function () {
this._unbindEvents();
this.items.addClass('ui-state-disabled');
},
enable: function () {
this._bindEvents();
this.items.removeClass('ui-state-disabled');
},
_createItemContent: function(choice) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, choice);
}
else if(this.options.content) {
return this.options.content.call(this, choice);
}
else {
return choice.label;
}
}
});
})();/**
* PrimeUI BaseMenu widget
*/
(function() {
$.widget("primeui.puibasemenu", {
options: {
popup: false,
trigger: null,
my: 'left top',
at: 'left bottom',
triggerEvent: 'click'
},
_create: function() {
if(this.options.popup) {
this._initPopup();
}
},
_initPopup: function() {
var $this = this;
this.element.closest('.pui-menu').addClass('pui-menu-dynamic pui-shadow').appendTo(document.body);
if($.type(this.options.trigger) === 'string') {
this.options.trigger = $(this.options.trigger);
}
this.positionConfig = {
my: this.options.my,
at: this.options.at,
of: this.options.trigger
};
this.options.trigger.on(this.options.triggerEvent + '.pui-menu', function(e) {
if($this.element.is(':visible')) {
$this.hide();
}
else {
$this.show();
}
e.preventDefault();
});
//hide overlay on document click
$(document.body).on('click.pui-menu', function (e) {
var popup = $this.element.closest('.pui-menu');
if(popup.is(":hidden")) {
return;
}
//do nothing if mousedown is on trigger
var target = $(e.target);
if(target.is($this.options.trigger.get(0))||$this.options.trigger.has(target).length > 0) {
return;
}
//hide if mouse is outside of overlay except trigger
var offset = popup.offset();
if(e.pageX < offset.left ||
e.pageX > offset.left + popup.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + popup.height()) {
$this.hide(e);
}
});
//Hide overlay on resize
$(window).on('resize.pui-menu', function() {
if($this.element.closest('.pui-menu').is(':visible')) {
$this.align();
}
});
},
show: function() {
this.align();
this.element.closest('.pui-menu').css('z-index', ++PUI.zindex).show();
},
hide: function() {
this.element.closest('.pui-menu').fadeOut('fast');
},
align: function() {
this.element.closest('.pui-menu').css({left:'', top:''}).position(this.positionConfig);
}
});
})();
/**
* PrimeUI Menu widget
*/
(function() {
$.widget("primeui.puimenu", $.primeui.puibasemenu, {
options: {
},
_create: function() {
this.element.addClass('pui-menu-list ui-helper-reset').
wrap('<div class="pui-menu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix" />');
this.element.children('li').each(function() {
var listItem = $(this);
if(listItem.children('h3').length > 0) {
listItem.addClass('ui-widget-header ui-corner-all');
}
else {
listItem.addClass('pui-menuitem ui-widget ui-corner-all');
var menuitemLink = listItem.children('a'),
icon = menuitemLink.data('icon');
menuitemLink.addClass('pui-menuitem-link ui-corner-all').contents().wrap('<span class="pui-menuitem-text" />');
if(icon) {
menuitemLink.prepend('<span class="pui-menuitem-icon fa fa-fw ' + icon + '"></span>');
}
}
});
this.menuitemLinks = this.element.find('.pui-menuitem-link:not(.ui-state-disabled)');
this._bindEvents();
this._super();
},
_bindEvents: function() {
var $this = this;
this.menuitemLinks.on('mouseenter.pui-menu', function(e) {
$(this).addClass('ui-state-hover');
})
.on('mouseleave.pui-menu', function(e) {
$(this).removeClass('ui-state-hover');
});
if(this.options.popup) {
this.menuitemLinks.on('click.pui-menu', function() {
$this.hide();
});
}
}
});
})();
/**
* PrimeUI BreadCrumb Widget
*/
(function() {
$.widget("primeui.puibreadcrumb", {
_create: function() {
this.element.wrap('<div class="pui-breadcrumb ui-module ui-widget ui-widget-header ui-helper-clearfix ui-corner-all" role="menu">');
this.element.children('li').each(function(index) {
var listItem = $(this);
listItem.attr('role', 'menuitem');
var menuitemLink = listItem.children('a');
menuitemLink.addClass('pui-menuitem-link ui-corner-all').contents().wrap('<span class="pui-menuitem-text" />');
if(index > 0) {
listItem.before('<li class="pui-breadcrumb-chevron fa fa-chevron-right"></li>');
}
else {
listItem.before('<li class="fa fa-home"></li>');
}
});
}
});
})();
/*
* PrimeUI TieredMenu Widget
*/
(function() {
$.widget("primeui.puitieredmenu", $.primeui.puibasemenu, {
options: {
autoDisplay: true
},
_create: function() {
this._render();
this.links = this.element.find('.pui-menuitem-link:not(.ui-state-disabled)');
this._bindEvents();
this._super();
},
_render: function() {
var $this = this;
this.element.addClass('pui-menu-list ui-helper-reset').
wrap('<div class="pui-tieredmenu pui-menu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix" />');
this.element.parent().uniqueId();
this.options.id = this.element.parent().attr('id');
this.element.find('li').each(function() {
var listItem = $(this),
menuitemLink = listItem.children('a'),
icon = menuitemLink.data('icon');
menuitemLink.addClass('pui-menuitem-link ui-corner-all').contents().wrap('<span class="pui-menuitem-text" />');
if(icon) {
menuitemLink.prepend('<span class="pui-menuitem-icon fa fa-fw ' + icon + '"></span>');
}
listItem.addClass('pui-menuitem ui-widget ui-corner-all');
if(listItem.children('ul').length > 0) {
var submenuIcon = listItem.parent().hasClass('pui-menu-child') ? 'fa-caret-right' : $this._getRootSubmenuIcon();
listItem.addClass('pui-menu-parent');
listItem.children('ul').addClass('ui-widget-content pui-menu-list ui-corner-all ui-helper-clearfix pui-menu-child pui-shadow');
menuitemLink.prepend('<span class="pui-submenu-icon fa fa-fw ' + submenuIcon + '"></span>');
}
});
},
_bindEvents: function() {
this._bindItemEvents();
this._bindDocumentHandler();
},
_bindItemEvents: function() {
var $this = this;
this.links.on('mouseenter.pui-menu',function() {
var link = $(this),
menuitem = link.parent(),
autoDisplay = $this.options.autoDisplay;
var activeSibling = menuitem.siblings('.pui-menuitem-active');
if(activeSibling.length === 1) {
$this._deactivate(activeSibling);
}
if(autoDisplay||$this.active) {
if(menuitem.hasClass('pui-menuitem-active')) {
$this._reactivate(menuitem);
}
else {
$this._activate(menuitem);
}
}
else {
$this._highlight(menuitem);
}
});
if(this.options.autoDisplay === false) {
this.rootLinks = this.element.find('> .pui-menuitem > .pui-menuitem-link');
this.rootLinks.data('primeui-tieredmenu-rootlink', this.options.id).find('*').data('primeui-tieredmenu-rootlink', this.options.id);
this.rootLinks.on('click.pui-menu', function(e) {
var link = $(this),
menuitem = link.parent(),
submenu = menuitem.children('ul.pui-menu-child');
if(submenu.length === 1) {
if(submenu.is(':visible')) {
$this.active = false;
$this._deactivate(menuitem);
}
else {
$this.active = true;
$this._highlight(menuitem);
$this._showSubmenu(menuitem, submenu);
}
}
});
}
this.element.parent().find('ul.pui-menu-list').on('mouseleave.pui-menu', function(e) {
if($this.activeitem) {
$this._deactivate($this.activeitem);
}
e.stopPropagation();
});
},
_bindDocumentHandler: function() {
var $this = this;
$(document.body).on('click.pui-menu', function(e) {
var target = $(e.target);
if(target.data('primeui-tieredmenu-rootlink') === $this.options.id) {
return;
}
$this.active = false;
$this.element.find('li.pui-menuitem-active').each(function() {
$this._deactivate($(this), true);
});
});
},
_deactivate: function(menuitem, animate) {
this.activeitem = null;
menuitem.children('a.pui-menuitem-link').removeClass('ui-state-hover');
menuitem.removeClass('pui-menuitem-active');
if(animate) {
menuitem.children('ul.pui-menu-child:visible').fadeOut('fast');
}
else {
menuitem.children('ul.pui-menu-child:visible').hide();
}
},
_activate: function(menuitem) {
this._highlight(menuitem);
var submenu = menuitem.children('ul.pui-menu-child');
if(submenu.length === 1) {
this._showSubmenu(menuitem, submenu);
}
},
_reactivate: function(menuitem) {
this.activeitem = menuitem;
var submenu = menuitem.children('ul.pui-menu-child'),
activeChilditem = submenu.children('li.pui-menuitem-active:first'),
_self = this;
if(activeChilditem.length === 1) {
_self._deactivate(activeChilditem);
}
},
_highlight: function(menuitem) {
this.activeitem = menuitem;
menuitem.children('a.pui-menuitem-link').addClass('ui-state-hover');
menuitem.addClass('pui-menuitem-active');
},
_showSubmenu: function(menuitem, submenu) {
submenu.css({
'left': menuitem.outerWidth(),
'top': 0,
'z-index': ++PUI.zindex
});
submenu.show();
},
_getRootSubmenuIcon: function() {
return 'fa-caret-right';
}
});
})();
/**
* PrimeUI Menubar Widget
*/
(function() {
$.widget("primeui.puimenubar", $.primeui.puitieredmenu, {
options: {
autoDisplay: true
},
_create: function() {
this._super();
this.element.parent().removeClass('pui-tieredmenu').
addClass('pui-menubar');
},
_showSubmenu: function(menuitem, submenu) {
var win = $(window),
submenuOffsetTop = null,
submenuCSS = {
'z-index': ++PUI.zindex
};
if(menuitem.parent().hasClass('pui-menu-child')) {
submenuCSS.left = menuitem.outerWidth();
submenuCSS.top = 0;
submenuOffsetTop = menuitem.offset().top - win.scrollTop();
}
else {
submenuCSS.left = 0;
submenuCSS.top = menuitem.outerHeight();
submenuOffsetTop = menuitem.offset().top + submenuCSS.top - win.scrollTop();
}
//adjust height within viewport
submenu.css('height', 'auto');
if((submenuOffsetTop + submenu.outerHeight()) > win.height()) {
submenuCSS.overflow = 'auto';
submenuCSS.height = win.height() - (submenuOffsetTop + 20);
}
submenu.css(submenuCSS).show();
},
_getRootSubmenuIcon: function() {
return 'fa-caret-down';
}
});
})();
/*
* PrimeUI SlideMenu Widget
*/
(function() {
$.widget("primeui.puislidemenu", $.primeui.puibasemenu, {
_create: function() {
this._render();
//elements
this.rootList = this.element;
this.content = this.element.parent();
this.wrapper = this.content.parent();
this.container = this.wrapper.parent();
this.submenus = this.container.find('ul.pui-menu-list');
this.links = this.element.find('a.pui-menuitem-link:not(.ui-state-disabled)');
this.backward = this.wrapper.children('div.pui-slidemenu-backward');
//config
this.stack = [];
this.jqWidth = this.container.width();
if(!this.element.hasClass('pui-menu-dynamic')) {
var $this = this;
setTimeout(function() {
$this._applyDimensions();
}, 100);
}
this._super();
this._bindEvents();
},
_render: function() {
this.element.addClass('pui-menu-list ui-helper-reset').
wrap('<div class="pui-menu pui-slidemenu ui-widget ui-widget-content ui-corner-all"/>').
wrap('<div class="pui-slidemenu-wrapper" />').
after('<div class="pui-slidemenu-backward ui-widget-header ui-corner-all">\n\
<span class="pui-icon fa fa-fw fa-caret-left"></span>Back</div>').
wrap('<div class="pui-slidemenu-content" />');
this.element.parent().uniqueId();
this.options.id = this.element.parent().attr('id');
this.element.find('li').each(function() {
var listItem = $(this),
menuitemLink = listItem.children('a'),
icon = menuitemLink.data('icon');
menuitemLink.addClass('pui-menuitem-link ui-corner-all').contents().wrap('<span class="pui-menuitem-text" />');
if(icon) {
menuitemLink.prepend('<span class="pui-menuitem-icon fa fa-fw ' + icon + '"></span>');
}
listItem.addClass('pui-menuitem ui-widget ui-corner-all');
if(listItem.children('ul').length > 0) {
listItem.addClass('pui-menu-parent');
listItem.children('ul').addClass('ui-widget-content pui-menu-list ui-corner-all ui-helper-clearfix pui-menu-child ui-shadow');
menuitemLink.prepend('<span class="pui-submenu-icon fa fa-fw fa-caret-right"></span>');
}
});
},
_bindEvents: function() {
var $this = this;
this.links.on('mouseenter.pui-menu',function() {
$(this).addClass('ui-state-hover');
})
.on('mouseleave.pui-menu',function() {
$(this).removeClass('ui-state-hover');
})
.on('click.pui-menu',function() {
var link = $(this),
submenu = link.next();
if(submenu.length == 1) {
$this._forward(submenu);
}
});
this.backward.on('click.pui-menu',function() {
$this._back();
});
},
_forward: function(submenu) {
var $this = this;
this._push(submenu);
var rootLeft = -1 * (this._depth() * this.jqWidth);
submenu.show().css({
left: this.jqWidth
});
this.rootList.animate({
left: rootLeft
}, 500, 'easeInOutCirc', function() {
if($this.backward.is(':hidden')) {
$this.backward.fadeIn('fast');
}
});
},
_back: function() {
if(!this.rootList.is(':animated')) {
var $this = this,
last = this._pop(),
depth = this._depth();
var rootLeft = -1 * (depth * this.jqWidth);
this.rootList.animate({
left: rootLeft
}, 500, 'easeInOutCirc', function() {
if(last) {
last.hide();
}
if(depth === 0) {
$this.backward.fadeOut('fast');
}
});
}
},
_push: function(submenu) {
this.stack.push(submenu);
},
_pop: function() {
return this.stack.pop();
},
_last: function() {
return this.stack[this.stack.length - 1];
},
_depth: function() {
return this.stack.length;
},
_applyDimensions: function() {
this.submenus.width(this.container.width());
this.wrapper.height(this.rootList.outerHeight(true) + this.backward.outerHeight(true));
this.content.height(this.rootList.outerHeight(true));
this.rendered = true;
},
show: function() {
this.align();
this.container.css('z-index', ++PUI.zindex).show();
if(!this.rendered) {
this._applyDimensions();
}
}
});
})();
/**
* PrimeUI Context Menu Widget
*/
(function() {
$.widget("primeui.puicontextmenu", $.primeui.puitieredmenu, {
options: {
autoDisplay: true,
target: null,
event: 'contextmenu'
},
_create: function() {
this._super();
this.element.parent().removeClass('pui-tieredmenu').
addClass('pui-contextmenu pui-menu-dynamic pui-shadow');
var $this = this;
if(this.options.target) {
if($.type(this.options.trigger) === 'string') {
this.options.trigger = $(this.options.trigger);
}
}
else {
this.options.target = $(document);
}
if(!this.element.parent().parent().is(document.body)) {
this.element.parent().appendTo('body');
}
if(this.options.target.hasClass('pui-datatable')) {
$this._bindDataTable();
}
else {
this.options.target.on(this.options.event + '.pui-contextmenu' , function(e){
$this.show(e);
});
}
},
_bindItemEvents: function() {
this._super();
var $this = this;
//hide menu on item click
this.links.bind('click', function() {
$this._hide();
});
},
_bindDocumentHandler: function() {
var $this = this;
//hide overlay when document is clicked
$(document.body).on('click.pui-contextmenu', function (e) {
if($this.element.parent().is(":hidden")) {
return;
}
$this._hide();
});
},
_bindDataTable: function() {
var rowSelector = '#' + this.options.target.attr('id') + ' tbody.pui-datatable-data > tr.ui-widget-content:not(.pui-datatable-empty-message)',
event = this.options.event + '.pui-datatable',
$this = this;
$(document).off(event, rowSelector)
.on(event, rowSelector, null, function(e) {
$this.options.target.puidatatable('onRowRightClick', event, $(this));
$this.show(e);
});
},
show: function(e) {
//hide other contextmenus if any
$(document.body).children('.pui-contextmenu:visible').hide();
var win = $(window),
left = e.pageX,
top = e.pageY,
width = this.element.parent().outerWidth(),
height = this.element.parent().outerHeight();
//collision detection for window boundaries
if((left + width) > (win.width())+ win.scrollLeft()) {
left = left - width;
}
if((top + height ) > (win.height() + win.scrollTop())) {
top = top - height;
}
if(this.options.beforeShow) {
this.options.beforeShow.call(this);
}
this.element.parent().css({
'left': left,
'top': top,
'z-index': ++PUI.zindex
}).show();
e.preventDefault();
e.stopPropagation();
},
_hide: function() {
var $this = this;
//hide submenus
this.element.parent().find('li.pui-menuitem-active').each(function() {
$this._deactivate($(this), true);
});
this.element.parent().fadeOut('fast');
},
isVisible: function() {
return this.element.parent().is(':visible');
},
getTarget: function() {
return this.jqTarget;
}
});
})();/**
* PrimeUI Messages widget
*/
(function() {
$.widget("primeui.puimessages", {
options: {
closable: true
},
_create: function() {
this.element.addClass('pui-messages ui-widget ui-corner-all');
if(this.options.closable) {
this.closer = $('<a href="#" class="pui-messages-close"><i class="fa fa-close"></i></a>').appendTo(this.element);
}
this.element.append('<span class="pui-messages-icon fa fa-2x"></span>');
this.msgContainer = $('<ul></ul>').appendTo(this.element);
this._bindEvents();
},
_bindEvents: function() {
var $this = this;
if(this.options.closable) {
this.closer.on('click', function(e) {
$this.element.slideUp();
e.preventDefault();
});
}
},
show: function(severity, msgs) {
this.clear();
this.element.removeClass('pui-messages-info pui-messages-warn pui-messages-error').addClass('pui-messages-' + severity);
this.element.children('.pui-messages-icon').removeClass('fa-info-circle fa-close fa-warning').addClass(this._getIcon(severity));
if($.isArray(msgs)) {
for(var i = 0; i < msgs.length; i++) {
this._showMessage(msgs[i]);
}
}
else {
this._showMessage(msgs);
}
this.element.show();
},
_showMessage: function(msg) {
this.msgContainer.append('<li><span class="pui-messages-summary">' + msg.summary + '</span><span class="pui-messages-detail">' + msg.detail + '</span></li>');
},
clear: function() {
this.msgContainer.children().remove();
this.element.hide();
},
_getIcon: function(severity) {
switch(severity) {
case 'info':
return 'fa-info-circle';
break;
case 'warn':
return 'fa-warning';
break;
case 'error':
return 'fa-close';
break;
default:
return 'fa-info-circle';
break;
}
}
});
})();(function() {
$.widget("primeui.puimultiselectlistbox", {
options: {
caption: null,
choices: null,
effect: false||'fade',
name: null,
value: null
},
_create: function() {
this.element.addClass('pui-multiselectlistbox ui-widget ui-helper-clearfix');
this.element.append('<input type="hidden"></input>');
this.element.append('<div class="pui-multiselectlistbox-listcontainer"></div>');
this.container = this.element.children('div');
this.input = this.element.children('input');
var choices = this.options.choices;
if(this.options.name) {
this.input.attr('name', this.options.name);
}
if(choices) {
if(this.options.caption) {
this.container.append('<div class="pui-multiselectlistbox-header ui-widget-header ui-corner-top">'+ this.options.caption +'</div>');
}
this.container.append('<ul class="pui-multiselectlistbox-list pui-inputfield ui-widget-content ui-corner-bottom"></ul>');
this.rootList = this.container.children('ul');
for(var i = 0; i < choices.length; i++) {
this._createItemNode(choices[i], this.rootList);
}
this.items = this.element.find('li.pui-multiselectlistbox-item');
this._bindEvents();
if(this.options.value !== undefined || this.options.value !== null) {
this.preselect(this.options.value);
}
}
},
_createItemNode: function(choice, parent) {
var listItem = $('<li class="pui-multiselectlistbox-item"><span>'+ choice.label + '</span></li>');
listItem.appendTo(parent);
if(choice.items) {
listItem.append('<ul class="ui-helper-hidden"></ul>');
var sublistContainer = listItem.children('ul');
for(var i = 0; i < choice.items.length; i++) {
this._createItemNode(choice.items[i], sublistContainer);
}
}
else {
listItem.attr('data-value', choice.value);
}
},
_unbindEvents: function() {
this.items.off('mouseover.multiSelectListbox mouseout.multiSelectListbox click.multiSelectListbox');
},
_bindEvents: function() {
var $this = this;
this.items.on('mouseover.multiSelectListbox', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight'))
$(this).addClass('ui-state-hover');
})
.on('mouseout.multiSelectListbox', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight'))
$(this).removeClass('ui-state-hover');
})
.on('click.multiSelectListbox', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight')) {
$this.showOptionGroup(item);
}
});
},
showOptionGroup: function(item) {
item.addClass('ui-state-highlight').removeClass('ui-state-hover').siblings().filter('.ui-state-highlight').removeClass('ui-state-highlight');
item.closest('.pui-multiselectlistbox-listcontainer').nextAll().remove();
var childItemsContainer = item.children('ul'),
itemValue = item.attr('data-value');
if(itemValue) {
this.input.val(itemValue);
}
if(childItemsContainer.length) {
var groupContainer = $('<div class="pui-multiselectlistbox-listcontainer" style="display:none"></div>');
childItemsContainer.clone(true).appendTo(groupContainer).addClass('pui-multiselectlistbox-list pui-inputfield ui-widget-content').removeClass('ui-helper-hidden');
groupContainer.prepend('<div class="pui-multiselectlistbox-header ui-widget-header ui-corner-top">' + item.children('span').text() + '</div>')
.children('.pui-multiselectlistbox-list').addClass('ui-corner-bottom');
this.element.append(groupContainer);
if (this.options.effect)
groupContainer.show(this.options.effect);
else
groupContainer.show();
}
},
disable: function() {
if(!this.options.disabled) {
this.options.disabled = true;
this.element.addClass('ui-state-disabled');
this._unbindEvents();
this.container.nextAll().remove();
}
},
getValue: function() {
return this.input.val();
},
preselect: function(value) {
var $this = this,
item = this.items.filter('[data-value="' + value + '"]');
if(item.length === 0) {
return;
}
var ancestors = item.parentsUntil('.pui-multiselectlistbox-list'),
selectedIndexMap = [];
for(var i = (ancestors.length - 1); i >= 0; i--) {
var ancestor = ancestors.eq(i);
if(ancestor.is('li')) {
selectedIndexMap.push(ancestor.index());
}
else if(ancestor.is('ul')) {
var groupContainer = $('<div class="pui-multiselectlistbox-listcontainer" style="display:none"></div>');
ancestor.clone(true).appendTo(groupContainer).addClass('pui-multiselectlistbox-list ui-widget-content ui-corner-all').removeClass('ui-helper-hidden');
groupContainer.prepend('<div class="pui-multiselectlistbox-header ui-widget-header ui-corner-top">' + ancestor.prev('span').text() + '</div>')
.children('.pui-multiselectlistbox-list').addClass('ui-corner-bottom').removeClass('ui-corner-all');
$this.element.append(groupContainer);
}
}
//highlight item
var lists = this.element.children('div.pui-multiselectlistbox-listcontainer'),
clonedItem = lists.find(' > ul.pui-multiselectlistbox-list > li.pui-multiselectlistbox-item').filter('[data-value="' + value + '"]');
clonedItem.addClass('ui-state-highlight');
//highlight ancestors
for(var i = 0; i < selectedIndexMap.length; i++) {
lists.eq(i).find('> .pui-multiselectlistbox-list > li.pui-multiselectlistbox-item').eq(selectedIndexMap[i]).addClass('ui-state-highlight');
}
$this.element.children('div.pui-multiselectlistbox-listcontainer:hidden').show();
}
});
})();
/**
* PrimeFaces Notify Widget
*/
(function() {
$.widget("primeui.puinotify", {
options: {
position: 'top',
visible: false,
animate: true,
effectSpeed: 'normal',
easing: 'swing'
},
_create: function() {
this.element.addClass('pui-notify pui-notify-' + this.options.position + ' ui-widget ui-widget-content pui-shadow')
.wrapInner('<div class="pui-notify-content" />').appendTo(document.body);
this.content = this.element.children('.pui-notify-content');
this.closeIcon = $('<span class="pui-notify-close fa fa-close"></span>').appendTo(this.element);
this._bindEvents();
if(this.options.visible) {
this.show();
}
},
_bindEvents: function() {
var $this = this;
this.closeIcon.on('click.puinotify', function() {
$this.hide();
});
},
show: function(content) {
var $this = this;
if(content) {
this.update(content);
}
this.element.css('z-index',++PUI.zindex);
this._trigger('beforeShow');
if(this.options.animate) {
this.element.slideDown(this.options.effectSpeed, this.options.easing, function() {
$this._trigger('afterShow');
});
}
else {
this.element.show();
$this._trigger('afterShow');
}
},
hide: function() {
var $this = this;
this._trigger('beforeHide');
if(this.options.animate) {
this.element.slideUp(this.options.effectSpeed, this.options.easing, function() {
$this._trigger('afterHide');
});
}
else {
this.element.hide();
$this._trigger('afterHide');
}
},
update: function(content) {
this.content.html(content);
}
});
})();/**
* PrimeUI picklist widget
*/
(function() {
$.widget("primeui.puiorderlist", {
options: {
controlsLocation: 'none',
dragdrop: true,
effect: 'fade',
caption: null,
responsive: false,
datasource: null,
content: null,
template: null
},
_create: function() {
this._createDom();
if(this.options.datasource) {
if($.isArray(this.options.datasource)) {
this._generateOptionElements(this.options.datasource);
}
else if($.type(this.options.datasource) === 'function') {
this.options.datasource.call(this, this._generateOptionElements);
}
}
this.optionElements = this.element.children('option');
this._createListElement();
this._bindEvents();
},
_createDom: function() {
this.element.addClass('ui-helper-hidden');
if(this.options.controlsLocation !== 'none')
this.element.wrap('<div class="pui-grid-col-10"></div>');
else
this.element.wrap('<div class="pui-grid-col-12"></div>');
this.element.parent().wrap('<div class="pui-orderlist pui-grid ui-widget"><div class="pui-grid-row"></div></div>')
this.container = this.element.closest('.pui-orderlist');
if(this.options.controlsLocation !== 'none') {
this.element.parent().before('<div class="pui-orderlist-controls pui-grid-col-2"></div>');
this._createButtons();
}
if(this.options.responsive) {
this.container.addClass('pui-grid-responsive');
}
},
_generateOptionElements: function(data) {
for(var i = 0; i < data.length; i++) {
var choice = data[i];
if(choice.label)
this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>');
else
this.element.append('<option value="' + choice + '">' + choice + '</option>');
}
},
_createListElement: function() {
this.list = $('<ul class="ui-widget-content pui-orderlist-list"></ul>').insertBefore(this.element);
for(var i = 0; i < this.optionElements.length; i++) {
var optionElement = this.optionElements.eq(i),
itemContent = this._createItemContent(optionElement.get(0)),
listItem = $('<li class="pui-orderlist-item ui-corner-all"></li>');
if($.type(itemContent) === 'string')
listItem.html(itemContent);
else
listItem.append(itemContent);
listItem.data('item-value', optionElement.attr('value')).appendTo(this.list);
}
this.items = this.list.children('.pui-orderlist-item');
if(this.options.caption) {
this.list.addClass('ui-corner-bottom').before('<div class="pui-orderlist-caption ui-widget-header ui-corner-top">' + this.options.caption + '</div>')
} else {
this.list.addClass('ui-corner-all')
}
},
_createButtons: function() {
var $this = this,
buttonContainer = this.element.parent().prev();
buttonContainer.append(this._createButton('fa-angle-up', 'pui-orderlist-button-moveup', function(){$this._moveUp();}))
.append(this._createButton('fa-angle-double-up', 'pui-orderlist-button-move-top', function(){$this._moveTop();}))
.append(this._createButton('fa-angle-down', 'pui-orderlist-button-move-down', function(){$this._moveDown();}))
.append(this._createButton('fa-angle-double-down', 'pui-orderlist-move-bottom', function(){$this._moveBottom();}));
},
_createButton: function(icon, cssClass, fn) {
var btn = $('<button class="' + cssClass + '" type="button"></button>').puibutton({
'icon': icon,
'click': function() {
fn();
$(this).removeClass('ui-state-hover ui-state-focus');
}
});
return btn;
},
_bindEvents: function() {
var $this = this;
this.items.on('mouseover.puiorderlist', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight'))
$(this).addClass('ui-state-hover');
})
.on('mouseout.puiorderlist', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight'))
$(this).removeClass('ui-state-hover');
})
.on('mousedown.puiorderlist', function(e) {
var element = $(this),
metaKey = (e.metaKey||e.ctrlKey);
if(!metaKey) {
element.removeClass('ui-state-hover').addClass('ui-state-highlight')
.siblings('.ui-state-highlight').removeClass('ui-state-highlight');
//$this.fireItemSelectEvent(element, e);
}
else {
if(element.hasClass('ui-state-highlight')) {
element.removeClass('ui-state-highlight');
//$this.fireItemUnselectEvent(element);
}
else {
element.removeClass('ui-state-hover').addClass('ui-state-highlight');
//$this.fireItemSelectEvent(element, e);
}
}
});
if(this.options.dragdrop) {
this.list.sortable({
revert: 1,
start: function(event, ui) {
//PrimeFaces.clearSelection();
}
,update: function(event, ui) {
$this.onDragDrop(event, ui);
}
});
}
},
_moveUp: function() {
var $this = this,
selectedItems = this.items.filter('.ui-state-highlight'),
itemsToMoveCount = selectedItems.length,
movedItemsCount = 0;
selectedItems.each(function() {
var item = $(this);
if(!item.is(':first-child')) {
item.hide($this.options.effect, {}, 'fast', function() {
item.insertBefore(item.prev()).show($this.options.effect, {}, 'fast', function() {
movedItemsCount++;
if(itemsToMoveCount === movedItemsCount) {
$this._saveState();
$this._fireReorderEvent();
}
});
});
}
else {
itemsToMoveCount--;
}
});
},
_moveTop: function() {
var $this = this,
selectedItems = this.items.filter('.ui-state-highlight'),
itemsToMoveCount = selectedItems.length,
movedItemsCount = 0;
selectedItems.each(function() {
var item = $(this);
if(!item.is(':first-child')) {
item.hide($this.options.effect, {}, 'fast', function() {
item.prependTo(item.parent()).show($this.options.effect, {}, 'fast', function(){
movedItemsCount++;
if(itemsToMoveCount === movedItemsCount) {
$this._saveState();
$this._fireReorderEvent();
}
});
});
}
else {
itemsToMoveCount--;
}
});
},
_moveDown: function() {
var $this = this,
selectedItems = $(this.items.filter('.ui-state-highlight').get().reverse()),
itemsToMoveCount = selectedItems.length,
movedItemsCount = 0;
selectedItems.each(function() {
var item = $(this);
if(!item.is(':last-child')) {
item.hide($this.options.effect, {}, 'fast', function() {
item.insertAfter(item.next()).show($this.options.effect, {}, 'fast', function() {
movedItemsCount++;
if(itemsToMoveCount === movedItemsCount) {
$this._saveState();
$this._fireReorderEvent();
}
});
});
}
else {
itemsToMoveCount--;
}
});
},
_moveBottom: function() {
var $this = this,
selectedItems = this.items.filter('.ui-state-highlight'),
itemsToMoveCount = selectedItems.length,
movedItemsCount = 0;
selectedItems.each(function() {
var item = $(this);
if(!item.is(':last-child')) {
item.hide($this.options.effect, {}, 'fast', function() {
item.appendTo(item.parent()).show($this.options.effect, {}, 'fast', function() {
movedItemsCount++;
if(itemsToMoveCount === movedItemsCount) {
$this._saveState();
$this._fireReorderEvent();
}
});
});
}
else {
itemsToMoveCount--;
}
});
},
_saveState: function() {
this.element.children().remove();
this._generateOptions();
},
_fireReorderEvent: function() {
this._trigger('reorder', null);
},
onDragDrop: function(event, ui) {
ui.item.removeClass('ui-state-highlight');
this._saveState();
this._fireReorderEvent();
},
_generateOptions: function() {
var $this = this;
this.list.children('.pui-orderlist-item').each(function() {
var item = $(this),
itemValue = item.data('item-value');
$this.element.append('<option value="' + itemValue + '" selected="selected">' + itemValue + '</option>');
});
},
_createItemContent: function(choice) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, choice);
}
else if(this.options.content) {
return this.options.content.call(this, choice);
}
else {
return choice.label;
}
}
});
})();/**
* PrimeUI Paginator Widget
*/
(function() {
var ElementHandlers = {
'{FirstPageLink}': {
markup: '<span class="pui-paginator-first pui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-step-backward"></span></span>',
create: function(paginator) {
var element = $(this.markup);
if(paginator.options.page === 0) {
element.addClass('ui-state-disabled');
}
element.on('click.puipaginator', function() {
if(!$(this).hasClass("ui-state-disabled")) {
paginator.option('page', 0);
}
});
return element;
},
update: function(element, state) {
if(state.page === 0) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
else {
element.removeClass('ui-state-disabled');
}
}
},
'{PreviousPageLink}': {
markup: '<span class="pui-paginator-prev pui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-backward"></span></span>',
create: function(paginator) {
var element = $(this.markup);
if(paginator.options.page === 0) {
element.addClass('ui-state-disabled');
}
element.on('click.puipaginator', function() {
if(!$(this).hasClass("ui-state-disabled")) {
paginator.option('page', paginator.options.page - 1);
}
});
return element;
},
update: function(element, state) {
if(state.page === 0) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
else {
element.removeClass('ui-state-disabled');
}
}
},
'{NextPageLink}': {
markup: '<span class="pui-paginator-next pui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-forward"></span></span>',
create: function(paginator) {
var element = $(this.markup);
if(paginator.options.page === (paginator.getPageCount() - 1)) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
element.on('click.puipaginator', function() {
if(!$(this).hasClass("ui-state-disabled")) {
paginator.option('page', paginator.options.page + 1);
}
});
return element;
},
update: function(element, state) {
if(state.page === (state.pageCount - 1)) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
else {
element.removeClass('ui-state-disabled');
}
}
},
'{LastPageLink}': {
markup: '<span class="pui-paginator-last pui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-step-forward"></span></span>',
create: function(paginator) {
var element = $(this.markup);
if(paginator.options.page === (paginator.getPageCount() - 1)) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
element.on('click.puipaginator', function() {
if(!$(this).hasClass("ui-state-disabled")) {
paginator.option('page', paginator.getPageCount() - 1);
}
});
return element;
},
update: function(element, state) {
if(state.page === (state.pageCount - 1)) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
else {
element.removeClass('ui-state-disabled');
}
}
},
'{PageLinks}': {
markup: '<span class="pui-paginator-pages"></span>',
create: function(paginator) {
var element = $(this.markup),
boundaries = this.calculateBoundaries({
page: paginator.options.page,
pageLinks: paginator.options.pageLinks,
pageCount: paginator.getPageCount()
}),
start = boundaries[0],
end = boundaries[1];
for(var i = start; i <= end; i++) {
var pageLinkNumber = (i + 1),
pageLinkElement = $('<span class="pui-paginator-page pui-paginator-element ui-state-default ui-corner-all">' + pageLinkNumber + "</span>");
if(i === paginator.options.page) {
pageLinkElement.addClass('ui-state-active');
}
pageLinkElement.on('click.puipaginator', function(e){
var link = $(this);
if(!link.hasClass('ui-state-disabled')&&!link.hasClass('ui-state-active')) {
paginator.option('page', parseInt(link.text(), 10) - 1);
}
});
element.append(pageLinkElement);
}
return element;
},
update: function(element, state, paginator) {
var pageLinks = element.children(),
boundaries = this.calculateBoundaries({
page: state.page,
pageLinks: state.pageLinks,
pageCount: state.pageCount
}),
start = boundaries[0],
end = boundaries[1];
pageLinks.remove();
for(var i = start; i <= end; i++) {
var pageLinkNumber = (i + 1),
pageLinkElement = $('<span class="pui-paginator-page pui-paginator-element ui-state-default ui-corner-all">' + pageLinkNumber + "</span>");
if(i === state.page) {
pageLinkElement.addClass('ui-state-active');
}
pageLinkElement.on('click.puipaginator', function(e){
var link = $(this);
if(!link.hasClass('ui-state-disabled')&&!link.hasClass('ui-state-active')) {
paginator.option('page', parseInt(link.text(), 10) - 1);
}
});
paginator._bindHover(pageLinkElement);
element.append(pageLinkElement);
}
},
calculateBoundaries: function(config) {
var page = config.page,
pageLinks = config.pageLinks,
pageCount = config.pageCount,
visiblePages = Math.min(pageLinks, pageCount);
//calculate range, keep current in middle if necessary
var start = Math.max(0, parseInt(Math.ceil(page - ((visiblePages) / 2)), 10)),
end = Math.min(pageCount - 1, start + visiblePages - 1);
//check when approaching to last page
var delta = pageLinks - (end - start + 1);
start = Math.max(0, start - delta);
return [start, end];
}
}
};
$.widget("primeui.puipaginator", {
options: {
pageLinks: 5,
totalRecords: 0,
page: 0,
rows: 0,
template: '{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}'
},
_create: function() {
this.element.addClass('pui-paginator ui-widget-header');
this.paginatorElements = [];
var elementKeys = this.options.template.split(/[ ]+/);
for(var i = 0; i < elementKeys.length;i++) {
var elementKey = elementKeys[i],
handler = ElementHandlers[elementKey];
if(handler) {
var paginatorElement = handler.create(this);
this.paginatorElements[elementKey] = paginatorElement;
this.element.append(paginatorElement);
}
}
this._bindEvents();
},
_bindEvents: function() {
this._bindHover(this.element.find('span.pui-paginator-element'));
},
_bindHover: function(elements) {
elements.on('mouseover.puipaginator', function() {
var el = $(this);
if(!el.hasClass('ui-state-active')&&!el.hasClass('ui-state-disabled')) {
el.addClass('ui-state-hover');
}
})
.on('mouseout.puipaginator', function() {
var el = $(this);
if(el.hasClass('ui-state-hover')) {
el.removeClass('ui-state-hover');
}
});
},
_setOption: function(key, value) {
if(key === 'page')
this.setPage(value);
else if(key === 'totalRecords')
this.setTotalRecords(value);
else
$.Widget.prototype._setOption.apply(this, arguments);
},
setPage: function(p, silent) {
var pc = this.getPageCount();
if(p >= 0 && p < pc) {
var newState = {
first: this.options.rows * p,
rows: this.options.rows,
page: p,
pageCount: pc,
pageLinks: this.options.pageLinks
};
this.options.page = p;
if(!silent) {
this._trigger('paginate', null, newState);
}
this.updateUI(newState);
}
},
//state contains page and totalRecords
setState: function(state) {
this.options.totalRecords = state.totalRecords;
this.setPage(state.page, true);
},
updateUI: function(state) {
for(var paginatorElementKey in this.paginatorElements) {
ElementHandlers[paginatorElementKey].update(this.paginatorElements[paginatorElementKey], state, this);
}
},
getPageCount: function() {
return Math.ceil(this.options.totalRecords / this.options.rows)||1;
},
setTotalRecords: function(value) {
this.options.totalRecords = value;
this.setPage(0, true);
}
});
})();/**
* PrimeUI Panel Widget
*/
(function() {
$.widget("primeui.puipanel", {
options: {
toggleable: false,
toggleDuration: 'normal',
toggleOrientation : 'vertical',
collapsed: false,
closable: false,
closeDuration: 'slow',
title: null
},
_create: function() {
this.element.addClass('pui-panel ui-widget ui-widget-content ui-corner-all')
.contents().wrapAll('<div class="pui-panel-content ui-widget-content" />');
var title = this.element.attr('title')||this.options.title;
if(title) {
this.element.prepend('<div class="pui-panel-titlebar ui-widget-header ui-helper-clearfix ui-corner-all"><span class="ui-panel-title">' +
title + "</span></div>").removeAttr('title');
}
this.header = this.element.children('div.pui-panel-titlebar');
this.title = this.header.children('span.ui-panel-title');
this.content = this.element.children('div.pui-panel-content');
var $this = this;
if(this.options.closable) {
this.closer = $('<a class="pui-panel-titlebar-icon ui-corner-all ui-state-default" href="#"><span class="pui-icon fa fa-fw fa-close"></span></a>')
.appendTo(this.header)
.on('click.puipanel', function(e) {
$this.close();
e.preventDefault();
});
}
if(this.options.toggleable) {
var icon = this.options.collapsed ? 'fa-plus' : 'fa-minus';
this.toggler = $('<a class="pui-panel-titlebar-icon ui-corner-all ui-state-default" href="#"><span class="pui-icon fa fa-fw ' + icon + '"></span></a>')
.appendTo(this.header)
.on('click.puipanel', function(e) {
$this.toggle();
e.preventDefault();
});
if(this.options.collapsed) {
this.content.hide();
}
}
this._bindEvents();
},
_bindEvents: function() {
this.header.find('a.pui-panel-titlebar-icon').on('mouseenter.puipanel', function() {
$(this).addClass('ui-state-hover');
})
.on('mouseleave.puipanel', function() {
$(this).removeClass('ui-state-hover');
});
},
close: function() {
var $this = this;
this._trigger('beforeClose', null);
this.element.fadeOut(this.options.closeDuration,
function() {
$this._trigger('afterClose', null);
}
);
},
toggle: function() {
if(this.options.collapsed) {
this.expand();
}
else {
this.collapse();
}
},
expand: function() {
this.toggler.children('.pui-icon').removeClass('fa-plus').addClass('fa-minus');
if(this.options.toggleOrientation === 'vertical') {
this._slideDown();
}
else if(this.options.toggleOrientation === 'horizontal') {
this._slideRight();
}
},
collapse: function() {
this.toggler.children('.pui-icon').removeClass('fa-minus').addClass('fa-plus');
if(this.options.toggleOrientation === 'vertical') {
this._slideUp();
}
else if(this.options.toggleOrientation === 'horizontal') {
this._slideLeft();
}
},
_slideUp: function() {
var $this = this;
this._trigger('beforeCollapse');
this.content.slideUp(this.options.toggleDuration, 'easeInOutCirc', function() {
$this._trigger('afterCollapse');
$this.options.collapsed = !$this.options.collapsed;
});
},
_slideDown: function() {
var $this = this;
this._trigger('beforeExpand');
this.content.slideDown(this.options.toggleDuration, 'easeInOutCirc', function() {
$this._trigger('afterExpand');
$this.options.collapsed = !$this.options.collapsed;
});
},
_slideLeft: function() {
var $this = this;
this.originalWidth = this.element.width();
this.title.hide();
this.toggler.hide();
this.content.hide();
this.element.animate({
width: '42px'
}, this.options.toggleSpeed, 'easeInOutCirc', function() {
$this.toggler.show();
$this.element.addClass('pui-panel-collapsed-h');
$this.options.collapsed = !$this.options.collapsed;
});
},
_slideRight: function() {
var $this = this,
expandWidth = this.originalWidth||'100%';
this.toggler.hide();
this.element.animate({
width: expandWidth
}, this.options.toggleSpeed, 'easeInOutCirc', function() {
$this.element.removeClass('pui-panel-collapsed-h');
$this.title.show();
$this.toggler.show();
$this.options.collapsed = !$this.options.collapsed;
$this.content.css({
'visibility': 'visible',
'display': 'block',
'height': 'auto'
});
});
}
});
})();/**
* PrimeUI password widget
*/
(function() {
$.widget("primeui.puipassword", {
options: {
promptLabel: 'Please enter a password',
weakLabel: 'Weak',
goodLabel: 'Medium',
strongLabel: 'Strong',
inline: false
},
_create: function() {
this.element.puiinputtext().addClass('pui-password');
if(!this.element.prop(':disabled')) {
var panelMarkup = '<div class="pui-password-panel ui-widget ui-state-highlight ui-corner-all ui-helper-hidden">';
panelMarkup += '<div class="pui-password-meter" style="background-position:0pt 0pt"> </div>';
panelMarkup += '<div class="pui-password-info">' + this.options.promptLabel + '</div>';
panelMarkup += '</div>';
this.panel = $(panelMarkup).insertAfter(this.element);
this.meter = this.panel.children('div.pui-password-meter');
this.infoText = this.panel.children('div.pui-password-info');
if(this.options.inline) {
this.panel.addClass('pui-password-panel-inline');
} else {
this.panel.addClass('pui-password-panel-overlay').appendTo('body');
}
this._bindEvents();
}
},
_destroy: function() {
this.panel.remove();
},
_bindEvents: function() {
var $this = this;
this.element.on('focus.puipassword', function() {
$this.show();
})
.on('blur.puipassword', function() {
$this.hide();
})
.on('keyup.puipassword', function() {
var value = $this.element.val(),
label = null,
meterPos = null;
if(value.length === 0) {
label = $this.options.promptLabel;
meterPos = '0px 0px';
}
else {
var score = $this._testStrength($this.element.val());
if(score < 30) {
label = $this.options.weakLabel;
meterPos = '0px -10px';
}
else if(score >= 30 && score < 80) {
label = $this.options.goodLabel;
meterPos = '0px -20px';
}
else if(score >= 80) {
label = $this.options.strongLabel;
meterPos = '0px -30px';
}
}
$this.meter.css('background-position', meterPos);
$this.infoText.text(label);
});
if(!this.options.inline) {
var resizeNS = 'resize.' + this.element.attr('id');
$(window).unbind(resizeNS).bind(resizeNS, function() {
if($this.panel.is(':visible')) {
$this.align();
}
});
}
},
_unbindEvents: function() {
this.element.off('focus.puipassword blur.puipassword keyup.puipassword');
},
_testStrength: function(str) {
var grade = 0,
val = 0,
$this = this;
val = str.match('[0-9]');
grade += $this._normalize(val ? val.length : 1/4, 1) * 25;
val = str.match('[a-zA-Z]');
grade += $this._normalize(val ? val.length : 1/2, 3) * 10;
val = str.match('[!@#$%^&*?_~.,;=]');
grade += $this._normalize(val ? val.length : 1/6, 1) * 35;
val = str.match('[A-Z]');
grade += $this._normalize(val ? val.length : 1/6, 1) * 30;
grade *= str.length / 8;
return grade > 100 ? 100 : grade;
},
_normalize: function(x, y) {
var diff = x - y;
if(diff <= 0) {
return x / y;
}
else {
return 1 + 0.5 * (x / (x + y/4));
}
},
align: function() {
this.panel.css({
left:'',
top:'',
'z-index': ++PUI.zindex
})
.position({
my: 'left top',
at: 'right top',
of: this.element
});
},
show: function() {
if(!this.options.inline) {
this.align();
this.panel.fadeIn();
}
else {
this.panel.slideDown();
}
},
hide: function() {
if(this.options.inline) {
this.panel.slideUp();
}
else {
this.panel.fadeOut();
}
},
disable: function () {
this.element.puiinputtext('disable');
this._unbindEvents();
},
enable: function () {
this.element.puiinputtext('enable');
this._bindEvents();
}
});
})();/**
* PrimeUI picklist widget
*/
(function() {
$.widget("primeui.puipicklist", {
options: {
effect: 'fade',
effectSpeed: 'fast',
sourceCaption: null,
targetCaption: null,
filter: false,
filterFunction: null,
filterMatchMode: 'startsWith',
dragdrop: true,
sourceData: null,
targetData: null,
content: null,
template: null,
responsive: false
},
_create: function() {
this.element.uniqueId().addClass('pui-picklist ui-widget ui-helper-clearfix');
if(this.options.responsive) {
this.element.addClass('pui-picklist-responsive');
}
this.inputs = this.element.children('select');
this.items = $();
this.sourceInput = this.inputs.eq(0);
this.targetInput = this.inputs.eq(1);
if(this.options.sourceData) {
this._populateInputFromData(this.sourceInput, this.options.sourceData);
}
if(this.options.targetData) {
this._populateInputFromData(this.targetInput, this.options.targetData);
}
this.sourceList = this._createList(this.sourceInput, 'pui-picklist-source', this.options.sourceCaption);
this._createButtons();
this.targetList = this._createList(this.targetInput, 'pui-picklist-target', this.options.targetCaption);
if(this.options.showSourceControls) {
this.element.prepend(this._createListControls(this.sourceList, 'pui-picklist-source-controls'));
}
if(this.options.showTargetControls) {
this.element.append(this._createListControls(this.targetList, 'pui-picklist-target-controls'));
}
this._bindEvents();
},
_populateInputFromData: function(input, data) {
for(var i = 0; i < data.length; i++) {
var choice = data[i];
if(choice.label)
input.append('<option value="' + choice.value + '">' + choice.label + '</option>');
else
input.append('<option value="' + choice + '">' + choice + '</option>');
}
},
_createList: function(input, cssClass, caption) {
var listWrapper = $('<div class="pui-picklist-listwrapper ' + cssClass + '-wrapper"></div>'),
listContainer = $('<ul class="ui-widget-content pui-picklist-list ' + cssClass + '"></ul>');
if(this.options.filter) {
listWrapper.append('<div class="pui-picklist-filter-container"><input type="text" class="pui-picklist-filter" /><span class="pui-icon fa fa-fw fa-search"></span></div>');
listWrapper.find('> .pui-picklist-filter-container > input').puiinputtext();
}
if(caption) {
listWrapper.append('<div class="pui-picklist-caption ui-widget-header ui-corner-tl ui-corner-tr">' + caption + '</div>');
listContainer.addClass('ui-corner-bottom');
}
else {
listContainer.addClass('ui-corner-all');
}
this._populateContainerFromOptions(input, listContainer);
listWrapper.append(listContainer);
input.addClass('ui-helper-hidden').appendTo(listWrapper);
listWrapper.appendTo(this.element);
return listContainer;
},
_populateContainerFromOptions: function(input, listContainer, data) {
var choices = input.children('option');
for(var i = 0; i < choices.length; i++) {
var choice = choices.eq(i),
content = this._createItemContent(choice.get(0)),
item = $('<li class="pui-picklist-item ui-corner-all"></li>').data({
'item-label': choice.text(),
'item-value': choice.val()
});
if($.type(content) === 'string')
item.html(content);
else
item.append(content);
this.items = this.items.add(item);
listContainer.append(item);
}
},
_createButtons: function() {
var $this = this,
buttonContainer = $('<div class="pui-picklist-buttons"><div class="pui-picklist-buttons-cell"></div>');
buttonContainer.children('div').append(this._createButton('fa-angle-right', 'pui-picklist-button-add', function(){$this._add();}))
.append(this._createButton('fa-angle-double-right', 'pui-picklist-button-addall', function(){$this._addAll();}))
.append(this._createButton('fa-angle-left', 'pui-picklist-button-remove', function(){$this._remove();}))
.append(this._createButton('fa-angle-double-left', 'pui-picklist-button-removeall', function(){$this._removeAll();}));
this.element.append(buttonContainer);
},
_createListControls: function(list, cssClass) {
var $this = this,
buttonContainer = $('<div class="' + cssClass + ' pui-picklist-buttons"><div class="pui-picklist-buttons-cell"></div>');
buttonContainer.children('div').append(this._createButton('fa-angle-up', 'pui-picklist-button-move-up', function(){$this._moveUp(list);}))
.append(this._createButton('fa-angle-double-up', 'pui-picklist-button-move-top', function(){$this._moveTop(list);}))
.append(this._createButton('fa-angle-down', 'pui-picklist-button-move-down', function(){$this._moveDown(list);}))
.append(this._createButton('fa-angle-double-down', 'pui-picklist-button-move-bottom', function(){$this._moveBottom(list);}));
return buttonContainer;
},
_createButton: function(icon, cssClass, fn) {
var btn = $('<button class="' + cssClass + '" type="button"></button>').puibutton({
'icon': icon,
'click': function() {
fn();
$(this).removeClass('ui-state-hover ui-state-focus');
}
});
return btn;
},
_bindEvents: function() {
var $this = this;
this.items.on('mouseover.puipicklist', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
$(this).addClass('ui-state-hover');
}
})
.on('mouseout.puipicklist', function(e) {
$(this).removeClass('ui-state-hover');
})
.on('click.puipicklist', function(e) {
var item = $(this),
metaKey = (e.metaKey||e.ctrlKey);
if(!e.shiftKey) {
if(!metaKey) {
$this.unselectAll();
}
if(metaKey && item.hasClass('ui-state-highlight')) {
$this.unselectItem(item);
}
else {
$this.selectItem(item);
$this.cursorItem = item;
}
}
else {
$this.unselectAll();
if($this.cursorItem && ($this.cursorItem.parent().is(item.parent()))) {
var currentItemIndex = item.index(),
cursorItemIndex = $this.cursorItem.index(),
startIndex = (currentItemIndex > cursorItemIndex) ? cursorItemIndex : currentItemIndex,
endIndex = (currentItemIndex > cursorItemIndex) ? (currentItemIndex + 1) : (cursorItemIndex + 1),
parentList = item.parent();
for(var i = startIndex ; i < endIndex; i++) {
$this.selectItem(parentList.children('li.ui-picklist-item').eq(i));
}
}
else {
$this.selectItem(item);
$this.cursorItem = item;
}
}
})
.on('dblclick.pickList', function() {
var item = $(this);
if($(this).closest('.pui-picklist-listwrapper').hasClass('pui-picklist-source'))
$this._transfer(item, $this.sourceList, $this.targetList, 'dblclick');
else
$this._transfer(item, $this.targetList, $this.sourceList, 'dblclick');
PUI.clearSelection();
});
if(this.options.filter) {
this._setupFilterMatcher();
this.element.find('> .pui-picklist-source-wrapper > .pui-picklist-filter-container > input').on('keyup', function(e) {
$this._filter(this.value, $this.sourceList);
});
this.element.find('> .pui-picklist-target-wrapper > .pui-picklist-filter-container > input').on('keyup', function(e) {
$this._filter(this.value, $this.targetList);
});
}
if(this.options.dragdrop) {
this.element.find('> .pui-picklist-listwrapper > ul.pui-picklist-list').sortable({
cancel: '.ui-state-disabled',
connectWith: '#' + this.element.attr('id') + ' .pui-picklist-list',
revert: 1,
update: function(event, ui) {
$this.unselectItem(ui.item);
$this._saveState();
},
receive: function(event, ui) {
$this._triggerTransferEvent(ui.item, ui.sender, ui.item.closest('ul.pui-picklist-list'), 'dragdrop');
}
});
}
},
selectItem: function(item) {
item.removeClass('ui-state-hover').addClass('ui-state-highlight');
},
unselectItem: function(item) {
item.removeClass('ui-state-highlight');
},
unselectAll: function() {
var selectedItems = this.items.filter('.ui-state-highlight');
for(var i = 0; i < selectedItems.length; i++) {
this.unselectItem(selectedItems.eq(i));
}
},
_add: function() {
var items = this.sourceList.children('li.pui-picklist-item.ui-state-highlight');
this._transfer(items, this.sourceList, this.targetList, 'command');
},
_addAll: function() {
var items = this.sourceList.children('li.pui-picklist-item:visible:not(.ui-state-disabled)');
this._transfer(items, this.sourceList, this.targetList, 'command');
},
_remove: function() {
var items = this.targetList.children('li.pui-picklist-item.ui-state-highlight');
this._transfer(items, this.targetList, this.sourceList, 'command');
},
_removeAll: function() {
var items = this.targetList.children('li.pui-picklist-item:visible:not(.ui-state-disabled)');
this._transfer(items, this.targetList, this.sourceList, 'command');
},
_moveUp: function(list) {
var $this = this,
animated = $this.options.effect,
items = list.children('.ui-state-highlight'),
itemsCount = items.length,
movedCount = 0;
items.each(function() {
var item = $(this);
if(!item.is(':first-child')) {
if(animated) {
item.hide($this.options.effect, {}, $this.options.effectSpeed, function() {
item.insertBefore(item.prev()).show($this.options.effect, {}, $this.options.effectSpeed, function() {
movedCount++;
if(movedCount === itemsCount) {
$this._saveState();
}
});
});
}
else {
item.hide().insertBefore(item.prev()).show();
}
}
});
if(!animated) {
this._saveState();
}
},
_moveTop: function(list) {
var $this = this,
animated = $this.options.effect,
items = list.children('.ui-state-highlight'),
itemsCount = items.length,
movedCount = 0;
list.children('.ui-state-highlight').each(function() {
var item = $(this);
if(!item.is(':first-child')) {
if(animated) {
item.hide($this.options.effect, {}, $this.options.effectSpeed, function() {
item.prependTo(item.parent()).show($this.options.effect, {}, $this.options.effectSpeed, function(){
movedCount++;
if(movedCount === itemsCount) {
$this._saveState();
}
});
});
}
else {
item.hide().prependTo(item.parent()).show();
}
}
});
if(!animated) {
this._saveState();
}
},
_moveDown: function(list) {
var $this = this,
animated = $this.options.effect,
items = list.children('.ui-state-highlight'),
itemsCount = items.length,
movedCount = 0;
$(list.children('.ui-state-highlight').get().reverse()).each(function() {
var item = $(this);
if(!item.is(':last-child')) {
if(animated) {
item.hide($this.options.effect, {}, $this.options.effectSpeed, function() {
item.insertAfter(item.next()).show($this.options.effect, {}, $this.options.effectSpeed, function() {
movedCount++;
if(movedCount === itemsCount) {
$this._saveState();
}
});
});
}
else {
item.hide().insertAfter(item.next()).show();
}
}
});
if(!animated) {
this._saveState();
}
},
_moveBottom: function(list) {
var $this = this,
animated = $this.options.effect,
items = list.children('.ui-state-highlight'),
itemsCount = items.length,
movedCount = 0;
list.children('.ui-state-highlight').each(function() {
var item = $(this);
if(!item.is(':last-child')) {
if(animated) {
item.hide($this.options.effect, {}, $this.options.effectSpeed, function() {
item.appendTo(item.parent()).show($this.options.effect, {}, $this.options.effectSpeed, function() {
movedCount++;
if(movedCount === itemsCount) {
$this._saveState();
}
});
});
}
else {
item.hide().appendTo(item.parent()).show();
}
}
});
if(!animated) {
this._saveState();
}
},
_transfer: function(items, from, to, type) {
var $this = this,
itemsCount = items.length,
transferCount = 0;
if(this.options.effect) {
items.hide(this.options.effect, {}, this.options.effectSpeed, function() {
var item = $(this);
$this.unselectItem(item);
item.appendTo(to).show($this.options.effect, {}, $this.options.effectSpeed, function() {
transferCount++;
if(transferCount === itemsCount) {
$this._saveState();
$this._triggerTransferEvent(items, from, to, type);
}
});
});
}
else {
items.hide().removeClass('ui-state-highlight ui-state-hover').appendTo(to).show();
this._saveState();
this._triggerTransferEvent(items, from, to, type);
}
},
_triggerTransferEvent: function(items, from, to, type) {
var obj = {};
obj.items = items;
obj.from = from;
obj.to = to;
obj.type = type;
this._trigger('transfer', null, obj);
},
_saveState: function() {
this.sourceInput.children().remove();
this.targetInput.children().remove();
this._generateItems(this.sourceList, this.sourceInput);
this._generateItems(this.targetList, this.targetInput);
this.cursorItem = null;
},
_generateItems: function(list, input) {
list.children('.pui-picklist-item').each(function() {
var item = $(this),
itemValue = item.data('item-value'),
itemLabel = item.data('item-label');
input.append('<option value="' + itemValue + '" selected="selected">' + itemLabel + '</option>');
});
},
_setupFilterMatcher: function() {
this.filterMatchers = {
'startsWith': this._startsWithFilter,
'contains': this._containsFilter,
'endsWith': this._endsWithFilter,
'custom': this.options.filterFunction
};
this.filterMatcher = this.filterMatchers[this.options.filterMatchMode];
},
_filter: function(value, list) {
var filterValue = $.trim(value).toLowerCase(),
items = list.children('li.pui-picklist-item');
if(filterValue === '') {
items.filter(':hidden').show();
}
else {
for(var i = 0; i < items.length; i++) {
var item = items.eq(i),
itemLabel = item.data('item-label');
if(this.filterMatcher(itemLabel, filterValue))
item.show();
else
item.hide();
}
}
},
_startsWithFilter: function(value, filter) {
return value.toLowerCase().indexOf(filter) === 0;
},
_containsFilter: function(value, filter) {
return value.toLowerCase().indexOf(filter) !== -1;
},
_endsWithFilter: function(value, filter) {
return value.indexOf(filter, value.length - filter.length) !== -1;
},
_setOption: function (key, value) {
$.Widget.prototype._setOption.apply(this, arguments);
if (key === 'sourceData') {
this._setOptionData(this.sourceInput, this.sourceList, this.options.sourceData);
}
if (key === 'targetData') {
this._setOptionData(this.targetInput, this.targetList, this.options.targetData);
}
},
_setOptionData: function(input, listContainer, data) {
input.empty();
listContainer.empty();
this._populateInputFromData(input, data);
this._populateContainerFromOptions(input, listContainer, data);
this._bindEvents();
},
_unbindEvents: function() {
this.items.off("mouseover.puipicklist mouseout.puipicklist click.puipicklist dblclick.pickList");
},
disable: function () {
this._unbindEvents();
this.items.addClass('ui-state-disabled');
this.element.find('.pui-picklist-buttons > button').each(function (idx, btn) {
$(btn).puibutton('disable');
});
},
enable: function () {
this._bindEvents();
this.items.removeClass('ui-state-disabled');
this.element.find('.pui-picklist-buttons > button').each(function (idx, btn) {
$(btn).puibutton('enable');
});
},
_createItemContent: function(choice) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, choice);
}
else if(this.options.content) {
return this.options.content.call(this, choice);
}
else {
return choice.label;
}
}
});
})();/**
* PrimeUI progressbar widget
*/
(function() {
$.widget("primeui.puiprogressbar", {
options: {
value: 0,
labelTemplate: '{value}%',
complete: null,
easing: 'easeInOutCirc',
effectSpeed: 'normal',
showLabel: true
},
_create: function() {
this.element.addClass('pui-progressbar ui-widget ui-widget-content ui-corner-all')
.append('<div class="pui-progressbar-value ui-widget-header ui-corner-all"></div>')
.append('<div class="pui-progressbar-label"></div>');
this.jqValue = this.element.children('.pui-progressbar-value');
this.jqLabel = this.element.children('.pui-progressbar-label');
if(this.options.value !==0) {
this._setValue(this.options.value, false);
}
this.enableARIA();
},
_setValue: function(value, animate) {
var anim = (animate === undefined || animate) ? true : false;
if(value >= 0 && value <= 100) {
if(value === 0) {
this.jqValue.hide().css('width', '0%').removeClass('ui-corner-right');
this.jqLabel.hide();
}
else {
if(anim) {
this.jqValue.show().animate({
'width': value + '%'
}, this.options.effectSpeed, this.options.easing);
}
else {
this.jqValue.show().css('width', value + '%');
}
if(this.options.labelTemplate && this.options.showLabel) {
var formattedLabel = this.options.labelTemplate.replace(/{value}/gi, value);
this.jqLabel.html(formattedLabel).show();
}
if(value === 100) {
this._trigger('complete');
}
}
this.options.value = value;
this.element.attr('aria-valuenow', value);
}
},
_getValue: function() {
return this.options.value;
},
enableARIA: function() {
this.element.attr('role', 'progressbar')
.attr('aria-valuemin', 0)
.attr('aria-valuenow', this.options.value)
.attr('aria-valuemax', 100);
},
_setOption: function(key, value) {
if(key === 'value') {
this._setValue(value);
}
$.Widget.prototype._setOption.apply(this, arguments);
},
_destroy: function() {
}
});
})();/**
* PrimeUI radiobutton widget
*/
(function() {
var checkedRadios = {};
$.widget("primeui.puiradiobutton", {
_create: function() {
this.element.wrap('<div class="pui-radiobutton ui-widget"><div class="ui-helper-hidden-accessible"></div></div>');
this.container = this.element.parent().parent();
this.box = $('<div class="pui-radiobutton-box ui-widget pui-radiobutton-relative ui-state-default">').appendTo(this.container);
this.icon = $('<span class="pui-radiobutton-icon pui-icon"></span>').appendTo(this.box);
this.disabled = this.element.prop('disabled');
this.label = $('label[for="' + this.element.attr('id') + '"]');
if(this.element.prop('checked')) {
this.box.addClass('ui-state-active');
this.icon.addClass('fa fa-fw fa-circle');
checkedRadios[this.element.attr('name')] = this.box;
}
if(this.disabled) {
this.box.addClass('ui-state-disabled');
} else {
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.box.on('mouseover.puiradiobutton', function() {
if(!$this._isChecked())
$this.box.addClass('ui-state-hover');
}).on('mouseout.puiradiobutton', function() {
if(!$this._isChecked())
$this.box.removeClass('ui-state-hover');
}).on('click.puiradiobutton', function() {
if(!$this._isChecked()) {
$this.element.trigger('click');
if(PUI.browser.msie && parseInt(PUI.browser.version, 10) < 9) {
$this.element.trigger('change');
}
}
});
if(this.label.length > 0) {
this.label.on('click.puiradiobutton', function(e) {
$this.element.trigger('click');
e.preventDefault();
});
}
this.element.focus(function() {
if($this._isChecked()) {
$this.box.removeClass('ui-state-active');
}
$this.box.addClass('ui-state-focus');
})
.blur(function() {
if($this._isChecked()) {
$this.box.addClass('ui-state-active');
}
$this.box.removeClass('ui-state-focus');
})
.change(function(e) {
var name = $this.element.attr('name');
if(checkedRadios[name]) {
checkedRadios[name].removeClass('ui-state-active ui-state-focus ui-state-hover').children('.pui-radiobutton-icon').removeClass('fa fa-fw fa-circle');
}
$this.icon.addClass('fa fa-fw fa-circle');
if(!$this.element.is(':focus')) {
$this.box.addClass('ui-state-active');
}
checkedRadios[name] = $this.box;
$this._trigger('change', null);
});
},
_isChecked: function() {
return this.element.prop('checked');
},
_unbindEvents: function () {
this.box.off();
if (this.label.length > 0) {
this.label.off();
}
},
enable: function () {
this._bindEvents();
this.box.removeClass('ui-state-disabled');
},
disable: function () {
this._unbindEvents();
this.box.addClass('ui-state-disabled');
}
});
})();/**
* PrimeUI rating widget
*/
(function() {
$.widget("primeui.puirating", {
options: {
stars: 5,
cancel: true,
readonly: false,
disabled: false
},
_create: function() {
var input = this.element;
input.wrap('<div />');
this.container = input.parent();
this.container.addClass('pui-rating');
var inputVal = input.val(),
value = inputVal === '' ? null : parseInt(inputVal, 10);
if(this.options.cancel) {
this.container.append('<div class="pui-rating-cancel"><a></a></div>');
}
for(var i = 0; i < this.options.stars; i++) {
var styleClass = (value > i) ? "pui-rating-star pui-rating-star-on" : "pui-rating-star";
this.container.append('<div class="' + styleClass + '"><a></a></div>');
}
this.stars = this.container.children('.pui-rating-star');
if(input.prop('disabled')||this.options.disabled) {
this.container.addClass('ui-state-disabled');
}
else if(!input.prop('readonly')&&!this.options.readonly){
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.stars.click(function() {
var value = $this.stars.index(this) + 1; //index starts from zero
$this.setValue(value);
});
this.container.children('.pui-rating-cancel').hover(function() {
$(this).toggleClass('pui-rating-cancel-hover');
})
.click(function() {
$this.cancel();
});
},
cancel: function() {
this.element.val('');
this.stars.filter('.pui-rating-star-on').removeClass('pui-rating-star-on');
this._trigger('oncancel', null);
},
getValue: function() {
var inputVal = this.element.val();
return inputVal === '' ? null : parseInt(inputVal, 10);
},
setValue: function(value) {
this.element.val(value);
//update visuals
this.stars.removeClass('pui-rating-star-on');
for(var i = 0; i < value; i++) {
this.stars.eq(i).addClass('pui-rating-star-on');
}
this._trigger('rate', null, value);
},
enable: function() {
this.container.removeClass('ui-state-disabled');
this._bindEvents();
},
disable: function() {
this.container.addClass('ui-state-disabled');
this._unbindEvents();
},
_unbindEvents: function() {
this.stars.off('click');
this.container.children('.pui-rating-cancel').off('hover click');
}
});
})();(function() {
$.widget("primeui.puiselectbutton", {
options: {
choices: null,
formfield: null,
unselectable: false,
tabindex: '0',
multiple: false
},
_create: function() {
this.element.addClass('pui-selectbutton pui-buttonset ui-widget ui-corner-all').attr('tabindex');
//create buttons
if(this.options.choices) {
this.element.addClass('pui-buttonset-' + this.options.choices.length);
for(var i = 0; i < this.options.choices.length; i++) {
this.element.append('<div class="pui-button ui-widget ui-state-default pui-button-text-only" tabindex="' + this.options.tabindex + '" data-value="'
+ this.options.choices[i].value + '">' +
'<span class="pui-button-text ui-c">' +
this.options.choices[i].label +
'</span></div>');
}
}
//cornering
this.buttons = this.element.children('div.pui-button');
this.buttons.filter(':first-child').addClass('ui-corner-left');
this.buttons.filter(':last-child').addClass('ui-corner-right');
//Single Select Button Or Multiple Select Button Decision
if(!this.options.multiple) {
this.input = $('<input type="hidden"></input>').appendTo(this.element);
}
else {
this.input = $('<select class="ui-helper-hidden-accessible" multiple></select>').appendTo(this.element);
for (var i = 0; i < this.options.choices.length; i++) {
var selectOption = '<option value = "'+ this.options.choices[i].value +'"></option>';
this.input.append(selectOption);
}
this.selectOptions = this.input.children('option');
}
if(this.options.formfield) {
this.input.attr('name', this.options.formfield);
}
this._bindEvents();
},
_bindEvents: function() {
var $this = this;
this.buttons.on('mouseover', function() {
var btn = $(this);
if(!btn.hasClass('ui-state-active')) {
btn.addClass('ui-state-hover');
}
})
.on('mouseout', function() {
$(this).removeClass('ui-state-hover');
})
.on('click', function(e) {
var btn = $(this);
if($(this).hasClass("ui-state-active")) {
if($this.options.unselectable) {
$this.unselectOption(btn);
$this._trigger('change', e);
}
}
else {
if($this.options.multiple) {
$this.selectOption(btn);
}
else {
$this.unselectOption(btn.siblings('.ui-state-active'));
$this.selectOption(btn);
}
$this._trigger('change', e);
}
})
.on('focus', function() {
$(this).addClass('ui-state-focus');
})
.on('blur', function() {
$(this).removeClass('ui-state-focus');
})
.on('keydown', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.ENTER) {
$this.element.trigger('click');
e.preventDefault();
}
})
.on('keydown', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE||e.which === keyCode.ENTER||e.which === keyCode.NUMPAD_ENTER) {
$(this).trigger('click');
e.preventDefault();
}
});
},
selectOption: function(value) {
var btn = $.isNumeric(value) ? this.element.children('.pui-button').eq(value) : value;
if(this.options.multiple)
this.selectOptions.eq(btn.index()).prop('selected',true);
else
this.input.val(btn.data('value'));
btn.addClass('ui-state-active');
},
unselectOption: function(value){
var btn = $.isNumeric(value) ? this.element.children('.pui-button').eq(value) : value;
if(this.options.multiple)
this.selectOptions.eq(btn.index()).prop('selected',false);
else
this.input.val('');
btn.removeClass('ui-state-active');
btn.removeClass('ui-state-focus');
}
});
})();
/**
* PrimeUI spinner widget
*/
(function() {
$.widget("primeui.puispinner", {
options: {
step: 1.0,
min: undefined,
max: undefined,
prefix: null,
suffix: null
},
_create: function() {
var input = this.element,
disabled = input.prop('disabled');
input.puiinputtext().addClass('pui-spinner-input').wrap('<span class="pui-spinner ui-widget ui-corner-all" />');
this.wrapper = input.parent();
this.wrapper.append('<a class="pui-spinner-button pui-spinner-up ui-corner-tr pui-button ui-widget ui-state-default pui-button-text-only"><span class="pui-button-text"><span class="pui-icon fa fa-fw fa-caret-up"></span></span></a><a class="pui-spinner-button pui-spinner-down ui-corner-br pui-button ui-widget ui-state-default pui-button-text-only"><span class="pui-button-text"><span class="pui-icon fa fa-fw fa-caret-down"></span></span></a>');
this.upButton = this.wrapper.children('a.pui-spinner-up');
this.downButton = this.wrapper.children('a.pui-spinner-down');
this.options.step = this.options.step||1;
if(parseInt(this.options.step, 10) === 0) {
this.options.precision = this.options.step.toString().split(/[,]|[.]/)[1].length;
}
this._initValue();
if(!disabled&&!input.prop('readonly')) {
this._bindEvents();
}
if(disabled) {
this.wrapper.addClass('ui-state-disabled');
}
//aria
input.attr({
'role': 'spinner',
'aria-multiline': false,
'aria-valuenow': this.value
});
if(this.options.min !== undefined) {
input.attr('aria-valuemin', this.options.min);
}
if(this.options.max !== undefined){
input.attr('aria-valuemax', this.options.max);
}
if(input.prop('disabled')) {
input.attr('aria-disabled', true);
}
if(input.prop('readonly')) {
input.attr('aria-readonly', true);
}
},
_bindEvents: function() {
var $this = this;
//visuals for spinner buttons
this.wrapper.children('.pui-spinner-button')
.mouseover(function() {
$(this).addClass('ui-state-hover');
}).mouseout(function() {
$(this).removeClass('ui-state-hover ui-state-active');
if($this.timer) {
window.clearInterval($this.timer);
}
}).mouseup(function() {
window.clearInterval($this.timer);
$(this).removeClass('ui-state-active').addClass('ui-state-hover');
}).mousedown(function(e) {
var element = $(this),
dir = element.hasClass('pui-spinner-up') ? 1 : -1;
element.removeClass('ui-state-hover').addClass('ui-state-active');
if($this.element.is(':not(:focus)')) {
$this.element.focus();
}
$this._repeat(null, dir);
//keep focused
e.preventDefault();
});
this.element.keydown(function (e) {
var keyCode = $.ui.keyCode;
switch(e.which) {
case keyCode.UP:
$this._spin($this.options.step);
break;
case keyCode.DOWN:
$this._spin(-1 * $this.options.step);
break;
default:
//do nothing
break;
}
})
.keyup(function () {
$this._updateValue();
})
.blur(function () {
$this._format();
})
.focus(function () {
//remove formatting
$this.element.val($this.value);
});
//mousewheel
this.element.bind('mousewheel', function(event, delta) {
if($this.element.is(':focus')) {
if(delta > 0) {
$this._spin($this.options.step);
}
else {
$this._spin(-1 * $this.options.step);
}
return false;
}
});
},
_repeat: function(interval, dir) {
var $this = this,
i = interval || 500;
window.clearTimeout(this.timer);
this.timer = window.setTimeout(function() {
$this._repeat(40, dir);
}, i);
this._spin(this.options.step * dir);
},
_toFixed: function (value, precision) {
var power = Math.pow(10, precision||0);
return String(Math.round(value * power) / power);
},
_spin: function(step) {
var newValue,
currentValue = this.value ? this.value : 0;
if(this.options.precision) {
newValue = parseFloat(this._toFixed(currentValue + step, this.options.precision));
}
else {
newValue = parseInt(currentValue + step, 10);
}
if(this.options.min !== undefined && newValue < this.options.min) {
newValue = this.options.min;
}
if(this.options.max !== undefined && newValue > this.options.max) {
newValue = this.options.max;
}
this.element.val(newValue).attr('aria-valuenow', newValue);
this.value = newValue;
this.element.trigger('change');
},
_updateValue: function() {
var value = this.element.val();
if(value === '') {
if(this.options.min !== undefined) {
this.value = this.options.min;
}
else {
this.value = 0;
}
}
else {
if(this.options.step) {
value = parseFloat(value);
}
else {
value = parseInt(value, 10);
}
if(!isNaN(value)) {
this.value = value;
}
}
},
_initValue: function() {
var value = this.element.val();
if(value === '') {
if(this.options.min !== undefined) {
this.value = this.options.min;
}
else {
this.value = 0;
}
}
else {
if(this.options.prefix) {
value = value.split(this.options.prefix)[1];
}
if(this.options.suffix) {
value = value.split(this.options.suffix)[0];
}
if(this.options.step) {
this.value = parseFloat(value);
}
else {
this.value = parseInt(value, 10);
}
}
},
_format: function() {
var value = this.value;
if(this.options.prefix) {
value = this.options.prefix + value;
}
if(this.options.suffix) {
value = value + this.options.suffix;
}
this.element.val(value);
},
_unbindEvents: function() {
//visuals for spinner buttons
this.wrapper.children('.pui-spinner-button').off();
this.element.off();
},
enable: function() {
this.wrapper.removeClass('ui-state-disabled');
this.element.puiinputtext('enable');
this._bindEvents();
},
disable: function() {
this.wrapper.addClass('ui-state-disabled');
this.element.puiinputtext('disable');
this._unbindEvents();
}
});
})();/**
* PrimeFaces SplitButton Widget
*/
(function() {
$.widget("primeui.puisplitbutton", {
options: {
icon: null,
iconPos: 'left',
items: null
},
_create: function() {
this.element.wrap('<div class="pui-splitbutton pui-buttonset ui-widget"></div>');
this.container = this.element.parent().uniqueId();
this.menuButton = this.container.append('<button class="pui-splitbutton-menubutton" type="button"></button>').children('.pui-splitbutton-menubutton');
this.options.disabled = this.element.prop('disabled');
if(this.options.disabled) {
this.menuButton.prop('disabled', true);
}
this.element.puibutton(this.options).removeClass('ui-corner-all').addClass('ui-corner-left');
this.menuButton.puibutton({
icon: 'fa-caret-down'
}).removeClass('ui-corner-all').addClass('ui-corner-right');
if(this.options.items && this.options.items.length) {
this._renderPanel();
this._bindEvents();
}
},
_renderPanel: function() {
this.menu = $('<div class="pui-menu pui-menu-dynamic ui-widget ui-widget-content ui-corner-all ui-helper-clearfix pui-shadow"></div>').
append('<ul class="pui-menu-list ui-helper-reset"></ul>');
this.menuList = this.menu.children('.pui-menu-list');
for(var i = 0; i < this.options.items.length; i++) {
var item = this.options.items[i],
menuitem = $('<li class="pui-menuitem ui-widget ui-corner-all" role="menuitem"></li>'),
link = $('<a class="pui-menuitem-link ui-corner-all"><span class="pui-menuitem-icon fa fa-fw ' + item.icon +'"></span><span class="pui-menuitem-text">' + item.text +'</span></a>');
if(item.url) {
link.attr('href', item.url);
}
if(item.click) {
link.on('click.puisplitbutton', item.click);
}
menuitem.append(link).appendTo(this.menuList);
}
this.menu.appendTo(this.options.appendTo||this.container);
this.options.position = {
my: 'left top',
at: 'left bottom',
of: this.element.parent()
};
},
_bindEvents: function() {
var $this = this;
this.menuButton.on('click.puisplitbutton', function() {
if($this.menu.is(':hidden'))
$this.show();
else
$this.hide();
});
this.menuList.children().on('mouseover.puisplitbutton', function(e) {
$(this).addClass('ui-state-hover');
}).on('mouseout.puisplitbutton', function(e) {
$(this).removeClass('ui-state-hover');
}).on('click.puisplitbutton', function() {
$this.hide();
});
$(document.body).bind('mousedown.' + this.container.attr('id'), function (e) {
if($this.menu.is(":hidden")) {
return;
}
var target = $(e.target);
if(target.is($this.element)||$this.element.has(target).length > 0) {
return;
}
var offset = $this.menu.offset();
if(e.pageX < offset.left ||
e.pageX > offset.left + $this.menu.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.menu.height()) {
$this.element.removeClass('ui-state-focus ui-state-hover');
$this.hide();
}
});
var resizeNS = 'resize.' + this.container.attr('id');
$(window).unbind(resizeNS).bind(resizeNS, function() {
if($this.menu.is(':visible')) {
$this._alignPanel();
}
});
},
show: function() {
this.menuButton.trigger('focus');
this.menu.show();
this._alignPanel();
this._trigger('show', null);
},
hide: function() {
this.menuButton.removeClass('ui-state-focus');
this.menu.fadeOut('fast');
this._trigger('hide', null);
},
_alignPanel: function() {
this.menu.css({left:'', top:'','z-index': ++PUI.zindex}).position(this.options.position);
},
disable: function() {
this.element.puibutton('disable');
this.menuButton.puibutton('disable');
},
enable: function() {
this.element.puibutton('enable');
this.menuButton.puibutton('enable');
}
});
})();/**
* PrimeUI sticky widget
*/
(function() {
$.widget("primeui.puisticky", {
_create: function() {
this.initialState = {
top: this.element.offset().top,
height: this.element.height()
};
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this._bindEvents();
},
_bindEvents: function() {
var $this = this,
win = $(window),
scrollNS = 'scroll.' + this.id,
resizeNS = 'resize.' + this.id;
win.off(scrollNS).on(scrollNS, function() {
if(win.scrollTop() > $this.initialState.top)
$this._fix();
else
$this._restore();
})
.off(resizeNS).on(resizeNS, function() {
if($this.fixed) {
$this.element.width($this.ghost.outerWidth() - ($this.element.outerWidth() - $this.element.width()));
}
});
},
_fix: function() {
if(!this.fixed) {
this.element.css({
'position': 'fixed',
'top': 0,
'z-index': 10000
})
.addClass('pui-shadow pui-sticky');
this.ghost = $('<div class="pui-sticky-ghost"></div>').height(this.initialState.height).insertBefore(this.element);
this.element.width(this.ghost.outerWidth() - (this.element.outerWidth() - this.element.width()));
this.fixed = true;
}
},
_restore: function() {
if(this.fixed) {
this.element.css({
position: 'static',
top: 'auto',
width: 'auto'
})
.removeClass('pui-shadow pui-sticky');
this.ghost.remove();
this.fixed = false;
}
}
});
})();(function() {
$.widget("primeui.puiswitch", {
options: {
onLabel: 'On',
offLabel: 'Off',
change: null
},
_create: function() {
this.element.wrap('<div class="pui-inputswitch ui-widget ui-widget-content ui-corner-all"></div>');
this.container = this.element.parent();
this.element.wrap('<div class="ui-helper-hidden-accessible"></div>');
this.container.prepend('<div class="pui-inputswitch-off"></div>' +
'<div class="pui-inputswitch-on ui-state-active"></div>' +
'<div class="pui-inputswitch-handle ui-state-default"></div>');
this.onContainer = this.container.children('.pui-inputswitch-on');
this.offContainer = this.container.children('.pui-inputswitch-off');
this.onContainer.append('<span>'+ this.options.onLabel +'</span>');
this.offContainer.append('<span>'+ this.options.offLabel +'</span>');
this.onLabel = this.onContainer.children('span');
this.offLabel = this.offContainer.children('span');
this.handle = this.container.children('.pui-inputswitch-handle');
var onContainerWidth = this.onContainer.width(),
offContainerWidth = this.offContainer.width(),
spanPadding = this.offLabel.innerWidth() - this.offLabel.width(),
handleMargins = this.handle.outerWidth() - this.handle.innerWidth();
var containerWidth = (onContainerWidth > offContainerWidth) ? onContainerWidth : offContainerWidth,
handleWidth = containerWidth;
this.handle.css({'width':handleWidth});
handleWidth = this.handle.width();
containerWidth = containerWidth + handleWidth + 6;
var labelWidth = containerWidth - handleWidth - spanPadding - handleMargins;
this.container.css({'width': containerWidth });
this.onLabel.width(labelWidth);
this.offLabel.width(labelWidth);
//position
this.offContainer.css({ width: this.container.width() - 5 });
this.offset = this.container.width() - this.handle.outerWidth();
if(this.element.prop('checked')) {
this.handle.css({ 'left': this.offset});
this.onContainer.css({ 'width': this.offset});
this.offLabel.css({ 'margin-right': -this.offset});
}
else {
this.onContainer.css({ 'width': 0 });
this.onLabel.css({'margin-left': -this.offset});
}
if(!this.element.prop('disabled')) {
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.container.on('click.inputSwitch', function(e) {
$this.toggle();
$this.element.trigger('focus');
});
this.element.on('focus.inputSwitch', function(e) {
$this.handle.addClass('ui-state-focus');
})
.on('blur.inputSwitch', function(e) {
$this.handle.removeClass('ui-state-focus');
})
.on('keydown.inputSwitch', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE) {
e.preventDefault();
}
})
.on('keyup.inputSwitch', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE) {
$this.toggle();
e.preventDefault();
}
})
.on('change.inputSwitch', function(e) {
if($this.element.prop('checked'))
$this._checkUI();
else
$this._uncheckUI();
$this._trigger('change', e);
});
},
toggle: function() {
if(this.element.prop('checked'))
this.uncheck();
else
this.check();
},
check: function() {
this.element.prop('checked', true).trigger('change');
},
uncheck: function() {
this.element.prop('checked', false).trigger('change');
},
_checkUI: function() {
this.onContainer.animate({width:this.offset}, 200);
this.onLabel.animate({marginLeft:0}, 200);
this.offLabel.animate({marginRight:-this.offset}, 200);
this.handle.animate({left:this.offset}, 200);
},
_uncheckUI: function() {
this.onContainer.animate({width:0}, 200);
this.onLabel.animate({marginLeft:-this.offset}, 200);
this.offLabel.animate({marginRight:0}, 200);
this.handle.animate({left:0}, 200);
}
});
})();
/**
* PrimeUI tabview widget
*/
(function() {
$.widget("primeui.puitabview", {
options: {
activeIndex:0,
orientation:'top'
},
_create: function() {
var element = this.element;
element.addClass('pui-tabview ui-widget ui-widget-content ui-corner-all ui-hidden-container')
.children('ul').addClass('pui-tabview-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all')
.children('li').addClass('ui-state-default ui-corner-top');
element.addClass('pui-tabview-' + this.options.orientation);
element.children('div').addClass('pui-tabview-panels').children().addClass('pui-tabview-panel ui-widget-content ui-corner-bottom');
element.find('> ul.pui-tabview-nav > li').eq(this.options.activeIndex).addClass('pui-tabview-selected ui-state-active');
element.find('> div.pui-tabview-panels > div.pui-tabview-panel:not(:eq(' + this.options.activeIndex + '))').addClass('ui-helper-hidden');
this.navContainer = element.children('.pui-tabview-nav');
this.panelContainer = element.children('.pui-tabview-panels');
this._bindEvents();
},
_bindEvents: function() {
var $this = this;
//Tab header events
this.navContainer.children('li')
.on('mouseover.tabview', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-disabled')&&!element.hasClass('ui-state-active')) {
element.addClass('ui-state-hover');
}
})
.on('mouseout.tabview', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-disabled')&&!element.hasClass('ui-state-active')) {
element.removeClass('ui-state-hover');
}
})
.on('click.tabview', function(e) {
var element = $(this);
if($(e.target).is(':not(.fa-close)')) {
var index = element.index();
if(!element.hasClass('ui-state-disabled') && index != $this.options.selected) {
$this.select(index);
}
}
e.preventDefault();
});
//Closable tabs
this.navContainer.find('li .fa-close')
.on('click.tabview', function(e) {
var index = $(this).parent().index();
$this.remove(index);
e.preventDefault();
});
},
select: function(index) {
this.options.selected = index;
var newPanel = this.panelContainer.children().eq(index),
headers = this.navContainer.children(),
oldHeader = headers.filter('.ui-state-active'),
newHeader = headers.eq(newPanel.index()),
oldPanel = this.panelContainer.children('.pui-tabview-panel:visible'),
$this = this;
//aria
oldPanel.attr('aria-hidden', true);
oldHeader.attr('aria-expanded', false);
newPanel.attr('aria-hidden', false);
newHeader.attr('aria-expanded', true);
if(this.options.effect) {
oldPanel.hide(this.options.effect.name, null, this.options.effect.duration, function() {
oldHeader.removeClass('pui-tabview-selected ui-state-active');
newHeader.removeClass('ui-state-hover').addClass('pui-tabview-selected ui-state-active');
newPanel.show($this.options.name, null, $this.options.effect.duration, function() {
$this._trigger('change', null, {'index':index});
});
});
}
else {
oldHeader.removeClass('pui-tabview-selected ui-state-active');
oldPanel.hide();
newHeader.removeClass('ui-state-hover').addClass('pui-tabview-selected ui-state-active');
newPanel.show();
$this._trigger('change', null, {'index':index});
}
},
remove: function(index) {
var header = this.navContainer.children().eq(index),
panel = this.panelContainer.children().eq(index);
this._trigger('close', null, {'index':index});
header.remove();
panel.remove();
//active next tab if active tab is removed
if(index == this.options.selected) {
var newIndex = this.options.selected == this.getLength() ? this.options.selected - 1: this.options.selected;
this.select(newIndex);
}
},
getLength: function() {
return this.navContainer.children().length;
},
getActiveIndex: function() {
return this.options.selected;
},
_markAsLoaded: function(panel) {
panel.data('loaded', true);
},
_isLoaded: function(panel) {
return panel.data('loaded') === true;
},
disable: function(index) {
this.navContainer.children().eq(index).addClass('ui-state-disabled');
},
enable: function(index) {
this.navContainer.children().eq(index).removeClass('ui-state-disabled');
}
});
})();/**
* PrimeUI Terminal widget
*/
(function() {
$.widget("primeui.puiterminal", {
options: {
welcomeMessage: '',
prompt:'prime $',
handler: null
},
_create: function() {
this.element.addClass('pui-terminal ui-widget ui-widget-content ui-corner-all')
.append('<div>' + this.options.welcomeMessage + '</div>')
.append('<div class="pui-terminal-content"></div>')
.append('<div><span class="pui-terminal-prompt">' + this.options.prompt + '</span>' +
'<input type="text" class="pui-terminal-input" autocomplete="off"></div>' );
this.promptContainer = this.element.find('> div:last-child > span.pui-terminal-prompt');
this.content = this.element.children('.pui-terminal-content');
this.input = this.promptContainer.next();
this.commands = [];
this.commandIndex = 0;
this._bindEvents();
},
_bindEvents: function() {
var $this = this;
this.input.on('keydown.terminal', function(e) {
var keyCode = $.ui.keyCode;
switch(e.which) {
case keyCode.UP:
if($this.commandIndex > 0) {
$this.input.val($this.commands[--$this.commandIndex]);
}
e.preventDefault();
break;
case keyCode.DOWN:
if($this.commandIndex < ($this.commands.length - 1)) {
$this.input.val($this.commands[++$this.commandIndex]);
}
else {
$this.commandIndex = $this.commands.length;
$this.input.val('');
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
$this._processCommand();
e.preventDefault();
break;
}
});
this.element.on('click', function() {
$this.input.trigger('focus');
});
},
_processCommand: function() {
var command = this.input.val();
this.commands.push();
this.commandIndex++;
if(this.options.handler && $.type(this.options.handler) === 'function') {
this.options.handler.call(this, command, this._updateContent);
}
},
_updateContent: function(content) {
var commandResponseContainer = $('<div></div>');
commandResponseContainer.append('<span>' + this.options.prompt + '</span><span class="pui-terminal-command">' + this.input.val() + '</span>')
.append('<div>' + content + '</div>').appendTo(this.content);
this.input.val('');
this.element.scrollTop(this.content.height());
},
clear: function() {
this.content.html('');
this.input.val('');
}
});
})();/**
* PrimeUI togglebutton widget
*/
(function() {
$.widget("primeui.puitogglebutton", {
options: {
onLabel: 'Yes',
offLabel: 'No',
onIcon: null,
offIcon: null
},
_create: function() {
this.element.wrap('<div class="pui-button pui-togglebutton ui-widget ui-state-default ui-corner-all" />');
this.container = this.element.parent();
this.element.addClass('ui-helper-hidden-accessible');
if(this.options.onIcon && this.options.offIcon) {
this.container.addClass('pui-button-text-icon-left');
this.container.append('<span class="pui-button-icon-left pui-icon fa fa-fw"></span>');
}
else {
this.container.addClass('pui-button-text-only');
}
this.container.append('<span class="pui-button-text"></span>');
if(this.options.style) {
this.container.attr('style', this.options.style);
}
if(this.options.styleClass) {
this.container.attr('class', this.options.styleClass);
}
this.label = this.container.children('.pui-button-text');
this.icon = this.container.children('.pui-icon');
//initial state
if(this.element.prop('checked')) {
this.check(true);
} else {
this.uncheck(true);
}
if(!this.element.prop('disabled')) {
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.container.on('mouseover', function() {
if(!$this.container.hasClass('ui-state-active')) {
$this.container.addClass('ui-state-hover');
}
}).on('mouseout', function() {
$this.container.removeClass('ui-state-hover');
})
.on('click', function() {
$this.toggle();
$this.element.trigger('focus');
});
this.element.on('focus', function() {
$this.container.addClass('ui-state-focus');
})
.on('blur', function() {
$this.container.removeClass('ui-state-focus');
})
.on('keydown', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE) {
e.preventDefault();
}
})
.on('keyup', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE) {
$this.toggle();
e.preventDefault();
}
});
},
_unbindEvents: function() {
this.container.off('mouseover mouseout click');
this.element.off('focus blur keydown keyup');
},
toggle: function() {
if(this.element.prop('checked'))
this.uncheck();
else
this.check();
this._trigger('change', null, this.element.prop('checked'));
},
check: function(silent) {
this.container.addClass('ui-state-active');
this.label.text(this.options.onLabel);
this.element.prop('checked', true);
if(this.options.onIcon) {
this.icon.removeClass(this.options.offIcon).addClass(this.options.onIcon);
}
if(!silent) {
this.element.trigger('change');
}
},
uncheck: function(silent) {
this.container.removeClass('ui-state-active')
this.label.text(this.options.offLabel);
this.element.prop('checked', false);
if(this.options.offIcon) {
this.icon.removeClass(this.options.onIcon).addClass(this.options.offIcon);
}
if(!silent) {
this.element.trigger('change');
}
},
disable: function () {
this.element.prop('disabled', true);
this.container.attr('aria-disabled', true);
this.container.addClass('ui-state-disabled').removeClass('ui-state-focus ui-state-hover');
this._unbindEvents();
},
enable: function () {
this.element.prop('disabled', false);
this.container.attr('aria-disabled', false);
this.container.removeClass('ui-state-disabled');
this._bindEvents();
},
isChecked: function() {
return this.element.prop('checked');
}
});
})();/**
* PrimeFaces Tooltip Widget
*/
(function() {
$.widget("primeui.puitooltip", {
options: {
showEvent: 'mouseover',
hideEvent: 'mouseout',
showEffect: 'fade',
hideEffect: null,
showEffectSpeed: 'normal',
hideEffectSpeed: 'normal',
my: 'left top',
at: 'right bottom',
showDelay: 150,
content: null
},
_create: function() {
this.options.showEvent = this.options.showEvent + '.puitooltip';
this.options.hideEvent = this.options.hideEvent + '.puitooltip';
if(this.element.get(0) === document) {
this._bindGlobal();
}
else {
this._bindTarget();
}
},
_bindGlobal: function() {
this.container = $('<div class="pui-tooltip pui-tooltip-global ui-widget ui-widget-content ui-corner-all pui-shadow" />').appendTo(document.body);
this.globalSelector = 'a,:input,:button,img';
var $this = this;
$(document).off(this.options.showEvent + ' ' + this.options.hideEvent, this.globalSelector)
.on(this.options.showEvent, this.globalSelector, null, function() {
var target = $(this),
title = target.attr('title');
if(title) {
$this.container.text(title);
$this.globalTitle = title;
$this.target = target;
target.attr('title', '');
$this.show();
}
})
.on(this.options.hideEvent, this.globalSelector, null, function() {
var target = $(this);
if($this.globalTitle) {
$this.container.hide();
target.attr('title', $this.globalTitle);
$this.globalTitle = null;
$this.target = null;
}
});
var resizeNS = 'resize.puitooltip';
$(window).unbind(resizeNS).bind(resizeNS, function() {
if($this.container.is(':visible')) {
$this._align();
}
});
},
_bindTarget: function() {
this.container = $('<div class="pui-tooltip ui-widget ui-widget-content ui-corner-all pui-shadow" />').appendTo(document.body);
var $this = this;
this.element.off(this.options.showEvent + ' ' + this.options.hideEvent)
.on(this.options.showEvent, function() {
$this.show();
})
.on(this.options.hideEvent, function() {
$this.hide();
});
this.container.html(this.options.content);
this.element.removeAttr('title');
this.target = this.element;
var resizeNS = 'resize.' + this.element.attr('id');
$(window).unbind(resizeNS).bind(resizeNS, function() {
if($this.container.is(':visible')) {
$this._align();
}
});
},
_align: function() {
this.container.css({
left:'',
top:'',
'z-index': ++PUI.zindex
})
.position({
my: this.options.my,
at: this.options.at,
of: this.target
});
},
show: function() {
var $this = this;
this.timeout = window.setTimeout(function() {
$this._align();
$this.container.show($this.options.showEffect, {}, $this.options.showEffectSpeed);
}, this.options.showDelay);
},
hide: function() {
window.clearTimeout(this.timeout);
this.container.hide(this.options.hideEffect, {}, this.options.hideEffectSpeed, function() {
$(this).css('z-index', '');
});
}
});
})();/**
* PrimeUI Tree widget
*/
(function() {
$.widget("primeui.puitree", {
options: {
nodes: null,
lazy: false,
animate: false,
selectionMode: null,
icons: null
},
_create: function() {
this.element.uniqueId().addClass('pui-tree ui-widget ui-widget-content ui-corner-all')
.append('<ul class="pui-tree-container"></ul>');
this.rootContainer = this.element.children('.pui-tree-container');
if(this.options.selectionMode) {
this.selection = [];
}
this._bindEvents();
if($.type(this.options.nodes) === 'array') {
this._renderNodes(this.options.nodes, this.rootContainer);
}
else if($.type(this.options.nodes) === 'function') {
this.options.nodes.call(this, {}, this._initData);
}
else {
throw 'Unsupported type. nodes option can be either an array or a function';
}
},
_renderNodes: function(nodes, container) {
for(var i = 0; i < nodes.length; i++) {
this._renderNode(nodes[i], container);
}
},
_renderNode: function(node, container) {
var leaf = this.options.lazy ? node.leaf : !(node.children && node.children.length),
iconType = node.iconType||'def',
expanded = node.expanded,
selectable = this.options.selectionMode ? (node.selectable === false ? false : true) : false,
toggleIcon = leaf ? 'pui-treenode-leaf-icon' :
(node.expanded ? 'pui-tree-toggler fa fa-fw fa-caret-down' : 'pui-tree-toggler fa fa-fw fa-caret-right'),
styleClass = leaf ? 'pui-treenode pui-treenode-leaf' : 'pui-treenode pui-treenode-parent',
nodeElement = $('<li class="' + styleClass + '"></li>'),
contentElement = $('<span class="pui-treenode-content"></span>');
nodeElement.data('puidata', node.data).appendTo(container);
if(selectable) {
contentElement.addClass('pui-treenode-selectable');
}
contentElement.append('<span class="' + toggleIcon + '"></span>')
.append('<span class="pui-treenode-icon"></span>')
.append('<span class="pui-treenode-label ui-corner-all">' + node.label + '</span>')
.appendTo(nodeElement);
var iconConfig = this.options.icons && this.options.icons[iconType];
if(iconConfig) {
var iconContainer = contentElement.children('.pui-treenode-icon'),
icon = ($.type(iconConfig) === 'string') ? iconConfig : (expanded ? iconConfig.expanded : iconConfig.collapsed);
iconContainer.addClass('fa fa-fw ' + icon);
}
if(!leaf) {
var childrenContainer = $('<ul class="pui-treenode-children"></ul>');
if(!node.expanded) {
childrenContainer.hide();
}
childrenContainer.appendTo(nodeElement);
if(node.children) {
for(var i = 0; i < node.children.length; i++) {
this._renderNode(node.children[i], childrenContainer);
}
}
}
},
_initData: function(data) {
this._renderNodes(data, this.rootContainer);
},
_handleNodeData: function(data, node) {
this._renderNodes(data, node.children('.pui-treenode-children'));
this._showNodeChildren(node);
node.data('puiloaded', true);
},
_bindEvents: function() {
var $this = this,
elementId = this.element.attr('id'),
togglerSelector = '#' + elementId + ' .pui-tree-toggler';
$(document).off('click.puitree-' + elementId, togglerSelector)
.on('click.puitree-' + elementId, togglerSelector, null, function(e) {
var toggleIcon = $(this),
node = toggleIcon.closest('li');
if(node.hasClass('pui-treenode-expanded'))
$this.collapseNode(node);
else
$this.expandNode(node);
});
if(this.options.selectionMode) {
var nodeLabelSelector = '#' + elementId + ' .pui-treenode-selectable .pui-treenode-label',
nodeContentSelector = '#' + elementId + ' .pui-treenode-selectable.pui-treenode-content';
$(document).off('mouseout.puitree-' + elementId + ' mouseover.puitree-' + elementId, nodeLabelSelector)
.on('mouseout.puitree-' + elementId, nodeLabelSelector, null, function() {
$(this).removeClass('ui-state-hover');
})
.on('mouseover.puitree-' + elementId, nodeLabelSelector, null, function() {
$(this).addClass('ui-state-hover');
})
.off('click.puitree-' + elementId, nodeContentSelector)
.on('click.puitree-' + elementId, nodeContentSelector, null, function(e) {
$this._nodeClick(e, $(this));
});
}
},
expandNode: function(node) {
this._trigger('beforeExpand', null, {'node': node, 'data': node.data('puidata')});
if(this.options.lazy && !node.data('puiloaded')) {
this.options.nodes.call(this, {
'node': node,
'data': node.data('puidata')
}, this._handleNodeData);
}
else {
this._showNodeChildren(node);
}
},
collapseNode: function(node) {
this._trigger('beforeCollapse', null, {'node': node, 'data': node.data('puidata')});
node.removeClass('pui-treenode-expanded');
var iconType = node.iconType||'def',
iconConfig = this.options.icons && this.options.icons[iconType];
if(iconConfig && $.type(iconConfig) !== 'string') {
node.find('> .pui-treenode-content > .pui-treenode-icon').removeClass(iconConfig.expanded).addClass(iconConfig.collapsed);
}
var toggleIcon = node.find('> .pui-treenode-content > .pui-tree-toggler'),
childrenContainer = node.children('.pui-treenode-children');
toggleIcon.addClass('fa-caret-right').removeClass('fa-caret-down');
if(this.options.animate) {
childrenContainer.slideUp('fast');
}
else {
childrenContainer.hide();
}
this._trigger('afterCollapse', null, {'node': node, 'data': node.data('puidata')});
},
_showNodeChildren: function(node) {
node.addClass('pui-treenode-expanded').attr('aria-expanded', true);
var iconType = node.iconType||'def',
iconConfig = this.options.icons && this.options.icons[iconType];
if(iconConfig && $.type(iconConfig) !== 'string') {
node.find('> .pui-treenode-content > .pui-treenode-icon').removeClass(iconConfig.collapsed).addClass(iconConfig.expanded);
}
var toggleIcon = node.find('> .pui-treenode-content > .pui-tree-toggler');
toggleIcon.addClass('fa-caret-down').removeClass('fa-caret-right');
if(this.options.animate) {
node.children('.pui-treenode-children').slideDown('fast');
}
else {
node.children('.pui-treenode-children').show();
}
this._trigger('afterExpand', null, {'node': node, 'data': node.data('puidata')});
},
_nodeClick: function(event, nodeContent) {
PUI.clearSelection();
if($(event.target).is(':not(.pui-tree-toggler)')) {
var node = nodeContent.parent();
var selected = this._isNodeSelected(node.data('puidata')),
metaKey = event.metaKey||event.ctrlKey;
if(selected && metaKey) {
this.unselectNode(node);
}
else {
if(this._isSingleSelection()||(this._isMultipleSelection() && !metaKey)) {
this.unselectAllNodes();
}
this.selectNode(node);
}
}
},
selectNode: function(node) {
node.attr('aria-selected', true).find('> .pui-treenode-content > .pui-treenode-label').removeClass('ui-state-hover').addClass('ui-state-highlight');
this._addToSelection(node.data('puidata'));
this._trigger('nodeSelect', null, {'node': node, 'data': node.data('puidata')});
},
unselectNode: function(node) {
node.attr('aria-selected', false).find('> .pui-treenode-content > .pui-treenode-label').removeClass('ui-state-highlight ui-state-hover');
this._removeFromSelection(node.data('puidata'));
this._trigger('nodeUnselect', null, {'node': node, 'data': node.data('puidata')});
},
unselectAllNodes: function() {
this.selection = [];
this.element.find('.pui-treenode-label.ui-state-highlight').each(function() {
$(this).removeClass('ui-state-highlight').closest('.ui-treenode').attr('aria-selected', false);
});
},
_addToSelection: function(nodedata) {
if(nodedata) {
var selected = this._isNodeSelected(nodedata);
if(!selected) {
this.selection.push(nodedata);
}
}
},
_removeFromSelection: function(nodedata) {
if(nodedata) {
var index = -1;
for(var i = 0; i < this.selection.length; i++) {
var data = this.selection[i];
if(data && (JSON.stringify(data) === JSON.stringify(nodedata))) {
index = i;
break;
}
}
if(index >= 0) {
this.selection.splice(index, 1);
}
}
},
_isNodeSelected: function(nodedata) {
var selected = false;
if(nodedata) {
for(var i = 0; i < this.selection.length; i++) {
var data = this.selection[i];
if(data && (JSON.stringify(data) === JSON.stringify(nodedata))) {
selected = true;
break;
}
}
}
return selected;
},
_isSingleSelection: function() {
return this.options.selectionMode && this.options.selectionMode === 'single';
},
_isMultipleSelection: function() {
return this.options.selectionMode && this.options.selectionMode === 'multiple';
}
});
})();/**
* PrimeUI TreeTable widget
*/
(function() {
$.widget("primeui.puitreetable", {
options: {
nodes: null,
lazy: false,
selectionMode: null,
header: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.addClass('pui-treetable ui-widget');
this.tableWrapper = $('<div class="pui-treetable-tablewrapper" />').appendTo(this.element);
this.table = $('<table><thead></thead><tbody></tbody></table>').appendTo(this.tableWrapper);
this.thead = this.table.children('thead');
this.tbody = this.table.children('tbody').addClass('pui-treetable-data');
var $this = this;
if(this.options.columns) {
var headerRow = $('<tr></tr>').appendTo(this.thead);
$.each(this.options.columns, function(i, col) {
var header = $('<th class="ui-state-default"></th>').data('field', col.field).appendTo(headerRow);
if(col.headerClass) {
header.addClass(col.headerClass);
}
if(col.headerStyle) {
header.attr('style', col.headerStyle);
}
if(col.headerText) {
header.text(col.headerText);
}
});
}
if(this.options.header) {
this.element.prepend('<div class="pui-treetable-header ui-widget-header ui-corner-top">' + this.options.header + '</div>');
}
if(this.options.footer) {
this.element.append('<div class="pui-treetable-footer ui-widget-header ui-corner-bottom">' + this.options.footer + '</div>');
}
if($.isArray(this.options.nodes)) {
this._renderNodes(this.options.nodes, null, true);
}
else if($.type(this.options.nodes) === 'function') {
this.options.nodes.call(this, {}, this._initData);
}
else {
throw 'Unsupported type. nodes option can be either an array or a function';
}
this._bindEvents();
},
_initData: function(data) {
this._renderNodes(data, null, true);
},
_renderNodes: function(nodes, rootRow, expanded) {
for(var i = 0; i < nodes.length; i++) {
var node = nodes[i],
nodeData = node.data,
leaf = this.options.lazy ? node.leaf : !(node.children && node.children.length),
row = $('<tr class="ui-widget-content"></tr>'),
depth = rootRow ? rootRow.data('depth') + 1 : 0,
parentRowkey = rootRow ? rootRow.data('rowkey'): null,
rowkey = parentRowkey ? parentRowkey + '_' + i : i.toString();
row.data({
'depth': depth,
'rowkey': rowkey,
'parentrowkey': parentRowkey,
'puidata': nodeData
});
if(!expanded) {
row.addClass('ui-helper-hidden');
}
for(var j = 0; j < this.options.columns.length; j++) {
var column = $('<td />').appendTo(row),
columnOptions = this.options.columns[j];
if(columnOptions.bodyClass) {
column.addClass(columnOptions.bodyClass);
}
if(columnOptions.bodyStyle) {
column.attr('style', columnOptions.bodyStyle);
}
if(j === 0) {
var toggler = $('<span class="pui-treetable-toggler pui-icon fa fa-fw fa-caret-right pui-c"></span>');
toggler.css('margin-left', depth * 16 + 'px');
if(leaf) {
toggler.css('visibility', 'hidden');
}
toggler.appendTo(column);
}
if(columnOptions.content) {
var content = columnOptions.content.call(this, nodeData);
if($.type(content) === 'string')
column.text(content);
else
column.append(content);
}
else {
column.append(nodeData[columnOptions.field]);
}
}
if(rootRow)
row.insertAfter(rootRow);
else
row.appendTo(this.tbody);
if(!leaf) {
this._renderNodes(node.children, row, node.expanded);
}
}
},
_bindEvents: function() {
var $this = this,
togglerSelector = '> tr > td:first-child > .pui-treetable-toggler';
//expand and collapse
this.tbody.off('click.puitreetable', togglerSelector)
.on('click.puitreetable', togglerSelector, null, function(e) {
var toggler = $(this),
row = toggler.closest('tr');
if(!row.data('processing')) {
row.data('processing', true);
if(toggler.hasClass('fa-caret-right'))
$this.expandNode(row);
else
$this.collapseNode(row);
}
});
//selection
if(this.options.selectionMode) {
this.selection = [];
var rowSelector = '> tr';
this.tbody.off('mouseover.puitreetable mouseout.puitreetable click.puitreetable', rowSelector)
.on('mouseover.puitreetable', rowSelector, null, function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.addClass('ui-state-hover');
}
})
.on('mouseout.puitreetable', rowSelector, null, function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.removeClass('ui-state-hover');
}
})
.on('click.puitreetable', rowSelector, null, function(e) {
$this.onRowClick(e, $(this));
});
}
},
expandNode: function(row) {
this._trigger('beforeExpand', null, {'node': row, 'data': row.data('puidata')});
if(this.options.lazy && !row.data('puiloaded')) {
this.options.nodes.call(this, {
'node': row,
'data': row.data('puidata')
}, this._handleNodeData);
}
else {
this._showNodeChildren(row, false);
this._trigger('afterExpand', null, {'node': row, 'data': row.data('puidata')});
}
},
_handleNodeData: function(data, node) {
this._renderNodes(data, node, true);
this._showNodeChildren(node, false);
node.data('puiloaded', true);
this._trigger('afterExpand', null, {'node': node, 'data': node.data('puidata')});
},
_showNodeChildren: function(row, showOnly) {
if(!showOnly) {
row.data('expanded', true).attr('aria-expanded', true)
.find('.pui-treetable-toggler:first').addClass('fa-caret-down').removeClass('fa-caret-right');
}
var children = this._getChildren(row);
for(var i = 0; i < children.length; i++) {
var child = children[i];
child.removeClass('ui-helper-hidden');
if(child.data('expanded')) {
this._showNodeChildren(child, true);
}
}
row.data('processing', false);
},
collapseNode: function(row) {
this._trigger('beforeCollapse', null, {'node': row, 'data': row.data('puidata')});
this._hideNodeChildren(row, false);
row.data('processing', false);
this._trigger('afterCollapse', null, {'node': row, 'data': row.data('puidata')});
},
_hideNodeChildren: function(row, hideOnly) {
if(!hideOnly) {
row.data('expanded', false).attr('aria-expanded', false)
.find('.pui-treetable-toggler:first').addClass('fa-caret-right').removeClass('fa-caret-down');
}
var children = this._getChildren(row);
for(var i = 0; i < children.length; i++) {
var child = children[i];
child.addClass('ui-helper-hidden');
if(child.data('expanded')) {
this._hideNodeChildren(child, true);
}
}
},
onRowClick: function(event, row) {
if(!$(event.target).is(':input,:button,a,.pui-c')) {
var selected = row.hasClass('ui-state-highlight'),
metaKey = event.metaKey||event.ctrlKey;
if(selected && metaKey) {
this.unselectNode(row);
}
else {
if(this.isSingleSelection()||(this.isMultipleSelection() && !metaKey)) {
this.unselectAllNodes();
}
this.selectNode(row);
}
PUI.clearSelection();
}
},
selectNode: function(row, silent) {
row.removeClass('ui-state-hover').addClass('ui-state-highlight').attr('aria-selected', true);
if(!silent) {
this._trigger('nodeSelect', {}, {'node': row, 'data': row.data('puidata')});
}
},
unselectNode: function(row, silent) {
row.removeClass('ui-state-highlight').attr('aria-selected', false);
if(!silent) {
this._trigger('nodeUnselect', {}, {'node': row, 'data': row.data('puidata')});
}
},
unselectAllNodes: function() {
var selectedNodes = this.tbody.children('tr.ui-state-highlight');
for(var i = 0; i < selectedNodes.length; i++) {
this.unselectNode(selectedNodes.eq(i), true);
}
},
isSingleSelection: function() {
return this.options.selectionMode === 'single';
},
isMultipleSelection: function() {
return this.options.selectionMode === 'multiple';
},
_getChildren: function(node) {
var nodeKey = node.data('rowkey'),
nextNodes = node.nextAll(),
children = [];
for(var i = 0; i < nextNodes.length; i++) {
var nextNode = nextNodes.eq(i),
nextNodeParentKey = nextNode.data('parentrowkey');
if(nextNodeParentKey === nodeKey) {
children.push(nextNode);
}
}
return children;
}
});
})();
|
analysis/deathknightblood/src/modules/features/DancingRuneWeapon.js | yajinni/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import SpellUsable from 'parser/shared/modules/SpellUsable';
import Abilities from 'parser/core/modules/Abilities';
import { t } from '@lingui/macro';
import Events from 'parser/core/Events';
const ALLOWED_CASTS_DURING_DRW = [
SPELLS.DEATH_STRIKE.id,
SPELLS.HEART_STRIKE.id,
SPELLS.BLOOD_BOIL.id,
SPELLS.MARROWREND.id,
SPELLS.CONSUMPTION_TALENT.id, // todo => test if new consumption talent actually works with DRW
];
class DancingRuneWeapon extends Analyzer {
static dependencies = {
spellUsable: SpellUsable,
abilities: Abilities,
};
castsDuringDRW = [];
constructor(options){
super(options);
this.addEventListener(Events.cast.by(SELECTED_PLAYER), this.onCast);
}
onCast(event) {
if (!this.selectedCombatant.hasBuff(SPELLS.DANCING_RUNE_WEAPON_BUFF.id)) {
return;
}
//push all casts during DRW that were on the GCD in array
if (event.ability.guid !== SPELLS.RAISE_ALLY.id && //probably usefull to rezz someone even if it's a personal DPS-loss
event.ability.guid !== SPELLS.DANCING_RUNE_WEAPON.id && //because you get the DRW buff before the cast event since BFA
this.abilities.getAbility(event.ability.guid) !== undefined &&
this.abilities.getAbility(event.ability.guid).gcd) {
this.castsDuringDRW.push(event.ability.guid);
}
}
get goodDRWCasts() {
return this.castsDuringDRW.filter((val, index) => ALLOWED_CASTS_DURING_DRW.includes(val));
}
get SuggestionThresholds() {
return {
actual: this.goodDRWCasts.length / this.castsDuringDRW.length,
isLessThan: {
minor: 1,
average: 0.9,
major: .8,
},
style: 'percentage',
};
}
spellLinks(id, index) {
if (id === SPELLS.CONSUMPTION_TALENT.id) {
return <React.Fragment key={id}>and (if in AoE)<SpellLink id={id} /></React.Fragment>;
} else if (index + 2 === ALLOWED_CASTS_DURING_DRW.length) {
return <React.Fragment key={id}><SpellLink id={id} /> </React.Fragment>;
} else {
return <React.Fragment key={id}><SpellLink id={id} />, </React.Fragment>;
}
}
get goodDRWSpells() {
return (
<div>
Try and prioritize {ALLOWED_CASTS_DURING_DRW.map((id, index) => this.spellLinks(id, index))}
</div>
);
}
suggestions(when) {
when(this.SuggestionThresholds)
.addSuggestion((suggest, actual, recommended) => suggest(<>Avoid casting spells during <SpellLink id={SPELLS.DANCING_RUNE_WEAPON.id} /> that don't benefit from the coppies such as <SpellLink id={SPELLS.BLOODDRINKER_TALENT.id} /> and <SpellLink id={SPELLS.DEATH_AND_DECAY.id} />. Check the cooldown-tab below for more detailed breakdown.{this.goodDRWSpells}</>)
.icon(SPELLS.DANCING_RUNE_WEAPON.icon)
.actual(t({
id: "deathknight.blood.suggestions.dancingRuneWeapon.numberCasts",
message: `${ this.goodDRWCasts.length } out of ${ this.castsDuringDRW.length} casts during DRW were good`
}))
.recommended(`${this.castsDuringDRW.length} recommended`));
}
}
export default DancingRuneWeapon;
|
ajax/libs/mediaelement/1.1.1/jquery.js | JohnKim/cdnjs | /*!
* jQuery JavaScript Library v1.4.4
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu Nov 11 19:04:53 2010 -0500
*/
(function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h=
h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"||
h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La,
"`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this,
e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a,
"margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+
a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,
C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j,
s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this,
j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length},
toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j===
-1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false;
if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--;
if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload",
b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&&
!F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&&
l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z],
z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j,
s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v=
s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)||
[];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u,
false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"),
k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false,
scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent=
false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom=
1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display=
"none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h=
c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando);
else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this,
a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e=
c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,
a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",
colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===
1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "),
l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,
"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one";
if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r=
a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},
attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&
b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0};
c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,
arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid=
d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+
c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b=
w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===
8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k===
"click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+
d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==B)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this,
Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=
c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U};
var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!==
"form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V,
xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired=
B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type===
"file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]===
0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d,
a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d=
1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d===
"object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}});
c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});
(function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i,
[y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3];
break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr,
q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h=
l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*"));
return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!==
B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()===
i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=
i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g,
"")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n,
m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===
true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===
g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]-
0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n===
"first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===
i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]];
if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m,
g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1;
for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"),
i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g);
n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&&
function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F||
p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g=
t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition?
function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML;
c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})},
not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h=
h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context):
c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,
2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,
b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&
e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={option:[1,
"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null;
else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=
c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a,
b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")):
this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append",
prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument||
b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length-
1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script"))));
d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i,
jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true,
zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b),
h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b);
if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f=
d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left;
e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b===
"object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&
!this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})},
getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html",
script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data||
!T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache=
false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset;
A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type",
b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&&
c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d||
c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]=
encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess",
[b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),
e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}});
if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show",
3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay",
d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b,
d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)===
"inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L||
1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b,
d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a*
Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)}
var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;
this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide||
this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=
c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===
b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&&
h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle;
for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+=
parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",
height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells=
f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a,
"marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a,
e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&&
c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();
c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+
b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window); |
app/main.js | Charmatzis/cargo-project | import React from 'react';
import { render } from 'react-dom';
import MapView from "./MapView";
import styles from './Leaflet.Coordinates-0.1.5.css';
const example = (
<MapView />
)
render(example, document.getElementById('app')); |
app/components/Footer/index.js | Luandro-com/repsparta-web-app | /**
*
* Footer
*
*/
import React from 'react';
import Loader from 'halogen/PulseLoader';
import styles from './styles.css';
import Divider from './divider2.svg';
import BotDivider from './footer.svg';
import Facebook from './facebook.png';
function Footer({footer}) {
function createMarkup() { return {__html: footer};};
let main;
footer !== null
? main = <div
className={styles.text}
dangerouslySetInnerHTML={createMarkup()} />
: main = <div className={styles.text}><Loader /></div>
return (
<div className={styles.wrapper}>
<img className={styles.divider} src={Divider} />
{main}
<img className={styles.bot_divider} src={BotDivider} />
<div className={styles.footer}>
<div className={styles.footer_container}>
<a href="https://www.facebook.com/Hospedagem-SMAGA-1607335222890211">
<img className={styles.facebook} src={Facebook} />
</a>
<span>© 2017 República Sparta</span>
<a href="http://luandro.com">
<span>por Luandro</span>
</a>
</div>
</div>
</div>
);
}
export default Footer;
|
app/javascript/mastodon/containers/timeline_container.js | codl/mastodon | import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { hydrateStore } from '../actions/store';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import PublicTimeline from '../features/standalone/public_timeline';
import HashtagTimeline from '../features/standalone/hashtag_timeline';
import initialState from '../initial_state';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
const store = configureStore();
if (initialState) {
store.dispatch(hydrateStore(initialState));
}
export default class TimelineContainer extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
hashtag: PropTypes.string,
};
render () {
const { locale, hashtag } = this.props;
let timeline;
if (hashtag) {
timeline = <HashtagTimeline hashtag={hashtag} />;
} else {
timeline = <PublicTimeline />;
}
return (
<IntlProvider locale={locale} messages={messages}>
<Provider store={store}>
{timeline}
</Provider>
</IntlProvider>
);
}
}
|
src/components/SvgIcons.js | g8extended/Character-Generator | import React from 'react';
export default (
() => (
<svg style={{ display: 'none' }} version="1.1" id="icons" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 26 26" enableBackground="new 0 0 26 26" xmlSpace="preserve">
<path id="twitter-icon" d="M24.877,6.129c-0.873,0.362-1.811,0.604-2.796,0.714c1.005-0.562,1.777-1.451,2.141-2.51
C23.28,4.852,22.239,5.23,21.13,5.434C20.242,4.551,18.977,4,17.576,4c-2.688,0-4.869,2.032-4.869,4.538
c0,0.356,0.043,0.703,0.126,1.034C8.788,9.383,5.201,7.576,2.799,4.831C2.381,5.502,2.141,6.28,2.141,7.113
c0,1.574,0.86,2.964,2.166,3.777c-0.798-0.024-1.549-0.228-2.206-0.568c0,0.02,0,0.038,0,0.058c0,2.2,1.678,4.033,3.905,4.45
c-0.408,0.104-0.839,0.157-1.282,0.157c-0.314,0-0.619-0.027-0.917-0.078c0.619,1.801,2.418,3.114,4.548,3.151
c-1.666,1.216-3.766,1.942-6.047,1.942c-0.393,0-0.78-0.022-1.161-0.063c2.154,1.286,4.714,2.039,7.462,2.039
c8.955,0,13.852-6.917,13.852-12.914c0-0.197-0.005-0.392-0.014-0.588C23.399,7.836,24.224,7.038,24.877,6.129z"/>
<path id="facebook-icon" d="M15.381,23.821h-4.677V13.093H8.366V9.396h2.338v-2.22c0-3.016,1.32-4.81,5.068-4.81h3.122
v3.697h-1.95c-1.46,0-1.557,0.517-1.557,1.482l-0.006,1.851h3.535l-0.414,3.697h-3.121V23.821z"/>
<path id="dribbble-icon" d="M13,1.422C6.433,1.422,1.109,6.606,1.109,13S6.433,24.578,13,24.578S24.891,19.394,24.891,13
S19.567,1.422,13,1.422z M20.851,6.763c1.413,1.683,2.268,3.827,2.29,6.161c-0.334-0.069-3.687-0.732-7.061-0.318
c-0.071-0.169-0.144-0.339-0.219-0.51c-0.21-0.482-0.437-0.961-0.673-1.433C18.938,9.17,20.637,7.045,20.851,6.763z M13.001,3.128
c2.577,0,4.932,0.943,6.722,2.492c-0.182,0.253-1.708,2.254-5.314,3.572c-1.662-2.977-3.504-5.423-3.784-5.789
C11.387,3.224,12.183,3.128,13.001,3.128z M8.69,4.068c0.267,0.357,2.08,2.806,3.76,5.719c-4.744,1.228-8.922,1.21-9.376,1.204
C3.732,7.923,5.852,5.373,8.69,4.068z M2.86,13.017c0-0.101,0.002-0.202,0.005-0.302c0.444,0.009,5.358,0.07,10.422-1.408
c0.29,0.554,0.568,1.117,0.822,1.679c-0.134,0.037-0.267,0.076-0.4,0.117c-5.23,1.649-8.013,6.143-8.243,6.526
C3.847,17.876,2.86,15.557,2.86,13.017z M13.001,22.906c-2.344,0-4.505-0.78-6.225-2.088c0.183-0.364,2.236-4.232,7.956-6.176
c0.022-0.008,0.045-0.015,0.067-0.022c1.424,3.608,2.012,6.631,2.163,7.499C15.745,22.626,14.406,22.906,13.001,22.906z
M18.667,21.215c-0.104-0.601-0.644-3.497-1.97-7.051c3.178-0.496,5.97,0.316,6.317,0.423
C22.562,17.338,20.942,19.714,18.667,21.215z"/>
<path id="creativemarket-icon" d="M24.976,10.354c0-0.918-0.395-6.373-0.395-6.373c0-0.865-0.321-1.444-0.723-1.839
c-0.394-0.401-0.973-0.723-1.838-0.723c0,0-5.456-0.395-6.375-0.395c-1.318,0-2.198-0.038-3.85,1.616
c-0.803,0.802-9.708,9.708-10.084,10.083c-0.375,0.375-1.642,1.853,0.52,4.014l3.42,3.42l0.193,0.193l3.42,3.421
c2.163,2.163,3.641,0.893,4.015,0.518c0.375-0.375,9.281-9.281,10.083-10.083C25.015,12.552,24.976,11.674,24.976,10.354z
M15.459,13.296l3.051,1.449l-1.122,2.008l-2.822-1.843c-0.065-0.043-0.14-0.065-0.214-0.065c-0.065,0-0.131,0.016-0.19,0.05
c-0.126,0.073-0.199,0.211-0.189,0.357l0.233,3.338h-2.259c0,0-0.006,0-0.01,0c0.009-0.028,0.186-3.34,0.186-3.34
c0.01-0.146-0.062-0.284-0.189-0.357c-0.128-0.073-0.284-0.067-0.404,0.015l-2.744,1.864l-1.225-1.948l3.078-1.528
c0.132-0.062,0.217-0.196,0.217-0.343s-0.085-0.281-0.217-0.343l-3.053-1.45l1.122-2.008l2.821,1.844
c0.12,0.08,0.276,0.089,0.404,0.015c0.126-0.073,0.199-0.211,0.189-0.357L11.89,7.316h2.26l-0.178,3.338
c-0.01,0.146,0.062,0.284,0.189,0.357c0.128,0.074,0.285,0.065,0.404-0.015l2.744-1.864l1.225,1.949l-3.075,1.528
c-0.132,0.062-0.217,0.196-0.217,0.343C15.242,13.1,15.326,13.234,15.459,13.296z M20.678,6.894c-0.799,0-1.444-0.647-1.444-1.444
c0-0.798,0.645-1.443,1.444-1.443c0.794,0,1.44,0.645,1.44,1.443S21.473,6.894,20.678,6.894z"/>
<path id="behance-icon" d="M22.671,8.116h-6.022V6.62h6.022V8.116L22.671,8.116z M12.64,14.25
c0.389,0.602,0.583,1.333,0.583,2.19c0,0.887-0.219,1.683-0.664,2.386c-0.283,0.465-0.635,0.858-1.058,1.175
c-0.476,0.366-1.04,0.617-1.688,0.751c-0.65,0.134-1.353,0.202-2.111,0.202H0.968V6H8.19c1.82,0.03,3.111,0.557,3.873,1.593
c0.457,0.635,0.684,1.397,0.684,2.283c0,0.914-0.229,1.646-0.691,2.201c-0.257,0.312-0.636,0.595-1.139,0.851
C11.677,13.207,12.254,13.646,12.64,14.25z M4.416,11.895H7.58c0.65,0,1.176-0.124,1.581-0.371
c0.405-0.246,0.607-0.684,0.607-1.314c0-0.696-0.267-1.157-0.803-1.379C8.504,8.677,7.915,8.597,7.2,8.597H4.416V11.895z
M10.072,16.226c0-0.777-0.317-1.314-0.951-1.602c-0.354-0.163-0.854-0.247-1.495-0.253h-3.21v3.985h3.16
c0.649,0,1.152-0.085,1.514-0.262C9.744,17.768,10.072,17.147,10.072,16.226z M24.905,13.794c0.073,0.489,0.106,1.199,0.092,2.127
h-7.799c0.043,1.076,0.415,1.829,1.119,2.26c0.425,0.27,0.94,0.402,1.544,0.402c0.636,0,1.155-0.161,1.554-0.492
c0.218-0.175,0.409-0.423,0.575-0.735h2.858c-0.075,0.636-0.419,1.281-1.038,1.936c-0.958,1.042-2.302,1.564-4.028,1.564
c-1.426,0-2.683-0.44-3.773-1.318c-1.087-0.881-1.633-2.309-1.633-4.291c0-1.858,0.49-3.28,1.474-4.27
c0.987-0.992,2.261-1.485,3.832-1.485c0.931,0,1.77,0.166,2.519,0.501c0.746,0.335,1.363,0.862,1.849,1.586
C24.49,12.216,24.773,12.954,24.905,13.794z M22.091,14.073c-0.052-0.744-0.301-1.308-0.748-1.693
c-0.444-0.386-0.998-0.58-1.66-0.58c-0.72,0-1.276,0.207-1.671,0.614c-0.398,0.406-0.645,0.959-0.747,1.658L22.091,14.073
L22.091,14.073z"/>
<path id="mail-icon" d="M16.6,5l-6.4,9.3V5H2.5l3.2,4.8V22h4.6L21.9,5H16.6z M17.1,13.7l-2.6,3.9l3,4.4h5.3L17.1,13.7z"/>
</svg>
)
);
|
node_modules/react-icons/fa/google-plus.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const FaGooglePlus = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m25.2 20.3q0 3.6-1.6 6.5t-4.3 4.4-6.5 1.6q-2.6 0-5-1t-4.1-2.7-2.7-4.1-1-5 1-5 2.7-4.1 4.1-2.7 5-1q5 0 8.6 3.3l-3.5 3.4q-2-2-5.1-2-2.1 0-4 1.1t-2.8 2.9-1.1 4.1 1.1 4.1 2.8 2.9 4 1.1q1.5 0 2.7-0.4t2-1 1.4-1.4 0.8-1.4 0.4-1.3h-7.3v-4.4h12.1q0.3 1.1 0.3 2.1z m15.1-2.1v3.6h-3.6v3.7h-3.7v-3.7h-3.7v-3.6h3.7v-3.7h3.7v3.7h3.6z"/></g>
</Icon>
)
export default FaGooglePlus
|
frontend/Editor/TextElements/Link/Link.js | fdemian/Morpheus | import React from 'react';
import {Entity} from 'draft-js';
const Link = (props) => {
const {url} = Entity.get(props.entityKey).getData();
return (
<a href={url}>{props.children}</a>
);
};
export default Link; |
packages/react-router-website/modules/examples/RouteConfig.js | justjavac/react-router-CN | import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
// 一些程序员喜欢把路由配置集中到一个地方,要知道路由的配置其实只是普通的数据
// 在把数据映射到组件上这方面,React 非常强大,并且,这里的 <Route> 就是一
// 个普通的组件。
////////////////////////////////////////////////////////////
// 我们先来定义route相关的组件。
const Main = () => <h2>主页</h2>
const Redbull = () => <h2>红牛</h2>
const Snacks = ({ routes }) => (
<div>
<h2>小吃</h2>
<ul>
<li><Link to="/snacks/spicy">辣条</Link></li>
<li><Link to="/snacks/chips">薯片</Link></li>
</ul>
{routes.map((route, i) => (
<RouteWithSubRoutes key={i} {...route}/>
))}
</div>
)
const Spicy = () => <h3>辣条</h3>
const Chips = () => <h3>薯片</h3>
////////////////////////////////////////////////////////////
// 这里是路由的配置。
const routes = [
{ path: '/redbull',
component: Redbull
},
{ path: '/snacks',
component: Snacks,
routes: [
{ path: '/snacks/spicy',
component: Spicy
},
{ path: '/snacks/chips',
component: Chips
}
]
}
]
// 把 <Route> 组件像这样包一层,然后在需要使用 <Route> 的地方使用 <RouteWithSubRoutes>
// 自路由可以加到任意路由组件上。
const RouteWithSubRoutes = (route) => (
<Route path={route.path} render={props => (
// 把自路由向下传递来达到嵌套。
<route.component {...props} routes={route.routes}/>
)}/>
)
const RouteConfigExample = () => (
<Router>
<div>
<ul>
<li><Link to="/snacks">小吃</Link></li>
<li><Link to="/redbull">红牛</Link></li>
</ul>
{routes.map((route, i) => (
<RouteWithSubRoutes key={i} {...route}/>
))}
</div>
</Router>
)
export default RouteConfigExample
|
src/parser/monk/brewmaster/modules/spells/GiftOfTheOx.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatNumber } from 'common/format';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import StatisticBox from 'interface/others/StatisticBox';
import StatTracker from 'parser/shared/modules/StatTracker';
import { calculatePrimaryStat } from 'common/stats';
import { BASE_AGI, GIFT_OF_THE_OX_SPELLS } from '../../constants';
import { GOTOX_GENERATED_EVENT } from '../../normalizers/GiftOfTheOx';
const WDPS_BASE_ILVL = 310;
const WDPS_310_AGI_POLEARM = 122.8;
/**
* Gift of the Ox
*
* Generated healing spheres when struck, which heal for 1.5x AP when
* consumed by walking over, expiration, overcapping, or casting
* Expel Harm.
*
* See peak for a breakdown of how it works and all its quirks:
* https://www.peakofserenity.com/2018/10/06/gift-of-the-ox/
*/
export default class GiftOfTheOx extends Analyzer {
static dependencies = {
stats: StatTracker,
}
totalHealing = 0;
agiBonusHealing = 0;
wdpsBonusHealing = 0;
_baseAgiHealing = 0;
masteryBonusHealing = 0;
_wdps = 0;
orbsGenerated = 0;
orbsConsumed = 0;
expelHarmCasts = 0;
expelHarmOrbsConsumed = 0;
expelHarmOverhealing = 0;
_lastEHTimestamp = null;
constructor(...args) {
super(...args);
this.addEventListener(GOTOX_GENERATED_EVENT, this._orbGenerated);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.EXPEL_HARM), this._expelCast);
this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(GIFT_OF_THE_OX_SPELLS), this._gotoxHeal);
this._wdps = calculatePrimaryStat(WDPS_BASE_ILVL, WDPS_310_AGI_POLEARM, this.selectedCombatant.mainHand.itemLevel);
}
_orbGenerated(event) {
this.orbsGenerated += 1;
}
_expelCast(event) {
this.expelHarmCasts += 1;
this._lastEHTimestamp = event.timestamp;
}
_gotoxHeal(event) {
this.orbsConsumed += 1;
const amount = event.amount + (event.absorbed || 0);
this.totalHealing += amount;
// so the formula for the healing is
//
// Heal = 1.5 * (6 * WDPS + BonusAgi + BaseAgi) * Mastery * Vers
//
// With BaseAgi known, we get:
//
// BonusHeal = 1.5 * (6 * WDPS + BonusAgi + BaseAgi) * Mastery * Vers - 1.5 * (6 * WDPS + BaseAgi) * Mastery * Vers
// = Heal * (1 - (6 WDPS + BaseAgi) / (6 WDPS + BonusAgi + BaseAgi))
// = Heal * (BonusAgi / (6 WDPS + BonusAgi + BaseAgi))
//
// and similar for bonus WDPS healing and base agi healing
const denom = (6 * this._wdps + this.stats.currentAgilityRating);
this.agiBonusHealing += amount * (this.stats.currentAgilityRating - BASE_AGI) / denom;
this.wdpsBonusHealing += amount * 6 * this._wdps / denom;
this._baseAgiHealing += amount * BASE_AGI / denom;
// MasteryBonusHeal = 1.5 * AP * (1 + BonusMastery + BaseMastery) * Vers - 1.5 * AP * (1 + BaseMastery) * Vers
// = Heal * (1 - (1 + BaseMastery) / (1 + BonusMastery + BaseMastery))
// = Heal * BonusMastery / (1 + BonusMastery + BaseMastery)
this.masteryBonusHealing += amount * (this.stats.currentMasteryPercentage - this.stats.masteryPercentage(0, true)) / (1 + this.stats.currentMasteryPercentage);
if(event.timestamp === this._lastEHTimestamp) {
this.expelHarmOrbsConsumed += 1;
this.expelHarmOverhealing += event.overheal || 0;
}
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={GIFT_OF_THE_OX_SPELLS[0].id} />}
label={"Gift of the Ox Healing"}
value={`${formatNumber(this.totalHealing / (this.owner.fightDuration / 1000))} HPS`}
tooltip={(
<>
You generated {formatNumber(this.orbsGenerated)} healing spheres and consumed {formatNumber(this.orbsConsumed)} of them, healing for <b>{formatNumber(this.totalHealing)}</b>.<br />
{formatNumber(this.expelHarmOrbsConsumed)} of these were consumed with Expel Harm over {formatNumber(this.expelHarmCasts)} casts.
</>
)}
/>
);
}
}
|
packages/material-ui-icons/src/FilterCenterFocus.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M5 15H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4zM12 9c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z" /></g>
, 'FilterCenterFocus');
|
react/features/base/react/components/native/HeaderLabel.js | gpolitis/jitsi-meet | // @flow
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { ColorSchemeRegistry } from '../../../color-scheme';
import { translate } from '../../../i18n';
import { connect } from '../../../redux';
/**
* The type of the React {@code Component} props of {@link HeaderLabel}.
*/
type Props = {
/**
* The i18n key of the label to be rendered.
*/
labelKey: string,
/**
* The i18n translate function.
*/
t: Function,
/**
* The color schemed style of the Header component.
*/
_headerStyles: Object
};
/**
* A component rendering a standard label in the header.
*/
class HeaderLabel extends Component<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { _headerStyles } = this.props;
return (
<View
pointerEvents = 'box-none'
style = { _headerStyles.headerTextWrapper }>
<Text
style = { [
_headerStyles.headerText
] }>
{ this.props.t(this.props.labelKey) }
</Text>
</View>
);
}
}
/**
* Maps part of the Redux state to the props of this component.
*
* @param {Object} state - The Redux state.
* @returns {{
* _headerStyles: Object
* }}
*/
function _mapStateToProps(state) {
return {
_headerStyles: ColorSchemeRegistry.get(state, 'Header')
};
}
export default translate(connect(_mapStateToProps)(HeaderLabel));
|
ajax/libs/hyperform/0.8.2/hyperform.amd.js | jdh8/cdnjs | /*! hyperform.js.org */
define(function () { 'use strict';
var registry = Object.create(null);
/**
* run all actions registered for a hook
*
* Every action gets called with a state object as `this` argument and with the
* hook's call arguments as call arguments.
*
* @return mixed the returned value of the action calls or undefined
*/
function call_hook(hook) {
var result;
var call_args = Array.prototype.slice.call(arguments, 1);
if (hook in registry) {
result = registry[hook].reduce(function (args) {
return function (previousResult, currentAction) {
var interimResult = currentAction.apply({
state: previousResult,
hook: hook
}, args);
return interimResult !== undefined ? interimResult : previousResult;
};
}(call_args), result);
}
return result;
}
/**
* remove an action again
*/
function remove_hook(hook, action) {
if (hook in registry) {
for (var i = 0; i < registry[hook].length; i++) {
if (registry[hook][i] === action) {
registry[hook].splice(i, 1);
break;
}
}
}
}
/**
* add an action to a hook
*/
function add_hook(hook, action, position) {
if (!(hook in registry)) {
registry[hook] = [];
}
if (position === undefined) {
position = registry[hook].length;
}
registry[hook].splice(position, 0, action);
}
/**
* return either the data of a hook call or the result of action, if the
* former is undefined
*
* @return function a function wrapper around action
*/
function return_hook_or (hook, action) {
return function () {
var data = call_hook(hook, Array.prototype.slice.call(arguments));
if (data !== undefined) {
return data;
}
return action.apply(this, arguments);
};
}
function trigger_event (element, event) {
var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var _ref$bubbles = _ref.bubbles;
var bubbles = _ref$bubbles === undefined ? true : _ref$bubbles;
var _ref$cancelable = _ref.cancelable;
var cancelable = _ref$cancelable === undefined ? false : _ref$cancelable;
if (!(event instanceof window.Event)) {
var _event = document.createEvent('Event');
_event.initEvent(event, bubbles, cancelable);
event = _event;
}
element.dispatchEvent(event);
return event;
}
/* and datetime-local? Spec says “Nah!” */
var dates = ['datetime', 'date', 'month', 'week', 'time'];
var plain_numbers = ['number', 'range'];
/* everything that returns something meaningful for valueAsNumber and
* can have the step attribute */
var numbers = dates.concat(plain_numbers, 'datetime-local');
/* the spec says to only check those for syntax in validity.typeMismatch.
* ¯\_(ツ)_/¯ */
var type_checked = ['email', 'url'];
/* check these for validity.badInput */
var input_checked = ['email', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'number', 'range', 'color'];
var text_types = ['text', 'search', 'tel', 'password'].concat(type_checked);
/* input element types, that are candidates for the validation API.
* Missing from this set are: button, hidden, menu (from <button>), reset and
* the types for non-<input> elements. */
var validation_candidates = ['checkbox', 'color', 'file', 'image', 'radio', 'submit'].concat(numbers, text_types);
/* all known types of <input> */
var inputs = ['button', 'hidden', 'reset'].concat(validation_candidates);
/* apparently <select> and <textarea> have types of their own */
var non_inputs = ['select-one', 'select-multiple', 'textarea'];
/**
* mark an object with a '__hyperform=true' property
*
* We use this to distinguish our properties from the native ones. Usage:
* js> mark(obj);
* js> assert(obj.__hyperform === true)
*/
function mark (obj) {
if (['object', 'function'].indexOf(typeof obj) > -1) {
delete obj.__hyperform;
Object.defineProperty(obj, '__hyperform', {
configurable: true,
enumerable: false,
value: true
});
}
return obj;
}
/**
* the internal storage for messages
*/
var store = new WeakMap();
/* jshint -W053 */
var message_store = {
set: function set(element, message) {
var is_custom = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
if (element instanceof window.HTMLFieldSetElement) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && !wrapped_form.settings.extend_fieldset) {
/* make this a no-op for <fieldset> in strict mode */
return message_store;
}
}
if (typeof message === 'string') {
message = new String(message);
}
if (is_custom) {
message.is_custom = true;
}
mark(message);
store.set(element, message);
/* allow the :invalid selector to match */
if ('_original_setCustomValidity' in element) {
element._original_setCustomValidity(message.toString());
}
return message_store;
},
get: function get(element) {
var message = store.get(element);
if (message === undefined && '_original_validationMessage' in element) {
/* get the browser's validation message, if we have none. Maybe it
* knows more than we. */
message = new String(element._original_validationMessage);
}
return message ? message : new String('');
},
delete: function _delete(element) {
if ('_original_setCustomValidity' in element) {
element._original_setCustomValidity('');
}
return store.delete(element);
}
};
/**
* counter that will be incremented with every call
*
* Will enforce uniqueness, as long as no more than 1 hyperform scripts
* are loaded. (In that case we still have the "random" part below.)
*/
var uid = 0;
/**
* generate a random ID
*
* @see https://gist.github.com/gordonbrander/2230317
*/
function generate_id () {
var prefix = arguments.length <= 0 || arguments[0] === undefined ? 'hf_' : arguments[0];
return prefix + uid++ + Math.random().toString(36).substr(2);
}
var warnings_cache = new WeakMap();
var DefaultRenderer = {
/**
* called when a warning should become visible
*/
attach_warning: function attach_warning(warning, element) {
/* should also work, if element is last,
* http://stackoverflow.com/a/4793630/113195 */
element.parentNode.insertBefore(warning, element.nextSibling);
},
/**
* called when a warning should vanish
*/
detach_warning: function detach_warning(warning, element) {
warning.parentNode.removeChild(warning);
},
/**
* called when feedback to an element's state should be handled
*
* i.e., showing and hiding warnings
*/
show_warning: function show_warning(element) {
var sub_radio = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var msg = message_store.get(element).toString();
var warning = warnings_cache.get(element);
if (msg) {
if (!warning) {
var wrapper = get_wrapper(element);
warning = document.createElement('div');
warning.className = wrapper && wrapper.settings.classes.warning || 'hf-warning';
warning.id = generate_id();
warning.setAttribute('aria-live', 'polite');
warnings_cache.set(element, warning);
}
element.setAttribute('aria-errormessage', warning.id);
warning.textContent = msg;
Renderer.attach_warning(warning, element);
} else if (warning && warning.parentNode) {
element.removeAttribute('aria-errormessage');
Renderer.detach_warning(warning, element);
}
if (!sub_radio && element.type === 'radio' && element.form) {
/* render warnings for all other same-name radios, too */
Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) {
return radio.name === element.name && radio.form === element.form;
}).map(function (radio) {
return Renderer.show_warning(radio, 'sub_radio');
});
}
}
};
var Renderer = {
attach_warning: DefaultRenderer.attach_warning,
detach_warning: DefaultRenderer.detach_warning,
show_warning: DefaultRenderer.show_warning,
set: function set(renderer, action) {
if (!action) {
action = DefaultRenderer[renderer];
}
Renderer[renderer] = action;
}
};
/**
* check element's validity and report an error back to the user
*/
function reportValidity(element) {
/* if this is a <form>, report validity of all child inputs */
if (element instanceof window.HTMLFormElement) {
return Array.prototype.map.call(element.elements, reportValidity).every(function (b) {
return b;
});
}
/* we copy checkValidity() here, b/c we have to check if the "invalid"
* event was canceled. */
var valid = ValidityState(element).valid;
var event;
if (valid) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && wrapped_form.settings.valid_event) {
event = trigger_event(element, 'valid', { cancelable: true });
}
} else {
event = trigger_event(element, 'invalid', { cancelable: true });
}
if (!event || !event.defaultPrevented) {
Renderer.show_warning(element);
}
return valid;
}
function submit_form_via(element) {
/* apparently, the submit event is not triggered in most browsers on
* the submit() method, so we do it manually here to model a natural
* submit as closely as possible. */
var submit_event = trigger_event(element.form, 'submit', { cancelable: true });
if (!submit_event.defaultPrevented) {
add_submit_field(element);
element.form.submit();
remove_submit_field(element);
}
}
function add_submit_field(button) {
/* if a submit button was clicked, add its name=value to the
* submitted data. */
if (['image', 'submit'].indexOf(button.type) > -1 && button.name) {
var wrapper = get_wrapper(button.form) || {};
var submit_helper = wrapper.submit_helper;
if (submit_helper) {
if (submit_helper.parentNode) {
submit_helper.parentNode.removeChild(submit_helper);
}
} else {
submit_helper = document.createElement('input');
submit_helper.type = 'hidden';
wrapper.submit_helper = submit_helper;
}
submit_helper.name = button.name;
submit_helper.value = button.value;
button.form.appendChild(submit_helper);
}
}
function remove_submit_field(button) {
if (['image', 'submit'].indexOf(button.type) > -1 && button.name) {
var wrapper = get_wrapper(button.form) || {};
var submit_helper = wrapper.submit_helper;
if (submit_helper && submit_helper.parentNode) {
submit_helper.parentNode.removeChild(submit_helper);
}
}
}
function check(event) {
event.preventDefault();
/* trigger a "validate" event on the form to be submitted */
var val_event = trigger_event(event.target.form, 'validate', { cancelable: true });
if (val_event.defaultPrevented) {
/* skip the whole submit thing, if the validation is canceled. A user
* can still call form.submit() afterwards. */
return;
}
var valid = true;
var first_invalid;
Array.prototype.map.call(event.target.form.elements, function (element) {
if (!reportValidity(element)) {
valid = false;
if (!first_invalid && 'focus' in element) {
first_invalid = element;
}
}
});
if (valid) {
submit_form_via(event.target);
} else if (first_invalid) {
/* focus the first invalid element, if validation went south */
first_invalid.focus();
}
}
/**
* test if node is a submit button
*/
function is_submit_button(node) {
return(
/* must be an input or button element... */
(node.nodeName === 'INPUT' || node.nodeName === 'BUTTON') && (
/* ...and have a submitting type */
node.type === 'image' || node.type === 'submit')
);
}
/**
* test, if the click event would trigger a submit
*/
function is_submitting_click(event) {
return(
/* prevented default: won't trigger a submit */
!event.defaultPrevented && (
/* left button or middle button (submits in Chrome) */
!('button' in event) || event.button < 2) &&
/* must be a submit button... */
is_submit_button(event.target) &&
/* the button needs a form, that's going to be submitted */
event.target.form &&
/* again, if the form should not be validated, we're out of the game */
!event.target.form.hasAttribute('novalidate')
);
}
/**
* test, if the keypress event would trigger a submit
*/
function is_submitting_keypress(event) {
return(
/* prevented default: won't trigger a submit */
!event.defaultPrevented && (
/* <Enter> was pressed... */
event.keyCode === 13 &&
/* ...on an <input> or <button> */
event.target.nodeName === 'INPUT' &&
/* this is a standard text input field (not checkbox, ...) */
text_types.indexOf(event.target.type) > -1 ||
/* or <Enter> or <Space> was pressed... */
(event.keyCode === 13 || event.keyCode === 32) &&
/* ...on a submit button */
is_submit_button(event.target)) &&
/* there's a form... */
event.target.form &&
/* ...and the form allows validation */
!event.target.form.hasAttribute('novalidate')
);
}
/**
* catch explicit submission by click on a button
*/
function click_handler(event) {
if (is_submitting_click(event)) {
if (is_submit_button(event.target) && event.target.hasAttribute('formnovalidate')) {
/* if validation should be ignored, we're not interested in any checks */
submit_form_via(event.target);
} else {
check(event);
}
}
}
/**
* catch explicit submission by click on a button, but circumvent validation
*/
function ignored_click_handler(event) {
if (is_submitting_click(event)) {
submit_form_via(event.target);
}
}
/**
* catch implicit submission by pressing <Enter> in some situations
*/
function keypress_handler(event) {
if (is_submitting_keypress(event)) {
/* check, that there is no submit button in the form. Otherwise
* that should be clicked. */
var el = event.target.form.elements.length;
var submit;
for (var i = 0; i < el; i++) {
if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) {
submit = event.target.form.elements[i];
break;
}
}
if (submit) {
event.preventDefault();
submit.click();
} else {
check(event);
}
}
}
/**
* catch implicit submission by pressing <Enter> in some situations, but circumvent validation
*/
function ignored_keypress_handler(event) {
if (is_submitting_keypress(event)) {
/* check, that there is no submit button in the form. Otherwise
* that should be clicked. */
var el = event.target.form.elements.length;
var submit;
for (var i = 0; i < el; i++) {
if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) {
submit = event.target.form.elements[i];
break;
}
}
if (submit) {
event.preventDefault();
submit.click();
} else {
submit_form_via(event.target);
}
}
}
/**
* catch all relevant events _prior_ to a form being submitted
*
* @param bool ignore bypass validation, when an attempt to submit the
* form is detected.
*/
function catch_submit(listening_node) {
var ignore = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (ignore) {
listening_node.addEventListener('click', ignored_click_handler);
listening_node.addEventListener('keypress', ignored_keypress_handler);
} else {
listening_node.addEventListener('click', click_handler);
listening_node.addEventListener('keypress', keypress_handler);
}
}
/**
* decommission the event listeners from catch_submit() again
*/
function uncatch_submit(listening_node) {
listening_node.removeEventListener('click', ignored_click_handler);
listening_node.removeEventListener('keypress', ignored_keypress_handler);
listening_node.removeEventListener('click', click_handler);
listening_node.removeEventListener('keypress', keypress_handler);
}
/**
* remove `property` from element and restore _original_property, if present
*/
function uninstall_property (element, property) {
delete element[property];
var original_descriptor = Object.getOwnPropertyDescriptor(element, '_original_' + property);
if (original_descriptor) {
Object.defineProperty(element, property, original_descriptor);
}
}
/**
* add `property` to an element
*
* js> installer(element, 'foo', { value: 'bar' });
* js> assert(element.foo === 'bar');
*/
function install_property (element, property, descriptor) {
descriptor.configurable = true;
descriptor.enumerable = true;
if ('value' in descriptor) {
descriptor.writable = true;
}
var original_descriptor = Object.getOwnPropertyDescriptor(element, property);
if (original_descriptor) {
/* we already installed that property... */
if (original_descriptor.get && original_descriptor.get.__hyperform || original_descriptor.value && original_descriptor.value.__hyperform) {
return;
}
/* publish existing property under new name, if it's not from us */
Object.defineProperty(element, '_original_' + property, original_descriptor);
}
delete element[property];
Object.defineProperty(element, property, descriptor);
}
function is_field (element) {
return element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement || element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLFieldSetElement || element === window.HTMLButtonElement.prototype || element === window.HTMLInputElement.prototype || element === window.HTMLSelectElement.prototype || element === window.HTMLTextAreaElement.prototype || element === window.HTMLFieldSetElement.prototype;
}
/**
* set a custom validity message or delete it with an empty string
*/
function setCustomValidity(element, msg) {
message_store.set(element, msg, true);
}
function sprintf (str) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var args_length = args.length;
var global_index = 0;
return str.replace(/%([0-9]+\$)?([sl])/g, function (match, position, type) {
var local_index = global_index;
if (position) {
local_index = Number(position.replace(/\$$/, '')) - 1;
}
global_index += 1;
var arg = '';
if (args_length > local_index) {
arg = args[local_index];
}
if (arg instanceof Date || typeof arg === 'number' || arg instanceof Number) {
/* try getting a localized representation of dates and numbers, if the
* browser supports this */
if (type === 'l') {
arg = (arg.toLocaleString || arg.toString).call(arg);
} else {
arg = arg.toString();
}
}
return arg;
});
}
/* For a given date, get the ISO week number
*
* Source: http://stackoverflow.com/a/6117889/113195
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function get_week_of_year (d) {
/* Copy date so don't modify original */
d = new Date(+d);
d.setUTCHours(0, 0, 0);
/* Set to nearest Thursday: current date + 4 - current day number
* Make Sunday's day number 7 */
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
/* Get first day of year */
var yearStart = new Date(d.getUTCFullYear(), 0, 1);
/* Calculate full weeks to nearest Thursday */
var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
/* Return array of year and week number */
return [d.getUTCFullYear(), weekNo];
}
function pad(num) {
var size = arguments.length <= 1 || arguments[1] === undefined ? 2 : arguments[1];
var s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
}
/**
* calculate a string from a date according to HTML5
*/
function date_to_string(date, element_type) {
if (!(date instanceof Date)) {
return null;
}
switch (element_type) {
case 'datetime':
return date_to_string(date, 'date') + 'T' + date_to_string(date, 'time');
case 'datetime-local':
return sprintf('%s-%s-%sT%s:%s:%s.%s', date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate()), pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()), pad(date.getMilliseconds(), 3)).replace(/(:00)?\.000$/, '');
case 'date':
return sprintf('%s-%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1), pad(date.getUTCDate()));
case 'month':
return sprintf('%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1));
case 'week':
var params = get_week_of_year(date);
return sprintf.call(null, '%s-W%s', params[0], pad(params[1]));
case 'time':
return sprintf('%s:%s:%s.%s', pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()), pad(date.getUTCMilliseconds(), 3)).replace(/(:00)?\.000$/, '');
}
return null;
}
/**
* return a new Date() representing the ISO date for a week number
*
* @see http://stackoverflow.com/a/16591175/113195
*/
function get_date_from_week (week, year) {
var date = new Date(Date.UTC(year, 0, 1 + (week - 1) * 7));
if (date.getUTCDay() <= 4 /* thursday */) {
date.setUTCDate(date.getUTCDate() - date.getUTCDay() + 1);
} else {
date.setUTCDate(date.getUTCDate() + 8 - date.getUTCDay());
}
return date;
}
/**
* calculate a date from a string according to HTML5
*/
function string_to_date (string, element_type) {
var date = new Date(0);
var ms;
switch (element_type) {
case 'datetime':
if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) {
return null;
}
ms = RegExp.$7 || '000';
while (ms.length < 3) {
ms += '0';
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
date.setUTCHours(Number(RegExp.$4), Number(RegExp.$5), Number(RegExp.$6 || 0), Number(ms));
return date;
case 'date':
if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})$/.test(string)) {
return null;
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
return date;
case 'month':
if (!/^([0-9]{4,})-([0-9]{2})$/.test(string)) {
return null;
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, 1);
return date;
case 'week':
if (!/^([0-9]{4,})-W(0[1-9]|[1234][0-9]|5[0-3])$/.test(string)) {
return null;
}
return get_date_from_week(Number(RegExp.$2), Number(RegExp.$1));
case 'time':
if (!/^([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) {
return null;
}
ms = RegExp.$4 || '000';
while (ms.length < 3) {
ms += '0';
}
date.setUTCHours(Number(RegExp.$1), Number(RegExp.$2), Number(RegExp.$3 || 0), Number(ms));
return date;
}
return null;
}
/**
* calculate a date from a string according to HTML5
*/
function string_to_number (string, element_type) {
var rval = string_to_date(string, element_type);
if (rval !== null) {
return +rval;
}
/* not parseFloat, because we want NaN for invalid values like "1.2xxy" */
return Number(string);
}
/**
* get the element's type in a backwards-compatible way
*/
function get_type (element) {
if (element instanceof window.HTMLTextAreaElement) {
return 'textarea';
} else if (element instanceof window.HTMLSelectElement) {
return element.hasAttribute('multiple') ? 'select-multiple' : 'select-one';
} else if (element instanceof window.HTMLButtonElement) {
return (element.getAttribute('type') || 'submit').toLowerCase();
} else if (element instanceof window.HTMLInputElement) {
var attr = (element.getAttribute('type') || '').toLowerCase();
if (attr && inputs.indexOf(attr) > -1) {
return attr;
} else {
/* perhaps the DOM has in-depth knowledge. Take that before returning
* 'text'. */
return element.type || 'text';
}
}
return '';
}
/**
* the following validation messages are from Firefox source,
* http://mxr.mozilla.org/mozilla-central/source/dom/locales/en-US/chrome/dom/dom.properties
* released under MPL license, http://mozilla.org/MPL/2.0/.
*/
var catalog = {
en: {
TextTooLong: 'Please shorten this text to %l characters or less (you are currently using %l characters).',
ValueMissing: 'Please fill out this field.',
CheckboxMissing: 'Please check this box if you want to proceed.',
RadioMissing: 'Please select one of these options.',
FileMissing: 'Please select a file.',
SelectMissing: 'Please select an item in the list.',
InvalidEmail: 'Please enter an email address.',
InvalidURL: 'Please enter a URL.',
PatternMismatch: 'Please match the requested format.',
PatternMismatchWithTitle: 'Please match the requested format: %l.',
NumberRangeOverflow: 'Please select a value that is no more than %l.',
DateRangeOverflow: 'Please select a value that is no later than %l.',
TimeRangeOverflow: 'Please select a value that is no later than %l.',
NumberRangeUnderflow: 'Please select a value that is no less than %l.',
DateRangeUnderflow: 'Please select a value that is no earlier than %l.',
TimeRangeUnderflow: 'Please select a value that is no earlier than %l.',
StepMismatch: 'Please select a valid value. The two nearest valid values are %l and %l.',
StepMismatchOneValue: 'Please select a valid value. The nearest valid value is %l.',
BadInputNumber: 'Please enter a number.'
}
};
var language = 'en';
function set_language(newlang) {
language = newlang;
}
function add_translation(lang, new_catalog) {
if (!(lang in catalog)) {
catalog[lang] = {};
}
for (var key in new_catalog) {
if (new_catalog.hasOwnProperty(key)) {
catalog[lang][key] = new_catalog[key];
}
}
}
function _ (s) {
if (language in catalog && s in catalog[language]) {
return catalog[language][s];
} else if (s in catalog.en) {
return catalog.en[s];
}
return s;
}
var default_step = {
'datetime-local': 60,
datetime: 60,
time: 60
};
var step_scale_factor = {
'datetime-local': 1000,
datetime: 1000,
date: 86400000,
week: 604800000,
time: 1000
};
var default_step_base = {
week: -259200000
};
var default_min = {
range: 0
};
var default_max = {
range: 100
};
/**
* get previous and next valid values for a stepped input element
*/
function get_next_valid (element) {
var n = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
var type = get_type(element);
var aMin = element.getAttribute('min');
var min = default_min[type] || NaN;
if (aMin) {
var pMin = string_to_number(aMin, type);
if (!isNaN(pMin)) {
min = pMin;
}
}
var aMax = element.getAttribute('max');
var max = default_max[type] || NaN;
if (aMax) {
var pMax = string_to_number(aMax, type);
if (!isNaN(pMax)) {
max = pMax;
}
}
var aStep = element.getAttribute('step');
var step = default_step[type] || 1;
if (aStep && aStep.toLowerCase() === 'any') {
/* quick return: we cannot calculate prev and next */
return [_('any value'), _('any value')];
} else if (aStep) {
var pStep = string_to_number(aStep, type);
if (!isNaN(pStep)) {
step = pStep;
}
}
var default_value = string_to_number(element.getAttribute('value'), type);
var value = string_to_number(element.value || element.getAttribute('value'), type);
if (isNaN(value)) {
/* quick return: we cannot calculate without a solid base */
return [_('any valid value'), _('any valid value')];
}
var step_base = !isNaN(min) ? min : !isNaN(default_value) ? default_value : default_step_base[type] || 0;
var scale = step_scale_factor[type] || 1;
var prev = step_base + Math.floor((value - step_base) / (step * scale)) * (step * scale) * n;
var next = step_base + (Math.floor((value - step_base) / (step * scale)) + 1) * (step * scale) * n;
if (prev < min) {
prev = null;
} else if (prev > max) {
prev = max;
}
if (next > max) {
next = null;
} else if (next < min) {
next = min;
}
/* convert to date objects, if appropriate */
if (dates.indexOf(type) > -1) {
prev = date_to_string(new Date(prev), type);
next = date_to_string(new Date(next), type);
}
return [prev, next];
}
/**
* implement the valueAsDate functionality
*
* @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate
*/
function valueAsDate(element) {
var value = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1];
var type = get_type(element);
if (dates.indexOf(type) > -1) {
if (value !== undefined) {
/* setter: value must be null or a Date() */
if (value === null) {
element.value = '';
} else if (value instanceof Date) {
if (isNaN(value.getTime())) {
element.value = '';
} else {
element.value = date_to_string(value, type);
}
} else {
throw new window.DOMException('valueAsDate setter encountered invalid value', 'TypeError');
}
return;
}
var value_date = string_to_date(element.value, type);
return value_date instanceof Date ? value_date : null;
} else if (value !== undefined) {
/* trying to set a date on a not-date input fails */
throw new window.DOMException('valueAsDate setter cannot set date on this element', 'InvalidStateError');
}
return null;
}
/**
* implement the valueAsNumber functionality
*
* @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasnumber
*/
function valueAsNumber(element) {
var value = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1];
var type = get_type(element);
if (numbers.indexOf(type) > -1) {
if (type === 'range' && element.hasAttribute('multiple')) {
/* @see https://html.spec.whatwg.org/multipage/forms.html#do-not-apply */
return NaN;
}
if (value !== undefined) {
/* setter: value must be NaN or a finite number */
if (isNaN(value)) {
element.value = '';
} else if (typeof value === 'number' && window.isFinite(value)) {
try {
/* try setting as a date, but... */
valueAsDate(element, new Date(value));
} catch (e) {
/* ... when valueAsDate is not responsible, ... */
if (!(e instanceof window.DOMException)) {
throw e;
}
/* ... set it via Number.toString(). */
element.value = value.toString();
}
} else {
throw new window.DOMException('valueAsNumber setter encountered invalid value', 'TypeError');
}
return;
}
return string_to_number(element.value, type);
} else if (value !== undefined) {
/* trying to set a number on a not-number input fails */
throw new window.DOMException('valueAsNumber setter cannot set number on this element', 'InvalidStateError');
}
return NaN;
}
/**
*
*/
function stepDown(element) {
var n = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
if (numbers.indexOf(get_type(element)) === -1) {
throw new window.DOMException('stepDown encountered invalid type', 'InvalidStateError');
}
if ((element.getAttribute('step') || '').toLowerCase() === 'any') {
throw new window.DOMException('stepDown encountered step "any"', 'InvalidStateError');
}
var _get_next_valid = get_next_valid(element, n);
var prev = _get_next_valid.prev;
var next = _get_next_valid.next;
if (prev !== null) {
valueAsNumber(element, prev);
}
}
/**
*
*/
function stepUp(element) {
var n = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
if (numbers.indexOf(get_type(element)) === -1) {
throw new window.DOMException('stepUp encountered invalid type', 'InvalidStateError');
}
if ((element.getAttribute('step') || '').toLowerCase() === 'any') {
throw new window.DOMException('stepUp encountered step "any"', 'InvalidStateError');
}
var _get_next_valid = get_next_valid(element, n);
var prev = _get_next_valid.prev;
var next = _get_next_valid.next;
if (next !== null) {
valueAsNumber(element, next);
}
}
/**
* get the validation message for an element, empty string, if the element
* satisfies all constraints.
*/
function validationMessage(element) {
var msg = message_store.get(element);
if (!msg) {
return '';
}
/* make it a primitive again, since message_store returns String(). */
return msg.toString();
}
/**
* check, if an element will be subject to HTML5 validation at all
*/
function willValidate(element) {
return is_validation_candidate(element);
}
var gA = function gA(prop) {
return function () {
return this.getAttribute(prop);
};
};
var sA = function sA(prop) {
return function (value) {
this.setAttribute(prop, value);
};
};
var gAb = function gAb(prop) {
return function () {
return this.hasAttribute(prop);
};
};
var sAb = function sAb(prop) {
return function (value) {
if (value) {
this.setAttribute(prop, prop);
} else {
this.removeAttribute(prop);
}
};
};
var gAn = function gAn(prop) {
return function () {
return Math.max(0, Number(this.getAttribute(prop)));
};
};
var sAn = function sAn(prop) {
return function (value) {
if (/^[0-9]+$/.test(value)) {
this.setAttribute(prop, value);
}
};
};
function install_properties(element) {
var _arr = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step'];
for (var _i = 0; _i < _arr.length; _i++) {
var prop = _arr[_i];
install_property(element, prop, {
get: gA(prop),
set: sA(prop)
});
}
var _arr2 = ['multiple', 'required', 'readOnly'];
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var _prop = _arr2[_i2];
install_property(element, _prop, {
get: gAb(_prop.toLowerCase()),
set: sAb(_prop.toLowerCase())
});
}
var _arr3 = ['minLength', 'maxLength'];
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var _prop2 = _arr3[_i3];
install_property(element, _prop2, {
get: gAn(_prop2.toLowerCase()),
set: sAn(_prop2.toLowerCase())
});
}
}
function uninstall_properties(element) {
var _arr4 = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step', 'multiple', 'required', 'readOnly', 'minLength', 'maxLength'];
for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
var prop = _arr4[_i4];
uninstall_property(element, prop);
}
}
var polyfills = {
checkValidity: {
value: mark(function () {
return checkValidity(this);
})
},
reportValidity: {
value: mark(function () {
return reportValidity(this);
})
},
setCustomValidity: {
value: mark(function (msg) {
return setCustomValidity(this, msg);
})
},
stepDown: {
value: mark(function () {
var n = arguments.length <= 0 || arguments[0] === undefined ? 1 : arguments[0];
return stepDown(this, n);
})
},
stepUp: {
value: mark(function () {
var n = arguments.length <= 0 || arguments[0] === undefined ? 1 : arguments[0];
return stepUp(this, n);
})
},
validationMessage: {
get: mark(function () {
return validationMessage(this);
})
},
validity: {
get: mark(function () {
return ValidityState(this);
})
},
valueAsDate: {
get: mark(function () {
return valueAsDate(this);
}),
set: mark(function (value) {
valueAsDate(this, value);
})
},
valueAsNumber: {
get: mark(function () {
return valueAsNumber(this);
}),
set: mark(function (value) {
valueAsNumber(this, value);
})
},
willValidate: {
get: mark(function () {
return willValidate(this);
})
}
};
function polyfill (element) {
if (is_field(element)) {
for (var prop in polyfills) {
install_property(element, prop, polyfills[prop]);
}
install_properties(element);
} else if (element instanceof window.HTMLFormElement || element === window.HTMLFormElement.prototype) {
install_property(element, 'checkValidity', polyfills.checkValidity);
install_property(element, 'reportValidity', polyfills.reportValidity);
}
}
function polyunfill (element) {
if (is_field(element)) {
uninstall_property(element, 'checkValidity');
uninstall_property(element, 'reportValidity');
uninstall_property(element, 'setCustomValidity');
uninstall_property(element, 'stepDown');
uninstall_property(element, 'stepUp');
uninstall_property(element, 'validationMessage');
uninstall_property(element, 'validity');
uninstall_property(element, 'valueAsDate');
uninstall_property(element, 'valueAsNumber');
uninstall_property(element, 'willValidate');
uninstall_properties(element);
} else if (element instanceof window.HTMLFormElement) {
uninstall_property(element, 'checkValidity');
uninstall_property(element, 'reportValidity');
}
}
var instances = new WeakMap();
/**
* wrap <form>s, window or document, that get treated with the global
* hyperform()
*/
function Wrapper(form, settings) {
/* do not allow more than one instance per form. Otherwise we'd end
* up with double event handlers, polyfills re-applied, ... */
var existing = instances.get(form);
if (existing) {
existing.settings = settings;
return existing;
}
this.form = form;
this.settings = settings;
this.revalidator = this.revalidate.bind(this);
instances.set(form, this);
catch_submit(form, settings.revalidate === 'never');
if (form === window || form instanceof window.HTMLDocument) {
/* install on the prototypes, when called for the whole document */
this.install([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]);
polyfill(window.HTMLFormElement);
} else if (form instanceof window.HTMLFormElement || form instanceof window.HTMLFieldSetElement) {
this.install(form.elements);
if (form instanceof window.HTMLFormElement) {
polyfill(form);
}
}
if (settings.revalidate === 'oninput' || settings.revalidate === 'hybrid') {
/* in a perfect world we'd just bind to "input", but support here is
* abysmal: http://caniuse.com/#feat=input-event */
form.addEventListener('keyup', this.revalidator);
form.addEventListener('change', this.revalidator);
}
if (settings.revalidate === 'onblur' || settings.revalidate === 'hybrid') {
/* useCapture=true, because `blur` doesn't bubble. See
* https://developer.mozilla.org/en-US/docs/Web/Events/blur#Event_delegation
* for a discussion */
form.addEventListener('blur', this.revalidator, true);
}
}
Wrapper.prototype = {
destroy: function destroy() {
uncatch_submit(this.form);
instances.delete(this.form);
this.form.removeEventListener('keyup', this.revalidator);
this.form.removeEventListener('change', this.revalidator);
this.form.removeEventListener('blur', this.revalidator, true);
if (this.form === window || this.form instanceof window.HTMLDocument) {
this.uninstall([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]);
polyunfill(window.HTMLFormElement);
} else if (this.form instanceof window.HTMLFormElement || this.form instanceof window.HTMLFieldSetElement) {
this.uninstall(this.form.elements);
if (this.form instanceof window.HTMLFormElement) {
polyunfill(this.form);
}
}
},
/**
* revalidate an input element
*/
revalidate: function revalidate(event) {
if (event.target instanceof window.HTMLButtonElement || event.target instanceof window.HTMLTextAreaElement || event.target instanceof window.HTMLSelectElement || event.target instanceof window.HTMLInputElement) {
if (this.settings.revalidate === 'hybrid') {
/* "hybrid" somewhat simulates what browsers do. See for example
* Firefox's :-moz-ui-invalid pseudo-class:
* https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-invalid */
if (event.type === 'blur' && event.target.value !== event.target.defaultValue || event.target.validity.valid) {
/* on blur, update the report when the value has changed from the
* default or when the element is valid (possibly removing a still
* standing invalidity report). */
reportValidity(event.target);
} else if (event.type === 'keyup' || event.type === 'change') {
if (event.target.validity.valid) {
// report instantly, when an element becomes valid,
// postpone report to blur event, when an element is invalid
reportValidity(event.target);
}
}
} else {
reportValidity(event.target);
}
}
},
/**
* install the polyfills on each given element
*
* If you add elements dynamically, you have to call install() on them
* yourself:
*
* js> var form = hyperform(document.forms[0]);
* js> document.forms[0].appendChild(input);
* js> form.install(input);
*
* You can skip this, if you called hyperform on window or document.
*/
install: function install(els) {
if (els instanceof window.Element) {
els = [els];
}
var els_length = els.length;
for (var i = 0; i < els_length; i++) {
polyfill(els[i]);
}
},
uninstall: function uninstall(els) {
if (els instanceof window.Element) {
els = [els];
}
var els_length = els.length;
for (var i = 0; i < els_length; i++) {
polyunfill(els[i]);
}
}
};
/**
* try to get the appropriate wrapper for a specific element by looking up
* its parent chain
*
* @return Wrapper | undefined
*/
function get_wrapper(element) {
var wrapped;
if (element.form) {
/* try a shortcut with the element's <form> */
wrapped = instances.get(element.form);
}
/* walk up the parent nodes until document (including) */
while (!wrapped && element) {
wrapped = instances.get(element);
element = element.parentNode;
}
if (!wrapped) {
/* try the global instance, if exists. This may also be undefined. */
wrapped = instances.get(window);
}
return wrapped;
}
/**
* check if an element is a candidate for constraint validation
*
* @see https://html.spec.whatwg.org/multipage/forms.html#barred-from-constraint-validation
*/
function is_validation_candidate (element) {
/* it must be any of those elements */
if (element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement) {
var type = get_type(element);
/* its type must be in the whitelist or missing (select, textarea) */
if (!type || non_inputs.indexOf(type) > -1 || validation_candidates.indexOf(type) > -1) {
/* it mustn't be disabled or readonly */
if (!element.hasAttribute('disabled') && !element.hasAttribute('readonly')) {
var wrapped_form = get_wrapper(element);
/* it hasn't got the (non-standard) attribute 'novalidate' or its
* parent form has got the strict parameter */
if (wrapped_form && wrapped_form.settings.novalidate_on_elements || !element.hasAttribute('novalidate') || !element.noValidate) {
/* it isn't part of a <fieldset disabled> */
var p = element.parentNode;
while (p && p.nodeType === 1) {
if (p instanceof window.HTMLFieldSetElement && p.hasAttribute('disabled')) {
/* quick return, if it's a child of a disabled fieldset */
return false;
} else if (p.nodeName.toUpperCase() === 'DATALIST') {
/* quick return, if it's a child of a datalist
* Do not use HTMLDataListElement to support older browsers,
* too.
* @see https://html.spec.whatwg.org/multipage/forms.html#the-datalist-element:barred-from-constraint-validation
*/
return false;
} else if (p === element.form) {
/* the outer boundary. We can stop looking for relevant
* fieldsets. */
break;
}
p = p.parentNode;
}
/* then it's a candidate */
return true;
}
}
}
}
/* this is no HTML5 validation candidate... */
return false;
}
/**
* patch String.length to account for non-BMP characters
*
* @see https://mathiasbynens.be/notes/javascript-unicode
* We do not use the simple [...str].length, because it needs a ton of
* polyfills in older browsers.
*/
function unicode_string_length (str) {
return str.match(/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/g).length;
}
/**
* internal storage for custom error messages
*/
var store$1 = new WeakMap();
/**
* register custom error messages per element
*/
var custom_messages = {
set: function set(element, validator, message) {
var messages = store$1.get(element) || {};
messages[validator] = message;
store$1.set(element, messages);
return custom_messages;
},
get: function get(element, validator) {
var _default = arguments.length <= 2 || arguments[2] === undefined ? undefined : arguments[2];
var messages = store$1.get(element);
if (messages === undefined || !(validator in messages)) {
var data_id = 'data-' + validator.replace(/[A-Z]/g, '-$&').toLowerCase();
if (element.hasAttribute(data_id)) {
/* if the element has a data-validator attribute, use this as fallback.
* E.g., if validator == 'valueMissing', the element can specify a
* custom validation message like this:
* <input data-value-missing="Oh noes!">
*/
return element.getAttribute(data_id);
}
return _default;
}
return messages[validator];
},
delete: function _delete(element) {
var validator = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
if (!validator) {
return store$1.delete(element);
}
var messages = store$1.get(element) || {};
if (validator in messages) {
delete messages[validator];
store$1.set(element, messages);
return true;
}
return false;
}
};
var internal_registry = new WeakMap();
/**
* A registry for custom validators
*
* slim wrapper around a WeakMap to ensure the values are arrays
* (hence allowing > 1 validators per element)
*/
var custom_validator_registry = {
set: function set(element, validator) {
var current = internal_registry.get(element) || [];
current.push(validator);
internal_registry.set(element, current);
return custom_validator_registry;
},
get: function get(element) {
return internal_registry.get(element) || [];
},
delete: function _delete(element) {
return internal_registry.delete(element);
}
};
/**
* test whether the element suffers from bad input
*/
function test_bad_input (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || input_checked.indexOf(type) === -1) {
/* we're not interested, thanks! */
return true;
}
/* the browser hides some bad input from the DOM, e.g. malformed numbers,
* email addresses with invalid punycode representation, ... We try to resort
* to the original method here. The assumption is, that a browser hiding
* bad input will hopefully also always support a proper
* ValidityState.badInput */
if (!element.value) {
if ('_original_validity' in element && !element._original_validity.__hyperform) {
return !element._original_validity.badInput;
}
/* no value and no original badInput: Assume all's right. */
return true;
}
var result = true;
switch (type) {
case 'color':
result = /^#[a-f0-9]{6}$/.test(element.value);
break;
case 'number':
case 'range':
result = !isNaN(Number(element.value));
break;
case 'datetime':
case 'date':
case 'month':
case 'week':
case 'time':
result = string_to_date(element.value, type) !== null;
break;
case 'datetime-local':
result = /^([0-9]{4,})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(element.value);
break;
case 'tel':
/* spec says No! Phone numbers can have all kinds of formats, so this
* is expected to be a free-text field. */
// TODO we could allow a setting 'phone_regex' to be evaluated here.
break;
case 'email':
break;
}
return result;
}
/**
* test the max attribute
*
* we use Number() instead of parseFloat(), because an invalid attribute
* value like "123abc" should result in an error.
*/
function test_max (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('max')) {
/* we're not responsible here */
return true;
}
var value = void 0,
max = void 0;
if (dates.indexOf(type) > -1) {
value = 1 * string_to_date(element.value, type);
max = 1 * (string_to_date(element.getAttribute('max'), type) || NaN);
} else {
value = Number(element.value);
max = Number(element.getAttribute('max'));
}
return isNaN(max) || value <= max;
}
/**
* test the maxlength attribute
*/
function test_maxlength (element) {
if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('maxlength') || !element.getAttribute('maxlength') // catch maxlength=""
) {
return true;
}
var maxlength = parseInt(element.getAttribute('maxlength'), 10);
/* check, if the maxlength value is usable at all.
* We allow maxlength === 0 to basically disable input (Firefox does, too).
*/
if (isNaN(maxlength) || maxlength < 0) {
return true;
}
return unicode_string_length(element.value) <= maxlength;
}
/**
* test the min attribute
*
* we use Number() instead of parseFloat(), because an invalid attribute
* value like "123abc" should result in an error.
*/
function test_min (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('min')) {
/* we're not responsible here */
return true;
}
var value = void 0,
min = void 0;
if (dates.indexOf(type) > -1) {
value = 1 * string_to_date(element.value, type);
min = 1 * (string_to_date(element.getAttribute('min'), type) || NaN);
} else {
value = Number(element.value);
min = Number(element.getAttribute('min'));
}
return isNaN(min) || value >= min;
}
/**
* test the minlength attribute
*/
function test_minlength (element) {
if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('minlength') || !element.getAttribute('minlength') // catch minlength=""
) {
return true;
}
var minlength = parseInt(element.getAttribute('minlength'), 10);
/* check, if the minlength value is usable at all. */
if (isNaN(minlength) || minlength < 0) {
return true;
}
return unicode_string_length(element.value) >= minlength;
}
/**
* test the pattern attribute
*/
function test_pattern (element) {
return !is_validation_candidate(element) || !element.value || !element.hasAttribute('pattern') || new RegExp('^(?:' + element.getAttribute('pattern') + ')$').test(element.value);
}
/**
* test the required attribute
*/
function test_required (element) {
if (!is_validation_candidate(element) || !element.hasAttribute('required')) {
/* nothing to do */
return true;
}
/* we don't need get_type() for element.type, because "checkbox" and "radio"
* are well supported. */
switch (element.type) {
case 'checkbox':
return element.checked;
//break;
case 'radio':
/* radio inputs have "required" fulfilled, if _any_ other radio
* with the same name in this form is checked. */
return !!(element.checked || element.form && Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) {
return radio.name === element.name && radio.form === element.form && radio.checked;
}).length > 0);
//break;
default:
return !!element.value;
}
}
/**
* test the step attribute
*/
function test_step (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || numbers.indexOf(type) === -1 || (element.getAttribute('step') || '').toLowerCase() === 'any') {
/* we're not responsible here. Note: If no step attribute is given, we
* need to validate against the default step as per spec. */
return true;
}
var step = element.getAttribute('step');
if (step) {
step = string_to_number(step, type);
} else {
step = default_step[type] || 1;
}
if (step <= 0 || isNaN(step)) {
/* error in specified "step". We cannot validate against it, so the value
* is true. */
return true;
}
var scale = step_scale_factor[type] || 1;
var value = string_to_number(element.value, type);
var min = string_to_number(element.getAttribute('min') || element.getAttribute('value') || '', type);
if (isNaN(min)) {
min = default_step_base[type] || 0;
}
if (type === 'month') {
/* type=month has month-wide steps. See
* https://html.spec.whatwg.org/multipage/forms.html#month-state-%28type=month%29
*/
min = new Date(min).getUTCFullYear() * 12 + new Date(min).getUTCMonth();
value = new Date(value).getUTCFullYear() * 12 + new Date(value).getUTCMonth();
}
var result = Math.abs(min - value) % (step * scale);
return result < 0.00000001 ||
/* crappy floating-point arithmetics! */
result > step * scale - 0.00000001;
}
var ws_on_start_or_end = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
/**
* trim a string of whitespace
*
* We don't use String.trim() to remove the need to polyfill it.
*/
function trim (str) {
return str.replace(ws_on_start_or_end, '');
}
/**
* split a string on comma and trim the components
*
* As specified at
* https://html.spec.whatwg.org/multipage/infrastructure.html#split-a-string-on-commas
* plus removing empty entries.
*/
function comma_split (str) {
return str.split(',').map(function (item) {
return trim(item);
}).filter(function (b) {
return b;
});
}
/* we use a dummy <a> where we set the href to test URL validity
* The definition is out of the "global" scope so that JSDOM can be instantiated
* after loading Hyperform for tests.
*/
var url_canary;
/* see https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address */
var email_pattern = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/**
* test the type-inherent syntax
*/
function test_type (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || type !== 'file' && !element.value || type !== 'file' && type_checked.indexOf(type) === -1) {
/* we're not responsible for this element */
return true;
}
var is_valid = true;
switch (type) {
case 'url':
if (!url_canary) {
url_canary = document.createElement('a');
}
var value = trim(element.value);
url_canary.href = value;
is_valid = url_canary.href === value || url_canary.href === value + '/';
break;
case 'email':
if (element.hasAttribute('multiple')) {
is_valid = comma_split(element.value).every(function (value) {
return email_pattern.test(value);
});
} else {
is_valid = email_pattern.test(trim(element.value));
}
break;
case 'file':
if ('files' in element && element.files.length && element.hasAttribute('accept')) {
var patterns = comma_split(element.getAttribute('accept')).map(function (pattern) {
if (/^(audio|video|image)\/\*$/.test(pattern)) {
pattern = new RegExp('^' + RegExp.$1 + '/.+$');
}
return pattern;
});
if (!patterns.length) {
break;
}
fileloop: for (var i = 0; i < element.files.length; i++) {
/* we need to match a whitelist, so pre-set with false */
var file_valid = false;
patternloop: for (var j = 0; j < patterns.length; j++) {
var file = element.files[i];
var pattern = patterns[j];
var fileprop = file.type;
if (typeof pattern === 'string' && pattern.substr(0, 1) === '.') {
if (file.name.search('.') === -1) {
/* no match with any file ending */
continue patternloop;
}
fileprop = file.name.substr(file.name.lastIndexOf('.'));
}
if (fileprop.search(pattern) === 0) {
/* we found one match and can quit looking */
file_valid = true;
break patternloop;
}
}
if (!file_valid) {
is_valid = false;
break fileloop;
}
}
}
}
return is_valid;
}
/**
* boilerplate function for all tests but customError
*/
function check$1(test, react) {
return function (element) {
var invalid = !test(element);
if (invalid) {
react(element);
}
return invalid;
};
}
/**
* create a common function to set error messages
*/
function set_msg(element, msgtype, _default) {
message_store.set(element, custom_messages.get(element, msgtype, _default));
}
var badInput = check$1(test_bad_input, function (element) {
return set_msg(element, 'badInput', _('Please match the requested type.'));
});
function customError(element) {
/* check, if there are custom validators in the registry, and call
* them. */
var custom_validators = custom_validator_registry.get(element);
var cvl = custom_validators.length;
var valid = true;
if (cvl) {
for (var i = 0; i < cvl; i++) {
var result = custom_validators[i](element);
if (result !== undefined && !result) {
valid = false;
/* break on first invalid response */
break;
}
}
}
/* check, if there are other validity messages already */
if (valid) {
var msg = message_store.get(element);
valid = !(msg.toString() && 'is_custom' in msg);
}
return !valid;
}
var patternMismatch = check$1(test_pattern, function (element) {
set_msg(element, 'patternMismatch', element.title ? sprintf(_('PatternMismatchWithTitle'), element.title) : _('PatternMismatch'));
});
var rangeOverflow = check$1(test_max, function (element) {
var type = get_type(element);
var msg = void 0;
switch (type) {
case 'date':
case 'datetime':
case 'datetime-local':
msg = sprintf(_('DateRangeOverflow'), string_to_date(element.getAttribute('max'), type));
break;
case 'time':
msg = sprintf(_('TimeRangeOverflow'), string_to_date(element.getAttribute('max'), type));
break;
// case 'number':
default:
msg = sprintf(_('NumberRangeOverflow'), string_to_number(element.getAttribute('max'), type));
break;
}
set_msg(element, 'rangeOverflow', msg);
});
var rangeUnderflow = check$1(test_min, function (element) {
var type = get_type(element);
var msg = void 0;
switch (type) {
case 'date':
case 'datetime':
case 'datetime-local':
msg = sprintf(_('DateRangeUnderflow'), string_to_date(element.getAttribute('min'), type));
break;
case 'time':
msg = sprintf(_('TimeRangeUnderflow'), string_to_date(element.getAttribute('min'), type));
break;
// case 'number':
default:
msg = sprintf(_('NumberRangeUnderflow'), string_to_number(element.getAttribute('min'), type));
break;
}
set_msg(element, 'rangeUnderflow', msg);
});
var stepMismatch = check$1(test_step, function (element) {
var list = get_next_valid(element);
var min = list[0];
var max = list[1];
var sole = false;
var msg = void 0;
if (min === null) {
sole = max;
} else if (max === null) {
sole = min;
}
if (sole !== false) {
msg = sprintf(_('StepMismatchOneValue'), sole);
} else {
msg = sprintf(_('StepMismatch'), min, max);
}
set_msg(element, 'stepMismatch', msg);
});
var tooLong = check$1(test_maxlength, function (element) {
set_msg(element, 'tooLong', sprintf(_('TextTooLong'), element.getAttribute('maxlength'), unicode_string_length(element.value)));
});
var tooShort = check$1(test_minlength, function (element) {
set_msg(element, 'tooShort', sprintf(_('Please lengthen this text to %l characters or more (you are currently using %l characters).'), element.getAttribute('maxlength'), unicode_string_length(element.value)));
});
var typeMismatch = check$1(test_type, function (element) {
var msg = _('Please use the appropriate format.');
var type = get_type(element);
if (type === 'email') {
if (element.hasAttribute('multiple')) {
msg = _('Please enter a comma separated list of email addresses.');
} else {
msg = _('InvalidEmail');
}
} else if (type === 'url') {
msg = _('InvalidURL');
} else if (type === 'file') {
msg = _('Please select a file of the correct type.');
}
set_msg(element, 'typeMismatch', msg);
});
var valueMissing = check$1(test_required, function (element) {
var msg = _('ValueMissing');
var type = get_type(element);
if (type === 'checkbox') {
msg = _('CheckboxMissing');
} else if (type === 'radio') {
msg = _('RadioMissing');
} else if (type === 'file') {
if (element.hasAttribute('multiple')) {
msg = _('Please select one or more files.');
} else {
msg = _('FileMissing');
}
} else if (element instanceof window.HTMLSelectElement) {
msg = _('SelectMissing');
}
set_msg(element, 'valueMissing', msg);
});
var validity_state_checkers = {
badInput: badInput,
customError: customError,
patternMismatch: patternMismatch,
rangeOverflow: rangeOverflow,
rangeUnderflow: rangeUnderflow,
stepMismatch: stepMismatch,
tooLong: tooLong,
tooShort: tooShort,
typeMismatch: typeMismatch,
valueMissing: valueMissing
};
/**
* the validity state constructor
*/
var ValidityState = function ValidityState(element) {
if (!(element instanceof window.HTMLElement)) {
throw new Error('cannot create a ValidityState for a non-element');
}
var cached = ValidityState.cache.get(element);
if (cached) {
return cached;
}
if (!(this instanceof ValidityState)) {
/* working around a forgotten `new` */
return new ValidityState(element);
}
this.element = element;
ValidityState.cache.set(element, this);
};
/**
* the prototype for new validityState instances
*/
var ValidityStatePrototype = {};
ValidityState.prototype = ValidityStatePrototype;
ValidityState.cache = new WeakMap();
/**
* copy functionality from the validity checkers to the ValidityState
* prototype
*/
for (var prop in validity_state_checkers) {
Object.defineProperty(ValidityStatePrototype, prop, {
configurable: true,
enumerable: true,
get: function (func) {
return function () {
return func(this.element);
};
}(validity_state_checkers[prop]),
set: undefined
});
}
/**
* the "valid" property calls all other validity checkers and returns true,
* if all those return false.
*
* This is the major access point for _all_ other API methods, namely
* (check|report)Validity().
*/
Object.defineProperty(ValidityStatePrototype, 'valid', {
configurable: true,
enumerable: true,
get: function get() {
var wrapper = get_wrapper(this.element);
var validClass = wrapper && wrapper.settings.classes.valid || 'hf-valid';
var invalidClass = wrapper && wrapper.settings.classes.invalid || 'hf-invalid';
var validatedClass = wrapper && wrapper.settings.classes.validated || 'hf-validated';
this.element.classList.add(validatedClass);
if (is_validation_candidate(this.element)) {
for (var _prop in validity_state_checkers) {
if (validity_state_checkers[_prop](this.element)) {
this.element.classList.add(invalidClass);
this.element.classList.remove(validClass);
this.element.setAttribute('aria-invalid', 'true');
return false;
}
}
}
message_store.delete(this.element);
this.element.classList.remove(invalidClass);
this.element.classList.add(validClass);
this.element.setAttribute('aria-invalid', 'false');
return true;
},
set: undefined
});
/**
* mark the validity prototype, because that is what the client-facing
* code deals with mostly, not the property descriptor thing */
mark(ValidityStatePrototype);
/**
* check an element's validity with respect to it's form
*/
var checkValidity = return_hook_or('checkValidity', function (element) {
/* if this is a <form>, check validity of all child inputs */
if (element instanceof window.HTMLFormElement) {
return Array.prototype.map.call(element.elements, checkValidity).every(function (b) {
return b;
});
}
/* default is true, also for elements that are no validation candidates */
var valid = ValidityState(element).valid;
if (valid) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && wrapped_form.settings.valid_event) {
trigger_event(element, 'valid');
}
} else {
trigger_event(element, 'invalid', { cancelable: true });
}
return valid;
});
var version = '0.8.2';
/**
* public hyperform interface:
*/
function hyperform(form) {
var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref$strict = _ref.strict;
var strict = _ref$strict === undefined ? false : _ref$strict;
var revalidate = _ref.revalidate;
var valid_event = _ref.valid_event;
var extend_fieldset = _ref.extend_fieldset;
var novalidate_on_elements = _ref.novalidate_on_elements;
var classes = _ref.classes;
if (revalidate === undefined) {
/* other recognized values: 'oninput', 'onblur', 'onsubmit' and 'never' */
revalidate = strict ? 'onsubmit' : 'hybrid';
}
if (valid_event === undefined) {
valid_event = !strict;
}
if (extend_fieldset === undefined) {
extend_fieldset = !strict;
}
if (novalidate_on_elements === undefined) {
novalidate_on_elements = !strict;
}
if (!classes) {
classes = {};
}
var settings = { strict: strict, revalidate: revalidate, valid_event: valid_event, extend_fieldset: extend_fieldset, classes: classes };
if (form instanceof window.NodeList || form instanceof window.HTMLCollection || form instanceof Array) {
return Array.prototype.map.call(form, function (element) {
return hyperform(element, settings);
});
}
return new Wrapper(form, settings);
}
hyperform.version = version;
hyperform.checkValidity = checkValidity;
hyperform.reportValidity = reportValidity;
hyperform.setCustomValidity = setCustomValidity;
hyperform.stepDown = stepDown;
hyperform.stepUp = stepUp;
hyperform.validationMessage = validationMessage;
hyperform.ValidityState = ValidityState;
hyperform.valueAsDate = valueAsDate;
hyperform.valueAsNumber = valueAsNumber;
hyperform.willValidate = willValidate;
hyperform.set_language = function (lang) {
set_language(lang);return hyperform;
};
hyperform.add_translation = function (lang, catalog) {
add_translation(lang, catalog);return hyperform;
};
hyperform.set_renderer = function (renderer, action) {
Renderer.set(renderer, action);return hyperform;
};
hyperform.add_validator = function (element, validator) {
custom_validator_registry.set(element, validator);return hyperform;
};
hyperform.set_message = function (element, validator, message) {
custom_messages.set(element, validator, message);return hyperform;
};
hyperform.add_hook = function (hook, action, position) {
add_hook(hook, action, position);return hyperform;
};
hyperform.remove_hook = function (hook, action) {
remove_hook(hook, action);return hyperform;
};
return hyperform;
}); |
files/mui/1.1.19-rc1/react/mui-react.js | yyx990803/jsdelivr | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* MUI config module
* @module config
*/
/** Define module API */
module.exports = {
/** Use debug mode */
debug: true
};
},{}],2:[function(require,module,exports){
/**
* MUI CSS/JS jqLite module
* @module lib/jqLite
*/
'use strict';
/**
* Add a class to an element.
* @param {Element} element - The DOM element.
* @param {string} cssClasses - Space separated list of class names.
*/
function jqLiteAddClass(element, cssClasses) {
if (!cssClasses || !element.setAttribute) return;
var existingClasses = _getExistingClasses(element),
splitClasses = cssClasses.split(' '),
cssClass;
for (var i=0; i < splitClasses.length; i++) {
cssClass = splitClasses[i].trim();
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
}
element.setAttribute('class', existingClasses.trim());
}
/**
* Get or set CSS properties.
* @param {Element} element - The DOM element.
* @param {string} [name] - The property name.
* @param {string} [value] - The property value.
*/
function jqLiteCss(element, name, value) {
// Return full style object
if (name === undefined) {
return getComputedStyle(element);
}
var nameType = jqLiteType(name);
// Set multiple values
if (nameType === 'object') {
for (var key in name) element.style[_camelCase(key)] = name[key];
return;
}
// Set a single value
if (nameType === 'string' && value !== undefined) {
element.style[_camelCase(name)] = value;
}
var styleObj = getComputedStyle(element),
isArray = (jqLiteType(name) === 'array');
// Read single value
if (!isArray) return _getCurrCssProp(element, name, styleObj);
// Read multiple values
var outObj = {},
key;
for (var i=0; i < name.length; i++) {
key = name[i];
outObj[key] = _getCurrCssProp(element, key, styleObj);
}
return outObj;
}
/**
* Check if element has class.
* @param {Element} element - The DOM element.
* @param {string} cls - The class name string.
*/
function jqLiteHasClass(element, cls) {
if (!cls || !element.getAttribute) return false;
return (_getExistingClasses(element).indexOf(' ' + cls + ' ') > -1);
}
/**
* Return the type of a variable.
* @param {} somevar - The JavaScript variable.
*/
function jqLiteType(somevar) {
// handle undefined
if (somevar === undefined) return 'undefined';
// handle others (of type [object <Type>])
var typeStr = Object.prototype.toString.call(somevar);
if (typeStr.indexOf('[object ') === 0) {
return typeStr.slice(8, -1).toLowerCase();
} else {
throw "Could not understand type: " + typeStr;
}
}
/**
* Attach an event handler to a DOM element
* @param {Element} element - The DOM element.
* @param {string} type - The event type name.
* @param {Function} callback - The callback function.
* @param {Boolean} useCapture - Use capture flag.
*/
function jqLiteOn(element, type, callback, useCapture) {
useCapture = (useCapture === undefined) ? false : useCapture;
// add to DOM
element.addEventListener(type, callback, useCapture);
// add to cache
var cache = element._muiEventCache = element._muiEventCache || {};
cache[type] = cache[type] || [];
cache[type].push([callback, useCapture]);
}
/**
* Remove an event handler from a DOM element
* @param {Element} element - The DOM element.
* @param {string} type - The event type name.
* @param {Function} callback - The callback function.
* @param {Boolean} useCapture - Use capture flag.
*/
function jqLiteOff(element, type, callback, useCapture) {
useCapture = (useCapture === undefined) ? false : useCapture;
// remove from cache
var cache = element._muiEventCache = element._muiEventCache || {},
argsList = cache[type] || [],
args,
i;
i = argsList.length;
while (i--) {
args = argsList[i];
// remove all events if callback is undefined
if (callback === undefined ||
(args[0] === callback && args[1] === useCapture)) {
// remove from cache
argsList.splice(i, 1);
// remove from DOM
element.removeEventListener(type, args[0], args[1]);
}
}
}
/**
* Attach an event hander which will only execute once
* @param {Element} element - The DOM element.
* @param {string} type - The event type name.
* @param {Function} callback - The callback function.
* @param {Boolean} useCapture - Use capture flag.
*/
function jqLiteOne(element, type, callback, useCapture) {
jqLiteOn(element, type, function onFn(ev) {
// execute callback
if (callback) callback.apply(this, arguments);
// remove wrapper
jqLiteOff(element, type, onFn);
}, useCapture);
}
/**
* Return object representing top/left offset and element height/width.
* @param {Element} element - The DOM element.
*/
function jqLiteOffset(element) {
var win = window,
docEl = document.documentElement,
rect = element.getBoundingClientRect(),
viewLeft,
viewTop;
viewLeft = (win.pageXOffset || docEl.scrollLeft) - (docEl.clientLeft || 0);
viewTop = (win.pageYOffset || docEl.scrollTop) - (docEl.clientTop || 0);
return {
top: rect.top + viewTop,
left: rect.left + viewLeft,
height: rect.height,
width: rect.width
};
}
/**
* Attach a callback to the DOM ready event listener
* @param {Function} fn - The callback function.
*/
function jqLiteReady(fn) {
var done = false,
top = true,
doc = document,
win = doc.defaultView,
root = doc.documentElement,
add = doc.addEventListener ? 'addEventListener' : 'attachEvent',
rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent',
pre = doc.addEventListener ? '' : 'on';
var init = function(e) {
if (e.type == 'readystatechange' && doc.readyState != 'complete') {
return;
}
(e.type == 'load' ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
};
var poll = function() {
try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; }
init('poll');
};
if (doc.readyState == 'complete') {
fn.call(win, 'lazy');
} else {
if (doc.createEventObject && root.doScroll) {
try { top = !win.frameElement; } catch(e) { }
if (top) poll();
}
doc[add](pre + 'DOMContentLoaded', init, false);
doc[add](pre + 'readystatechange', init, false);
win[add](pre + 'load', init, false);
}
}
/**
* Remove classes from a DOM element
* @param {Element} element - The DOM element.
* @param {string} cssClasses - Space separated list of class names.
*/
function jqLiteRemoveClass(element, cssClasses) {
if (!cssClasses || !element.setAttribute) return;
var existingClasses = _getExistingClasses(element),
splitClasses = cssClasses.split(' '),
cssClass;
for (var i=0; i < splitClasses.length; i++) {
cssClass = splitClasses[i].trim();
while (existingClasses.indexOf(' ' + cssClass + ' ') >= 0) {
existingClasses = existingClasses.replace(' ' + cssClass + ' ', ' ');
}
}
element.setAttribute('class', existingClasses.trim());
}
// ------------------------------
// Utilities
// ------------------------------
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g,
MOZ_HACK_REGEXP = /^moz([A-Z])/,
ESCAPE_REGEXP = /([.*+?^=!:${}()|\[\]\/\\])/g,
BOOLEAN_ATTRS;
BOOLEAN_ATTRS = {
multiple: true,
selected: true,
checked: true,
disabled: true,
readonly: true,
required: true,
open: true
}
function _getExistingClasses(element) {
var classes = (element.getAttribute('class') || '').replace(/[\n\t]/g, '');
return ' ' + classes + ' ';
}
function _camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
function _escapeRegExp(string) {
return string.replace(ESCAPE_REGEXP, "\\$1");
}
function _getCurrCssProp(elem, name, computed) {
var ret;
// try computed style
ret = computed.getPropertyValue(name);
// try style attribute (if element is not attached to document)
if (ret === '' && !elem.ownerDocument) ret = elem.style[_camelCase(name)];
return ret;
}
/**
* Module API
*/
module.exports = {
/** Add classes */
addClass: jqLiteAddClass,
/** Get or set CSS properties */
css: jqLiteCss,
/** Check for class */
hasClass: jqLiteHasClass,
/** Remove event handlers */
off: jqLiteOff,
/** Return offset values */
offset: jqLiteOffset,
/** Add event handlers */
on: jqLiteOn,
/** Add an execute-once event handler */
one: jqLiteOne,
/** DOM ready event handler */
ready: jqLiteReady,
/** Remove classes */
removeClass: jqLiteRemoveClass,
/** Check JavaScript variable instance type */
type: jqLiteType
};
},{}],3:[function(require,module,exports){
/**
* MUI CSS/JS utilities module
* @module lib/util
*/
'use strict';
var config = require('../config.js'),
jqLite = require('./jqLite.js'),
win = window,
doc = window.document,
nodeInsertedCallbacks = [],
head,
_supportsPointerEvents;
head = doc.head || doc.getElementsByTagName('head')[0] || doc.documentElement;
/**
* Logging function
*/
function logFn() {
if (config.debug && typeof win.console !== "undefined") {
try {
win.console.log.apply(win.console, arguments);
} catch (a) {
var e = Array.prototype.slice.call(arguments);
win.console.log(e.join("\n"));
}
}
}
/**
* Load CSS text in new stylesheet
* @param {string} cssText - The css text.
*/
function loadStyleFn(cssText) {
if (doc.createStyleSheet) {
doc.createStyleSheet().cssText = cssText;
} else {
var e = doc.createElement('style');
e.type = 'text/css';
if (e.styleSheet) e.styleSheet.cssText = cssText;
else e.appendChild(doc.createTextNode(cssText));
// add to document
head.insertBefore(e, head.firstChild);
}
}
/**
* Raise an error
* @param {string} msg - The error message.
*/
function raiseErrorFn(msg) {
throw "MUI Error: " + msg;
}
/**
* Register callbacks on muiNodeInserted event
* @param {function} callbackFn - The callback function.
*/
function onNodeInsertedFn(callbackFn) {
nodeInsertedCallbacks.push(callbackFn);
// initalize listeners
if (nodeInsertedCallbacks._initialized === undefined) {
jqLite.on(doc, 'animationstart', animationHandlerFn);
jqLite.on(doc, 'mozAnimationStart', animationHandlerFn);
jqLite.on(doc, 'webkitAnimationStart', animationHandlerFn);
nodeInsertedCallbacks._initialized = true;
}
}
/**
* Execute muiNodeInserted callbacks
* @param {Event} ev - The DOM event.
*/
function animationHandlerFn(ev) {
// check animation name
if (ev.animationName !== 'mui-node-inserted') return;
var el = ev.target;
// iterate through callbacks
for (var i=nodeInsertedCallbacks.length - 1; i >= 0; i--) {
nodeInsertedCallbacks[i](el);
}
}
/**
* Convert Classname object, with class as key and true/false as value, to an
* class string.
* @param {Object} classes The classes
* @return {String} class string
*/
function classNamesFn(classes) {
var cs = '';
for (var i in classes) {
cs += (classes[i]) ? i + ' ' : '';
}
return cs.trim();
}
/**
* Check if client supports pointer events.
*/
function supportsPointerEventsFn() {
// check cache
if (_supportsPointerEvents !== undefined) return _supportsPointerEvents;
var element = document.createElement('x');
element.style.cssText = 'pointer-events:auto';
_supportsPointerEvents = (element.style.pointerEvents === 'auto');
return _supportsPointerEvents;
}
/**
* Create callback closure.
* @param {Object} instance - The object instance.
* @param {String} funcName - The name of the callback function.
*/
function callbackFn(instance, funcName) {
return function() {instance[funcName].apply(instance, arguments);};
}
/**
* Dispatch event.
* @param {Element} element - The DOM element.
* @param {String} eventType - The event type.
* @param {Boolean} bubbles=true - If true, event bubbles.
* @param {Boolean} cancelable=true = If true, event is cancelable
*/
function dispatchEventFn(element, eventType, bubbles, cancelable) {
var ev = document.createEvent('HTMLEvents'),
bubbles = (bubbles !== undefined) ? bubbles : true,
cancelable = (cancelable !== undefined) ? cancelable : true;
ev.initEvent(eventType, bubbles, cancelable);
element.dispatchEvent(ev);
}
/**
* Define the module API
*/
module.exports = {
/** Create callback closures */
callback: callbackFn,
/** Classnames object to string */
classNames: classNamesFn,
/** Dispatch event */
dispatchEvent: dispatchEventFn,
/** Log messages to the console when debug is turned on */
log: logFn,
/** Load CSS text as new stylesheet */
loadStyle: loadStyleFn,
/** Register muiNodeInserted handler */
onNodeInserted: onNodeInsertedFn,
/** Raise MUI error */
raiseError: raiseErrorFn,
/** Support Pointer Events check */
supportsPointerEvents: supportsPointerEventsFn
};
},{"../config.js":1,"./jqLite.js":2}],4:[function(require,module,exports){
/**
* MUI React buttons module
* @module react/buttons
*/
'use strict';
var util = require('../js/lib/util.js'),
Ripple = require('./ripple.jsx');
var buttonClass = 'mui-btn',
flatClass = buttonClass + '-flat',
raisedClass = buttonClass + '-raised',
largeClass = buttonClass + '-lg',
floatingClass = buttonClass + '-floating';
/**
* Button constructor
* @class
*/
var Button = React.createClass({displayName: "Button",
mixins: [Ripple],
getDefaultProps: function() {
return {
type: 'default', // one of default, primary, danger or accent
disabled: false
};
},
render: function() {
var cs = {};
cs[buttonClass] = true;
cs[buttonClass + '-' + this.props.type] = true;
cs[flatClass] = this.props.flat;
cs[raisedClass] = this.props.raised;
cs[largeClass] = this.props.large;
cs = util.classNames(cs);
return (
React.createElement("button", {
className: cs,
disabled: this.props.disabled,
onMouseDown: this.ripple,
onTouchStart: this.ripple,
onClick: this.props.onClick
},
this.props.children,
this.state.ripples && this.renderRipples()
)
);
}
});
/**
* Round button constructor
* @class
*/
var RoundButton = React.createClass({displayName: "RoundButton",
mixins: [Ripple],
getDefaultProps: function() {
return {
floating: true
};
},
render: function() {
var cs = {};
cs[buttonClass] = true;
cs[floatingClass] = true;
cs[floatingClass + '-mini'] = this.props.mini;
cs = util.classNames(cs);
return (
React.createElement("button", {
className: cs,
disabled: this.props.disabled,
onMouseDown: this.ripple,
onTouchStart: this.ripple,
onClick: this.props.onClick
},
this.props.children,
this.state.ripples && this.renderRipples()
)
);
}
})
/** Define module API */
module.exports = {
Button: Button,
RoundButton: RoundButton
};
},{"../js/lib/util.js":3,"./ripple.jsx":9}],5:[function(require,module,exports){
/**
* MUI React dropdowns module
* @module react/dropdowns
*/
/* jshint quotmark:false */
// jscs:disable validateQuoteMarks
'use strict';
var util = require('../js/lib/util'),
jqLite = require('../js/lib/jqLite'),
buttons = require('./buttons.jsx'),
Button = buttons.Button,
RoundButton = buttons.RoundButton;
var dropdownClass = 'mui-dropdown',
caretClass = 'mui-caret',
menuClass = 'mui-dropdown-menu',
openClass = 'mui-open',
rightClass = 'mui-dropdown-menu-right';
/**
* Dropdown constructor
* @class
*/
var Dropdown = React.createClass({displayName: "Dropdown",
menuStyle: { top: 0 },
getInitialState: function() {
return {
opened: false
};
},
componentWillMount: function() {
document.addEventListener('click', this._outsideClick);
},
componentWillUnmount: function() {
document.removeEventListener('click', this._outsideClick);
},
render: function() {
var button;
if (this.props.round) {
button = (
React.createElement(RoundButton, {
ref: "button",
onClick: this._click,
mini: this.props.mini,
disabled: this.props.disabled
},
this.props.label,
React.createElement("span", {className: caretClass })
)
);
} else {
button = (
React.createElement(Button, {
ref: "button",
onClick: this._click,
type: this.props.type,
flat: this.props.flat,
raised: this.props.raised,
large: this.props.large,
disabled: this.props.disabled
},
this.props.label,
React.createElement("span", {className: caretClass })
)
);
}
var cs = {};
cs[menuClass] = true;
cs[openClass] = this.state.opened;
cs[rightClass] = this.props.right;
cs = util.classNames(cs);
return (
React.createElement("div", {className: dropdownClass, style: {padding: '0px 2px 0px'} },
button,
this.state.opened && (
React.createElement("ul", {
className: cs,
style: this.menuStyle,
ref: "menu",
onClick: this._select
},
this.props.children
))
)
);
},
_click: function (ev) {
// only left clicks
if (ev.button !== 0) return;
// exit if toggle button is disabled
if (this.props.disabled) return;
setTimeout(function () {
if (!ev.defaultPrevented) this._toggle();
}.bind(this), 0);
},
_toggle: function () {
// exit if no menu element
if (!this.props.children) {
return util.raiseError('Dropdown menu element not found');
}
if (this.state.opened) this._close();
else this._open();
},
_open: function () {
// position menu element below toggle button
var wrapperRect = React.findDOMNode(this).getBoundingClientRect(),
toggleRect;
toggleRect = React.findDOMNode(this.refs.button).getBoundingClientRect();
this.menuStyle.top = toggleRect.top - wrapperRect.top + toggleRect.height;
this.setState({
opened: true
});
},
_close: function () {
this.setState({
opened: false
});
},
_select: function (ev) {
if (this.props.onClick) this.props.onClick(this, ev);
},
_outsideClick: function (ev) {
var isClickInside = React.findDOMNode(this).contains(event.target);
if (!isClickInside) {
this._close();
}
}
});
/**
* DropdownItem constructor
* @class
*/
var DropdownItem = React.createClass({displayName: "DropdownItem",
render: function () {
return (
React.createElement("li", null,
React.createElement("a", {href: this.props.link || '#', onClick: this._click},
this.props.children
)
)
);
},
_click: function (ev) {
if (this.props.onClick) this.props.onClick(this, ev);
}
});
/** Define module API */
module.exports = {
Dropdown: Dropdown,
DropdownItem: DropdownItem
};
},{"../js/lib/jqLite":2,"../js/lib/util":3,"./buttons.jsx":4}],6:[function(require,module,exports){
/**
* MUI React main module
* @module react/main
*/
(function(win) {
// return if library has been loaded already
if (win._muiReactLoaded) return;
else win._muiReactLoaded = true;
// load dependencies
var layout = require('./layout.jsx'),
forms = require('./forms.jsx'),
buttons = require('./buttons.jsx'),
dropdowns = require('./dropdowns.jsx'),
tabs = require('./tabs.jsx'),
doc = win.document;
// export React classes
win.MUIContainer = layout.Container;
win.MUIFluidContainer = layout.FluidContainer;
win.MUIPanel = layout.Panel;
win.MUIFormControl = forms.FormControl;
win.MUIFormGroup = forms.FormGroup;
win.MUIButton = buttons.Button;
win.MUIRoundButton = buttons.RoundButton;
win.MUIDropdown = dropdowns.Dropdown;
win.MUIDropdownItem = dropdowns.DropdownItem;
win.MUITabs = tabs.Tabs;
win.MUITabItem = tabs.TabItem;
})(window);
},{"./buttons.jsx":4,"./dropdowns.jsx":5,"./forms.jsx":7,"./layout.jsx":8,"./tabs.jsx":10}],7:[function(require,module,exports){
/**
* MUI React forms module
* @module react/forms
*/
'use strict';
var util = require('../js/lib/util.js');
var formControlClass = 'mui-form-control',
formGroupClass = 'mui-form-group',
floatingLabelBaseClass = 'mui-form-floating-label',
floatingLabelActiveClass = floatingLabelBaseClass + '-active';
/**
* FormControl constructor
* @class
*/
var FormControl = React.createClass({displayName: "FormControl",
render: function() {
return (
React.createElement("input", {
type: this.props.type || 'text',
className: formControlClass,
value: this.props.value,
autoFocus: this.props.autofocus,
onInput: this.props.onInput}
)
);
}
});
/**
* FormLabel constructor
* @class
*/
var FormLabel = React.createClass({displayName: "FormLabel",
getInitialState: function() {
return {
style: {}
};
},
componentDidMount: function() {
setTimeout(function() {
var s = '.15s ease-out',
style;
style = {
transition: s,
WebkitTransition: s,
MozTransition: s,
OTransition: s,
msTransform: s
};
this.setState({
style: style
});
}.bind(this), 150);
},
render: function() {
var labelText = this.props.text,
labelClass;
if (labelText) {
labelClass = {};
labelClass[floatingLabelBaseClass] = this.props.floating;
labelClass[floatingLabelActiveClass] = this.props.active;
labelClass = util.classNames(labelClass);
}
return (
React.createElement("label", {
className: labelClass,
style: this.state.style,
onClick: this.props.onClick
},
labelText
)
);
}
});
/**
* FormGroup constructor
* @class
*/
var FormGroup = React.createClass({displayName: "FormGroup",
getInitialState: function() {
return {
hasInput: false
};
},
componentDidMount: function() {
if (this.props.value) {
this.setState({
hasInput: true
});
}
},
render: function() {
var labelText = this.props.label;
return (
React.createElement("div", {className: formGroupClass },
React.createElement(FormControl, {
type: this.props.type,
value: this.props.value,
autoFocus: this.props.autofocus,
onInput: this._input}
),
labelText &&
React.createElement(FormLabel, {
text: labelText,
onClick: this._focus,
active: this.state.hasInput,
floating: this.props.isLabelFloating}
)
)
);
},
_focus: function (e) {
// pointer-events shim
if (util.supportsPointerEvents() === false) {
var labelEl = e.target;
labelEl.style.cursor = 'text';
if (!this.state.hasInput) {
var inputEl = React.findDOMNode(this.refs.input);
inputEl.focus();
}
}
},
_input: function (e) {
if (e.target.value) {
this.setState({
hasInput: true
});
} else {
this.setState({
hasInput: false
});
}
if (this.props.onClick) {
this.props.onClick(e);
}
}
});
/** Define module API */
module.exports = {
FormControl: FormControl,
FormGroup: FormGroup
};
},{"../js/lib/util.js":3}],8:[function(require,module,exports){
/**
* MUI React layout module
* @module react/layout
*/
'use strict';
var containerClass = 'mui-container',
fluidClass = 'mui-container-fluid',
panelClass = 'mui-panel';
/**
* Container constructor
* @class
*/
var Container = React.createClass({displayName: "Container",
render: function() {
return (
React.createElement("div", {className: containerClass },
this.props.children
)
);
}
});
/**
* FluidContainer constructor
* @class
*/
var FluidContainer = React.createClass({displayName: "FluidContainer",
render: function() {
return (
React.createElement("div", {className: fluidClass },
this.props.children
)
);
}
});
/**
* Panel constructor
* @class
*/
var Panel = React.createClass({displayName: "Panel",
render: function() {
return (
React.createElement("div", {className: panelClass },
this.props.children
)
);
}
});
/** Define module API */
module.exports = {
Container: Container,
FluidContainer: FluidContainer,
Panel: Panel
};
},{}],9:[function(require,module,exports){
/**
* MUI React ripple module
* @module react/ripple
*/
'use strict';
var jqLite = require('../js/lib/jqLite.js');
var rippleClass = 'mui-ripple-effect';
/**
* Ripple singleton
*/
var Ripple = {
getInitialState: function() {
return {
touchFlag: false,
ripples: []
};
},
getDefaultProps: function() {
return {
rippleClass: rippleClass
};
},
ripple: function (ev) {
// only left clicks
if (ev.button !== 0) return;
var buttonEl = React.findDOMNode(this);
// exit if button is disabled
if (this.props.disabled === true) return;
// de-dupe touchstart and mousedown with 100msec flag
if (this.state.touchFlag === true) {
return;
} else {
this.setState({ touchFlag: true });
setTimeout(function() {
this.setState({ touchFlag: false });
}.bind(this), 100);
}
var offset = jqLite.offset(buttonEl),
xPos = ev.pageX - offset.left,
yPos = ev.pageY - offset.top,
diameter,
radius;
// get height
if (this.props.floating) {
diameter = offset.height / 2;
} else {
diameter = offset.height;
}
radius = diameter / 2;
var style = {
height: diameter,
width: diameter,
top: yPos - radius,
left: xPos - radius
};
var ripples = this.state.ripples || [];
window.setTimeout(function() {
this._removeRipple();
}.bind(this), 2000);
ripples.push({ style: style });
this.setState({
ripples: ripples
});
},
_removeRipple: function () {
this.state.ripples.shift();
this.setState({
ripples: this.state.ripples
});
},
renderRipples: function () {
if (this.state.ripples.length === 0) return;
var i = 0;
return this.state.ripples.map(function (ripple) {
i++;
return (
React.createElement("div", {
className: this.props.rippleClass,
key: i,
style: ripple.style}
)
);
}.bind(this));
}
};
/** Define module API */
module.exports = Ripple;
},{"../js/lib/jqLite.js":2}],10:[function(require,module,exports){
/**
* MUI React tabs module
* @module react/tabs
*/
/* jshint quotmark:false */
// jscs:disable validateQuoteMarks
'use strict';
var util = require('../js/lib/util.js');
var tabClass = 'mui-tabs',
contentClass = 'mui-tab-content',
paneClass = 'mui-tab-pane',
justifiedClass = 'mui-tabs-justified',
activeClass = 'mui-active';
/**
* Tabs constructor
* @class
*/
var Tabs = React.createClass({displayName: "Tabs",
getDefaultProps: function() {
return {
justified: false
};
},
getInitialState: function() {
return {
activeTab: ""
};
},
componentDidMount: function() {
if (this.props.activeTab) {
this.setState({
activeTab: this.props.activeTab
});
} else {
this.setState({
activeTab: this.props.children && this.props.children[0].props.id
});
}
},
render: function() {
var items = this.props.children.map(function (item) {
return {
name: item.props.id,
label: item.props.label,
pane: item.props.children
};
});
return (
React.createElement("div", {className: "tabs"},
React.createElement(TabHeaders, {
items: items,
justified: this.props.justified,
active: this.state.activeTab,
onClick: this._changeTab}
),
React.createElement(TabContainers, {items: items, active: this.state.activeTab})
)
);
},
_changeTab: function (toWhich, e) {
// only left clicks
if (e.button !== 0) return;
if (e.target.getAttribute('disabled') !== null) return;
setTimeout(function () {
if (!e.defaultPrevented) {
this.setState({
activeTab: toWhich
});
}
}.bind(this), 0);
}
});
/**
* TabHeaders constructor
* @class
*/
var TabHeaders = React.createClass({displayName: "TabHeaders",
getDefaultProps: function() {
return {
items: []
};
},
render: function() {
var classes = {};
classes[tabClass] = true;
classes[justifiedClass] = this.props.justified;
classes = util.classNames(classes);
var items = this.props.items.map(function (item) {
return (
React.createElement(TabHeaderItem, {key: item.name,
name: item.name,
label: item.label,
active: item.name === this.props.active,
onClick: this.props.onClick})
);
}.bind(this));
return (
React.createElement("ul", {className: classes },
items
)
);
}
});
/**
* TabHeaderItem constructor
* @class
*/
var TabHeaderItem = React.createClass({displayName: "TabHeaderItem",
render: function () {
var classes = {};
classes[activeClass] = this.props.active;
classes = util.classNames(classes);
return (
React.createElement("li", {className: classes },
React.createElement("a", {onClick: this._click},
this.props.label
)
)
);
},
_click: function (e) {
if (this.props.onClick) {
this.props.onClick(this.props.name, e);
}
}
});
/**
* TabContainers constructor
* @class
*/
var TabContainers = React.createClass({displayName: "TabContainers",
getDefaultProps: function() {
return {
items: []
};
},
render: function() {
var items = this.props.items.map(function (item) {
return (
React.createElement(TabPane, {key: item.name,
active: item.name === this.props.active},
item.pane
)
);
}.bind(this));
return (
React.createElement("div", {className: contentClass },
items
)
);
}
});
/**
* TabPane constructor
* @class
*/
var TabPane = React.createClass({displayName: "TabPane",
render: function () {
var classes = {};
classes[paneClass] = true;
classes[activeClass] = this.props.active;
classes = util.classNames(classes);
return (
React.createElement("div", {className: classes },
this.props.children
)
);
}
});
/**
* TabItem constructor
* @class
*/
var TabItem = React.createClass({displayName: "TabItem",
render: function() {
return null;
}
});
/** Define module API */
module.exports = {
Tabs: Tabs,
TabItem: TabItem
};
},{"../js/lib/util.js":3}]},{},[6]) |
src/issues/UserDisplay.js | evandavis/react-github-issues | import React from 'react';
const UserDisplay = ({user, className}) => {
return (
<div className={`user-display ${className}`}>
<img src={`${user.avatar_url}&s=32`} alt={user.login} className='user-display-avatar' />
<span className='user-display-name'>{user.login}</span>
</div>
);
}
export default UserDisplay;
|
src/components/sketched/SketchPresetColors.js | conorhastings/react-color | 'use strict' /* @flow */
import React from 'react'
import ReactCSS from 'reactcss'
import shallowCompare from 'react-addons-shallow-compare'
export class SketchPresetColors extends ReactCSS.Component {
shouldComponentUpdate = shallowCompare.bind(this, this, arguments[0], arguments[1])
classes(): any {
return {
'default': {
colors: {
marginRight: '-10px',
marginLeft: '-10px',
paddingLeft: '10px',
paddingTop: '10px',
borderTop: '1px solid #eee',
},
li: {
borderRadius: '3px',
overflow: 'hidden',
position: 'relative',
display: 'inline-block',
margin: '0 10px 10px 0',
verticalAlign: 'top',
cursor: 'pointer',
},
square: {
borderRadius: '3px',
width: '16px',
height: '16px',
boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15)',
},
},
'no-presets': {
colors: {
display: 'none',
},
},
}
}
styles(): any {
return this.css({
'no-presets': !this.props.colors || !this.props.colors.length,
})
}
handleClick = (hex: any) => {
this.props.onClick({
hex: hex,
source: 'hex',
})
}
render(): any {
var colors = []
if (this.props.colors) {
for (var i = 0; i < this.props.colors.length; i++) {
var color = this.props.colors[i]
colors.push(<div key={ color } is="li" ref={ color } onClick={ this.handleClick.bind(null, color) }><div style={{ background: color }} > <div is="square" /> </div></div>)
}
}
return (
<div is="colors">
{ colors }
</div>
)
}
}
export default SketchPresetColors
|
client/extensions/woocommerce/woocommerce-services/components/number-field/number-input.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import FormTextInput from 'components/forms/form-text-input';
export default class NumberInput extends Component {
static propTypes = {
onChange: PropTypes.func,
};
static defaultProps = {
onChange: () => {},
};
state = {
focused: false,
text: this.props.value,
};
UNSAFE_componentWillReceiveProps( nextProps ) {
if ( ! this.state.focused && nextProps.value !== this.props.value ) {
this.setState( { text: nextProps.value } );
}
}
handleChange = event => {
this.setState( { text: event.target.value } );
this.props.onChange( event );
};
handleBlur = event => {
this.setState( {
focused: false,
text: this.props.value,
} );
this.props.onChange( event );
};
handleFocus = () => {
this.setState( { focused: true } );
};
render() {
return (
<FormTextInput
{ ...this.props }
value={ this.state.text }
onChange={ this.handleChange }
onBlur={ this.handleBlur }
onFocus={ this.handleFocus }
/>
);
}
}
|
yycomponent/breadcrumb/Item.js | 77ircloud/yycomponent | import React from 'react';
import { Breadcrumb } from 'antd';
class Item extends React.Component{
constructor(props){
super(props);
}
render(){
return (<Breadcrumb.Item {...this.props}/>);
}
}
export default Item
|
__tests__/components/TBD-test.js | nickjvm/grommet | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React from 'react';
import renderer from 'react-test-renderer';
import TBD from '../../src/js/components/TBD';
describe('TBD', () => {
it('has correct default options', () => {
const component = renderer.create(
<TBD />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
|
client/app/bundles/PartyMode/parties/containers/partyItems/PartyItems.js | lrosskamp/makealist-public | import React from 'react'
import { connect } from 'react-redux'
import * as globalSelectors from '../../../selectors'
import * as s from '../../selectors'
import ui from '../../../ui'
import PartyItems from '../../components/partyItems/PartyItems'
const mapStateToProps = (state) =>({
categoriesWithItemsWithMemberIds: globalSelectors
.getCategoriesWithItemsWithMemberIds(state),
withCount: ui.listEntriesForm.selectors.getWithCountBoolean(
globalSelectors.getListEntriesForm(state)
),
isPending: s.getIsPending(state.parties)
})
const mapDispatchToProps = (dispatch) =>({
toggleWithCount: () => dispatch(ui.listEntriesForm.actions.toggleWithCount())
})
export default connect(mapStateToProps, mapDispatchToProps)(PartyItems)
|
src/components/MenuButton.js | germtb/react-redux-burguer-menu | import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import {store} from '../store';
import {HoverButton} from './HoverButton';
import Radium from 'radium';
const divStyle = {
fontSize: '25px',
marginLeft: '20px',
marginRight: '20px',
marginBottom: '20px',
};
const imageStyle = {
};
const textStyle = {
};
@Radium
export class MenuButton extends React.Component {
render() {
return (
<div style={divStyle}>
<img style={imageStyle} src={this.props.img}/>
<div style={textStyle}> {this.props.text} </div>
</div>
);
}
}
|
lib-module-dev/layout/Html.js | turacojs/fody | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _jsxFileName = 'layout/Html.jsx',
_this = this;
import React from 'react';
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
/* eslint-disable jsx-a11y/html-has-lang */
import { ReactNodeType as _ReactNodeType, HelmetDataType as _HelmetDataType } from '../types';
import t from 'flow-runtime';
var ReactNodeType = t.tdz(function () {
return _ReactNodeType;
});
var HelmetDataType = t.tdz(function () {
return _HelmetDataType;
});
var PropsType = t.type('PropsType', t.object(t.property('helmet', t.ref(HelmetDataType)), t.property('children', t.ref(ReactNodeType))));
export default (function html(_arg) {
var _returnType = t.return(t.ref(ReactNodeType));
var _PropsType$assert = PropsType.assert(_arg),
helmet = _PropsType$assert.helmet,
children = _PropsType$assert.children,
otherProps = _objectWithoutProperties(_PropsType$assert, ['helmet', 'children']);
return _returnType.assert(React.createElement(
'html',
_extends({}, helmet.htmlAttributes.toComponent(), otherProps, {
__self: _this,
__source: {
fileName: _jsxFileName,
lineNumber: 14
}
}),
children
));
});
//# sourceMappingURL=Html.js.map |
src/app/jquery.min.js | viking/hourglass | /*!
* jQuery JavaScript Library v1.6.2
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu Jun 30 14:16:56 2011 -0400
*/
(function(a,b){function cv(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cs(a){if(!cg[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ch||(ch=c.createElement("iframe"),ch.frameBorder=ch.width=ch.height=0),b.appendChild(ch);if(!ci||!ch.createElement)ci=(ch.contentWindow||ch.contentDocument).document,ci.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),ci.close();d=ci.createElement(a),ci.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ch)}cg[a]=e}return cg[a]}function cr(a,b){var c={};f.each(cm.concat.apply([],cm.slice(0,b)),function(){c[this]=a});return c}function cq(){cn=b}function cp(){setTimeout(cq,0);return cn=f.now()}function cf(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ce(){try{return new a.XMLHttpRequest}catch(b){}}function b$(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bZ(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bY(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bC.test(a)?d(a,e):bY(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)bY(a+"["+e+"]",b[e],c,d);else d(a,b)}function bX(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bR,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bX(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bX(a,c,d,e,"*",g));return l}function bW(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bN),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bA(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bv:bw;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bx(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function bm(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(be,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bl(a){f.nodeName(a,"input")?bk(a):"getElementsByTagName"in a&&f.grep(a.getElementsByTagName("input"),bk)}function bk(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bj(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function bi(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bh(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c=f.expando,d=f.data(a),e=f.data(b,d);if(d=d[c]){var g=d.events;e=e[c]=f.extend({},d);if(g){delete e.handle,e.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)f.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function bg(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function W(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(R.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(a,b){return(a&&a!=="*"?a+".":"")+b.replace(z,"`").replace(A,"&")}function M(a){var b,c,d,e,g,h,i,j,k,l,m,n,o,p=[],q=[],r=f._data(this,"events");if(!(a.liveFired===this||!r||!r.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var s=r.live.slice(0);for(i=0;i<s.length;i++)g=s[i],g.origType.replace(x,"")===a.type?q.push(g.selector):s.splice(i--,1);e=f(a.target).closest(q,a.currentTarget);for(j=0,k=e.length;j<k;j++){m=e[j];for(i=0;i<s.length;i++){g=s[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,d=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,d=f(a.relatedTarget).closest(g.selector)[0],d&&f.contains(h,d)&&(d=h);(!d||d!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){e=p[j];if(c&&e.level>c)break;a.currentTarget=e.elem,a.data=e.handleObj.data,a.handleObj=e.handleObj,o=e.handleObj.origHandler.apply(e.elem,arguments);if(o===!1||a.isPropagationStopped()){c=e.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function K(a,c,d){var e=f.extend({},d[0]);e.type=a,e.originalEvent={},e.liveFired=b,f.event.handle.call(c,e),e.isDefaultPrevented()&&d[0].preventDefault()}function E(){return!0}function D(){return!1}function m(a,c,d){var e=c+"defer",g=c+"queue",h=c+"mark",i=f.data(a,e,b,!0);i&&(d==="queue"||!f.data(a,g,b,!0))&&(d==="mark"||!f.data(a,h,b,!0))&&setTimeout(function(){!f.data(a,g,b,!0)&&!f.data(a,h,b,!0)&&(f.removeData(a,e,!0),i.resolve())},0)}function l(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function k(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(j,"$1-$2").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNaN(d)?i.test(d)?f.parseJSON(d):d:parseFloat(d)}catch(g){}f.data(a,c,d)}else d=b}return d}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z])/ig,x=function(a,b){return b.toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.6.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.resolveWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!A){A=e._Deferred();if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNaN:function(a){return a==null||!m.test(a)||isNaN(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a);return c===b||D.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(b,c,d){a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),d=c.documentElement,(!d||!d.nodeName||d.nodeName==="parsererror")&&e.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b){if(H)return H.call(b,a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g="done fail isResolved isRejected promise then always pipe".split(" "),h=[].slice;f.extend({_Deferred:function(){var a=[],b,c,d,e={done:function(){if(!d){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=f.type(i),j==="array"?e.done.apply(e,i):j==="function"&&a.push(i);k&&e.resolveWith(k[0],k[1])}return this},resolveWith:function(e,f){if(!d&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(e,f)}finally{b=[e,f],c=0}}return this},resolve:function(){e.resolveWith(this,arguments);return this},isResolved:function(){return!!c||!!b},cancel:function(){d=1,a=[];return this}};return e},Deferred:function(a){var b=f._Deferred(),c=f._Deferred(),d;f.extend(b,{then:function(a,c){b.done(a).fail(c);return this},always:function(){return b.done.apply(b,arguments).fail.apply(this,arguments)},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,pipe:function(a,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[c,"reject"]},function(a,c){var e=c[0],g=c[1],h;f.isFunction(e)?b[a](function(){h=e.apply(this,arguments),h&&f.isFunction(h.promise)?h.promise().then(d.resolve,d.reject):d[g](h)}):b[a](d[g])})}).promise()},promise:function(a){if(a==null){if(d)return d;d=a={}}var c=g.length;while(c--)a[g[c]]=b[g[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?h.call(arguments,0):c,--e||g.resolveWith(g,h.call(b,0))}}var b=arguments,c=0,d=b.length,e=d,g=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred();if(d>1){for(;c<d;c++)b[c]&&f.isFunction(b[c].promise)?b[c].promise().then(i(c),g.reject):--e;e||g.resolveWith(g,b)}else g!==a&&g.resolveWith(g,d?[a]:[]);return g.promise()}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55$/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.firstChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0},m&&f.extend(p,{position:"absolute",left:-1e3,top:-1e3});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0),o.innerHTML="",n.removeChild(o);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var i=/^(?:\{.*\}|\[.*\])$/,j=/([a-z])([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!l(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g=f.expando,h=typeof c=="string",i,j=a.nodeType,k=j?f.cache:a,l=j?a[f.expando]:a[f.expando]&&f.expando;if((!l||e&&l&&!k[l][g])&&h&&d===b)return;l||(j?a[f.expando]=l=++f.uuid:l=f.expando),k[l]||(k[l]={},j||(k[l].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?k[l][g]=f.extend(k[l][g],c):k[l]=f.extend(k[l],c);i=k[l],e&&(i[g]||(i[g]={}),i=i[g]),d!==b&&(i[f.camelCase(c)]=d);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[f.camelCase(c)]||i[c]:i}},removeData:function(b,c,d){if(!!f.acceptData(b)){var e=f.expando,g=b.nodeType,h=g?f.cache:b,i=g?b[f.expando]:f.expando;if(!h[i])return;if(c){var j=d?h[i][e]:h[i];if(j){delete j[c];if(!l(j))return}}if(d){delete h[i][e];if(!l(h[i]))return}var k=h[i][e];f.support.deleteExpando||h!=a?delete h[i]:h[i]=null,k?(h[i]={},g||(h[i].toJSON=f.noop),h[i][e]=k):g&&(f.support.deleteExpando?delete b[f.expando]:b.removeAttribute?b.removeAttribute(f.expando):b[f.expando]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d=null;if(typeof a=="undefined"){if(this.length){d=f.data(this[0]);if(this[0].nodeType===1){var e=this[0].attributes,g;for(var h=0,i=e.length;h<i;h++)g=e[h].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),k(this[0],g,d[g]))}}return d}if(typeof a=="object")return this.each(function(){f.data(this,a)});var j=a.split(".");j[1]=j[1]?"."+j[1]:"";if(c===b){d=this.triggerHandler("getData"+j[1]+"!",[j[0]]),d===b&&this.length&&(d=f.data(this[0],a),d=k(this[0],a,d));return d===b&&j[1]?this.data(j[0]):d}return this.each(function(){var b=f(this),d=[j[0],c];b.triggerHandler("setData"+j[1]+"!",d),f.data(this,a,c),b.triggerHandler("changeData"+j[1]+"!",d)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,c){a&&(c=(c||"fx")+"mark",f.data(a,c,(f.data(a,c,b,!0)||0)+1,!0))},_unmark:function(a,c,d){a!==!0&&(d=c,c=a,a=!1);if(c){d=d||"fx";var e=d+"mark",g=a?0:(f.data(c,e,b,!0)||1)-1;g?f.data(c,e,g,!0):(f.removeData(c,e,!0),m(c,d,"mark"))}},queue:function(a,c,d){if(a){c=(c||"fx")+"queue";var e=f.data(a,c,b,!0);d&&(!e||f.isArray(d)?e=f.data(a,c,f.makeArray(d),!0):e.push(d));return e||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e;d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),d.call(a,function(){f.dequeue(a,b)})),c.length||(f.removeData(a,b+"queue",!0),m(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){f.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f._Deferred(),!0))h++,l.done(m);m();return d.promise()}});var n=/[\n\t\r]/g,o=/\s+/,p=/\r/g,q=/^(?:button|input)$/i,r=/^(?:button|input|object|select|textarea)$/i,s=/^a(?:rea)?$/i,t=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,u=/\:|^on/,v,w;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(o);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(o);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(n," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(o);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(n," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e=this[0];if(!arguments.length){if(e){c=f.valHooks[e.nodeName.toLowerCase()]||f.valHooks[e.type];if(c&&"get"in c&&(d=c.get(e,"value"))!==b)return d;d=e.value;return typeof d=="string"?d.replace(p,""):d==null?"":d}return b}var g=f.isFunction(a);return this.each(function(d){var e=f(this),h;if(this.nodeType===1){g?h=a.call(this,d,e.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c=a.selectedIndex,d=[],e=a.options,g=a.type==="select-one";if(c<0)return null;for(var h=g?c:0,i=g?c+1:e.length;h<i;h++){var j=e[h];if(j.selected&&(f.support.optDisabled?!j.disabled:j.getAttribute("disabled")===null)&&(!j.parentNode.disabled||!f.nodeName(j.parentNode,"optgroup"))){b=f(j).val();if(g)return b;d.push(b)}}if(g&&!d.length&&e.length)return f(e[c]).val();return d},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attrFix:{tabindex:"tabIndex"},attr:function(a,c,d,e){var g=a.nodeType;if(!a||g===3||g===8||g===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);var h,i,j=g!==1||!f.isXMLDoc(a);j&&(c=f.attrFix[c]||c,i=f.attrHooks[c],i||(t.test(c)?i=w:v&&c!=="className"&&(f.nodeName(a,"form")||u.test(c))&&(i=v)));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(i&&"set"in i&&j&&(h=i.set(a,d,c))!==b)return h;a.setAttribute(c,""+d);return d}if(i&&"get"in i&&j&&(h=i.get(a,c))!==null)return h;h=a.getAttribute(c);return h===null?b:h},removeAttr:function(a,b){var c;a.nodeType===1&&(b=f.attrFix[b]||b,f.support.getSetAttribute?a.removeAttribute(b):(f.attr(a,b,""),a.removeAttributeNode(a.getAttributeNode(b))),t.test(b)&&(c=f.propFix[b]||b)in a&&(a[c]=!1))},attrHooks:{type:{set:function(a,b){if(q.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},tabIndex:{get:function(a){var c=a.getAttributeNode("tabIndex");return c&&c.specified?parseInt(c.value,10):r.test(a.nodeName)||s.test(a.nodeName)&&a.href?0:b}},value:{get:function(a,b){if(v&&f.nodeName(a,"button"))return v.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(v&&f.nodeName(a,"button"))return v.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e=a.nodeType;if(!a||e===3||e===8||e===2)return b;var g,h,i=e!==1||!f.isXMLDoc(a);i&&(c=f.propFix[c]||c,h=f.propHooks[c]);return d!==b?h&&"set"in h&&(g=h.set(a,d,c))!==b?g:a[c]=d:h&&"get"in h&&(g=h.get(a,c))!==b?g:a[c]},propHooks:{}}),w={get:function(a,c){return f.prop(a,c)?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},f.support.getSetAttribute||(f.attrFix=f.propFix,v=f.attrHooks.name=f.attrHooks.title=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&d.nodeValue!==""?d.nodeValue:b},set:function(a,b,c){var d=a.getAttributeNode(c);if(d){d.nodeValue=b;return b}}},f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})})),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}})),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var x=/\.(.*)$/,y=/^(?:textarea|input|select)$/i,z=/\./g,A=/ /g,B=/[^\w\s.|`]/g,C=function(a){return a.replace(B,"\\$&")};f.event={add:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){if(d===!1)d=D;else if(!d)return;var g,h;d.handler&&(g=d,d=g.handler),d.guid||(d.guid=f.guid++);var i=f._data(a);if(!i)return;var j=i.events,k=i.handle;j||(i.events=j={}),k||(i.handle=k=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.handle.apply(k.elem,arguments):b}),k.elem=a,c=c.split(" ");var l,m=0,n;while(l=c[m++]){h=g?f.extend({},g):{handler:d,data:e},l.indexOf(".")>-1?(n=l.split("."),l=n.shift(),h.namespace=n.slice(0).sort().join(".")):(n=[],h.namespace=""),h.type=l,h.guid||(h.guid=d.guid);var o=j[l],p=f.event.special[l]||{};if(!o){o=j[l]=[];if(!p.setup||p.setup.call(a,e,n,k)===!1)a.addEventListener?a.addEventListener(l,k,!1):a.attachEvent&&a.attachEvent("on"+l,k)}p.add&&(p.add.call(a,h),h.handler.guid||(h.handler.guid=d.guid)),o.push(h),f.event.global[l]=!0}a=null}},global:{},remove:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){d===!1&&(d=D);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=f.hasData(a)&&f._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(d=c.handler,c=c.type);if(!c||typeof c=="string"&&c.charAt(0)==="."){c=c||"";for(h in t)f.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+f.map(m.slice(0).sort(),C).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!d){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))f.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=f.event.special[h]||{};for(j=e||0;j<p.length;j++){q=p[j];if(d.guid===q.guid){if(l||n.test(q.namespace))e==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(e!=null)break}}if(p.length===0||e!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&f.removeEvent(a,h,s.handle),g=null,delete t[h]}if(f.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,f.isEmptyObject(s)&&f.removeData(a,b,!0)}}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){var h=c.type||c,i=[],j;h.indexOf("!")>=0&&(h=h.slice(0,-1),j=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.
shift(),i.sort());if(!!e&&!f.event.customEvent[h]||!!f.event.global[h]){c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.exclusive=j,c.namespace=i.join("."),c.namespace_re=new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)");if(g||!e)c.preventDefault(),c.stopPropagation();if(!e){f.each(f.cache,function(){var a=f.expando,b=this[a];b&&b.events&&b.events[h]&&f.event.trigger(c,d,b.handle.elem)});return}if(e.nodeType===3||e.nodeType===8)return;c.result=b,c.target=e,d=d!=null?f.makeArray(d):[],d.unshift(c);var k=e,l=h.indexOf(":")<0?"on"+h:"";do{var m=f._data(k,"handle");c.currentTarget=k,m&&m.apply(k,d),l&&f.acceptData(k)&&k[l]&&k[l].apply(k,d)===!1&&(c.result=!1,c.preventDefault()),k=k.parentNode||k.ownerDocument||k===c.target.ownerDocument&&a}while(k&&!c.isPropagationStopped());if(!c.isDefaultPrevented()){var n,o=f.event.special[h]||{};if((!o._default||o._default.call(e.ownerDocument,c)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)){try{l&&e[h]&&(n=e[l],n&&(e[l]=null),f.event.triggered=h,e[h]())}catch(p){}n&&(e[l]=n),f.event.triggered=b}}return c.result}},handle:function(c){c=f.event.fix(c||a.event);var d=((f._data(this,"events")||{})[c.type]||[]).slice(0),e=!c.exclusive&&!c.namespace,g=Array.prototype.slice.call(arguments,0);g[0]=c,c.currentTarget=this;for(var h=0,i=d.length;h<i;h++){var j=d[h];if(e||c.namespace_re.test(j.namespace)){c.handler=j.handler,c.data=j.data,c.handleObj=j;var k=j.handler.apply(this,g);k!==b&&(c.result=k,k===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[f.expando])return a;var d=a;a=f.Event(d);for(var e=this.props.length,g;e;)g=this.props[--e],a[g]=d[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=a.target.ownerDocument||c,i=h.documentElement,j=h.body;a.pageX=a.clientX+(i&&i.scrollLeft||j&&j.scrollLeft||0)-(i&&i.clientLeft||j&&j.clientLeft||0),a.pageY=a.clientY+(i&&i.scrollTop||j&&j.scrollTop||0)-(i&&i.clientTop||j&&j.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:f.proxy,special:{ready:{setup:f.bindReady,teardown:f.noop},live:{add:function(a){f.event.add(this,N(a.origType,a.selector),f.extend({},a,{handler:M,guid:a.handler.guid}))},remove:function(a){f.event.remove(this,N(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!this.preventDefault)return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?E:D):this.type=a,b&&f.extend(this,b),this.timeStamp=f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=E;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=E;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=E,this.stopPropagation()},isDefaultPrevented:D,isPropagationStopped:D,isImmediatePropagationStopped:D};var F=function(a){var b=a.relatedTarget,c=!1,d=a.type;a.type=a.data,b!==this&&(b&&(c=f.contains(this,b)),c||(f.event.handle.apply(this,arguments),a.type=d))},G=function(a){a.type=a.data,f.event.handle.apply(this,arguments)};f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={setup:function(c){f.event.add(this,b,c&&c.selector?G:F,a)},teardown:function(a){f.event.remove(this,b,a&&a.selector?G:F)}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(a,b){if(!f.nodeName(this,"form"))f.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&f(b).closest("form").length&&K("submit",this,arguments)}),f.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&f(b).closest("form").length&&a.keyCode===13&&K("submit",this,arguments)});else return!1},teardown:function(a){f.event.remove(this,".specialSubmit")}});if(!f.support.changeBubbles){var H,I=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?f.map(a.options,function(a){return a.selected}).join("-"):"":f.nodeName(a,"select")&&(c=a.selectedIndex);return c},J=function(c){var d=c.target,e,g;if(!!y.test(d.nodeName)&&!d.readOnly){e=f._data(d,"_change_data"),g=I(d),(c.type!=="focusout"||d.type!=="radio")&&f._data(d,"_change_data",g);if(e===b||g===e)return;if(e!=null||g)c.type="change",c.liveFired=b,f.event.trigger(c,arguments[1],d)}};f.event.special.change={filters:{focusout:J,beforedeactivate:J,click:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="radio"||c==="checkbox"||f.nodeName(b,"select"))&&J.call(this,a)},keydown:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(a.keyCode===13&&!f.nodeName(b,"textarea")||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&J.call(this,a)},beforeactivate:function(a){var b=a.target;f._data(b,"_change_data",I(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in H)f.event.add(this,c+".specialChange",H[c]);return y.test(this.nodeName)},teardown:function(a){f.event.remove(this,".specialChange");return y.test(this.nodeName)}},H=f.event.special.change.filters,H.focus=H.beforeactivate}f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){function e(a){var c=f.event.fix(a);c.type=b,c.originalEvent={},f.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var d=0;f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.each(["bind","one"],function(a,c){f.fn[c]=function(a,d,e){var g;if(typeof a=="object"){for(var h in a)this[c](h,d,a[h],e);return this}if(arguments.length===2||d===!1)e=d,d=b;c==="one"?(g=function(a){f(this).unbind(a,g);return e.apply(this,arguments)},g.guid=e.guid||f.guid++):g=e;if(a==="unload"&&c!=="one")this.one(a,d,e);else for(var i=0,j=this.length;i<j;i++)f.event.add(this[i],a,g,d);return this}}),f.fn.extend({unbind:function(a,b){if(typeof a=="object"&&!a.preventDefault)for(var c in a)this.unbind(c,a[c]);else for(var d=0,e=this.length;d<e;d++)f.event.remove(this[d],a,b);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f.data(this,"lastToggle"+a.guid)||0)%d;f.data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var L={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};f.each(["live","die"],function(a,c){f.fn[c]=function(a,d,e,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:f(this.context);if(typeof a=="object"&&!a.preventDefault){for(var o in a)n[c](o,d,a[o],m);return this}if(c==="die"&&!a&&g&&g.charAt(0)==="."){n.unbind(g);return this}if(d===!1||f.isFunction(d))e=d||D,d=b;a=(a||"").split(" ");while((h=a[i++])!=null){j=x.exec(h),k="",j&&(k=j[0],h=h.replace(x,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,L[h]?(a.push(L[h]+k),h=h+k):h=(L[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)f.event.add(n[p],"live."+N(h,m),{data:d,selector:m,handler:e,origType:h,origHandler:e,preType:l});else n.unbind("live."+N(h,m),e)}return this}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d=0,e=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,f,g){f=f||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return f;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(e.call(n)==="[object Array]")if(!u)f.push.apply(f,n);else if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&f.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&f.push(j[t]);else p(n,f);o&&(k(o,h,f,g),k.uniqueSort(f));return f};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(!f)g=o=!0;else if(f===!0)continue}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("parentNode",b,f,a,e,c)},"~":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("previousSibling",b,f,a,e,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=d++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(e.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var f=a.length;c<f;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){if(a===b){g=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};f.find=k,f.expr=k.selectors,f.expr[":"]=f.expr.filters,f.unique=k.uniqueSort,f.text=k.getText,f.isXMLDoc=k.isXML,f.contains=k.contains}();var O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(d=0,e=a.length;d<e;d++)i=a[d],j[i]||(j[i]=T.test(i)?f(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:f(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=T.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(l?l.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a=="string")return f.inArray(this[0],a?f(a):this.parent().children());return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var X=/ jQuery\d+="(?:\d+|null)"/g,Y=/^\s+/,Z=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,$=/<([\w:]+)/,_=/<tbody/i,ba=/<|&#?\w+;/,bb=/<(?:script|object|embed|option|style)/i,bc=/checked\s*(?:[^=]|=\s*.checked.)/i,bd=/\/(java|ecma)script/i,be=/^\s*<!(?:\[CDATA\[|\-\-)/,bf={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};bf.optgroup=bf.option,bf.tbody=bf.tfoot=bf.colgroup=bf.caption=bf.thead,bf.th=bf.td,f.support.htmlSerialize||(bf._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(X,""):null;if(typeof a=="string"&&!bb.test(a)&&(f.support.leadingWhitespace||!Y.test(a))&&!bf[($.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Z,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bc.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bg(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bm)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i;b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof a[0]=="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!bb.test(a[0])&&(f.support.checkClone||!bc.test(a[0]))&&(g=!0,h=f.fragments[a[0]],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[a[0]]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j
)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bi(a,d),e=bj(a),g=bj(d);for(h=0;e[h];++h)bi(e[h],g[h])}if(b){bh(a,d);if(c){e=bj(a),g=bj(d);for(h=0;e[h];++h)bh(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!ba.test(k))k=b.createTextNode(k);else{k=k.replace(Z,"<$1></$2>");var l=($.exec(k)||["",""])[1].toLowerCase(),m=bf[l]||bf._default,n=m[0],o=b.createElement("div");o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=_.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&Y.test(k)&&o.insertBefore(b.createTextNode(Y.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bl(k[i]);else bl(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bd.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.expando,g=f.event.special,h=f.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&f.noData[j.nodeName.toLowerCase()])continue;c=j[f.expando];if(c){b=d[c]&&d[c][e];if(b&&b.events){for(var k in b.events)g[k]?f.event.remove(j,k):f.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[f.expando]:j.removeAttribute&&j.removeAttribute(f.expando),delete d[c]}}}});var bn=/alpha\([^)]*\)/i,bo=/opacity=([^)]*)/,bp=/([A-Z]|^ms)/g,bq=/^-?\d+(?:px)?$/i,br=/^-?\d/,bs=/^[+\-]=/,bt=/[^+\-\.\de]+/g,bu={position:"absolute",visibility:"hidden",display:"block"},bv=["Left","Right"],bw=["Top","Bottom"],bx,by,bz;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bx(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d;if(h==="number"&&isNaN(d)||d==null)return;h==="string"&&bs.test(d)&&(d=+d.replace(bt,"")+parseFloat(f.css(a,c)),h="number"),h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bx)return bx(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bA(a,b,d);f.swap(a,bu,function(){e=bA(a,b,d)});return e}},set:function(a,b){if(!bq.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bo.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle;c.zoom=1;var e=f.isNaN(b)?"":"alpha(opacity="+b*100+")",g=d&&d.filter||c.filter||"";c.filter=bn.test(g)?g.replace(bn,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bx(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(by=function(a,c){var d,e,g;c=c.replace(bp,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bz=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bq.test(d)&&br.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bx=by||bz,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bB=/%20/g,bC=/\[\]$/,bD=/\r?\n/g,bE=/#.*$/,bF=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bG=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bH=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,bI=/^(?:GET|HEAD)$/,bJ=/^\/\//,bK=/\?/,bL=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bM=/^(?:select|textarea)/i,bN=/\s+/,bO=/([?&])_=[^&]*/,bP=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bQ=f.fn.load,bR={},bS={},bT,bU;try{bT=e.href}catch(bV){bT=c.createElement("a"),bT.href="",bT=bT.href}bU=bP.exec(bT.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bQ)return bQ.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bL,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bM.test(this.nodeName)||bG.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bD,"\r\n")}}):{name:b.name,value:c.replace(bD,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?f.extend(!0,a,f.ajaxSettings,b):(b=a,a=f.extend(!0,f.ajaxSettings,b));for(var c in{context:1,url:1})c in b?a[c]=b[c]:c in f.ajaxSettings&&(a[c]=f.ajaxSettings[c]);return a},ajaxSettings:{url:bT,isLocal:bH.test(bU[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML}},ajaxPrefilter:bW(bR),ajaxTransport:bW(bS),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a?4:0;var o,r,u,w=l?bZ(d,v,l):b,x,y;if(a>=200&&a<300||a===304){if(d.ifModified){if(x=v.getResponseHeader("Last-Modified"))f.lastModified[k]=x;if(y=v.getResponseHeader("Etag"))f.etag[k]=y}if(a===304)c="notmodified",o=!0;else try{r=b$(d,w),c="success",o=!0}catch(z){c="parsererror",u=z}}else{u=c;if(!c||a)c="error",a<0&&(a=0)}v.status=a,v.statusText=c,o?h.resolveWith(e,[r,c,v]):h.rejectWith(e,[v,c,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.resolveWith(e,[v,c]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f._Deferred(),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bF.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.done,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bE,"").replace(bJ,bU[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bN),d.crossDomain==null&&(r=bP.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bU[1]&&r[2]==bU[2]&&(r[3]||(r[1]==="http:"?80:443))==(bU[3]||(bU[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bX(bR,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bI.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bK.test(d.url)?"&":"?")+d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bO,"$1_="+x);d.url=y+(y===d.url?(bK.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", */*; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bX(bS,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){status<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)bY(g,a[g],c,e);return d.join("&").replace(bB,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var b_=f.now(),ca=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+b_++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ca.test(b.url)||e&&ca.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ca,l),b.url===j&&(e&&(k=k.replace(ca,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cb=a.ActiveXObject?function(){for(var a in cd)cd[a](0,1)}:!1,cc=0,cd;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ce()||cf()}:ce,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cb&&delete cd[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cc,cb&&(cd||(cd={},f(a).unload(cb)),cd[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cg={},ch,ci,cj=/^(?:toggle|show|hide)$/,ck=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cl,cm=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cn,co=a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cr("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cs(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cr("hide",3),a,b,c);for(var d=0,e=this.length;d<e;d++)if(this[d].style){var g=f.css(this[d],"display");g!=="none"&&!f._data(this[d],"olddisplay")&&f._data(this[d],"olddisplay",g)}for(d=0;d<e;d++)this[d].style&&(this[d].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cr("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return this[e.queue===!1?"each":"queue"](function(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(f.support.inlineBlockNeedsLayout?(j=cs(this.nodeName),j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)):this.style.display="inline-block"))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)k=new f.fx(this,b,i),h=a[i],cj.test(h)?k[h==="toggle"?d?"show":"hide":h]():(l=ck.exec(h),m=k.cur(),l?(n=parseFloat(l[2]),o=l[3]||(f.cssNumber[i]?"":"px"),o!=="px"&&(f.style(this,i,(n||1)+o),m=(n||1)/k.cur()*m,f.style(this,i,m+o)),l[1]&&(n=(l[1]==="-="?-1:1)*n+m),k.custom(m,n,o)):k.custom(m,h,""));return!0})},stop:function(a,b){a&&this.queue([]),this.each(function(){var a=f.timers,c=a.length;b||f._unmark(!0,this);while(c--)a[c].elem===this&&(b&&a[c](!0),a.splice(c,1))}),b||this.dequeue();return this}}),f.each({slideDown:cr("show",1),slideUp:cr("hide",1),slideToggle:cr("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default,d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue!==!1?f.dequeue(this):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function h(a){return d.step(a)}var d=this,e=f.fx,g;this.startTime=cn||cp(),this.start=a,this.end=b,this.unit=c||this.unit||(f.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,h.elem=this.elem,h()&&f.timers.push(h)&&!cl&&(co?(cl=!0,g=function(){cl&&(co(g),e.tick())},co(g)):cl=setInterval(e.tick,e.interval))},show:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=cn||cp(),c=!0,d=this.elem,e=this.options,g,h;if(a||b>=e.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),e.animatedProperties[this.prop]=!0;for(g in e.animatedProperties)e.animatedProperties[g]!==!0&&(c=!1);if(c){e.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){d.style["overflow"+b]=e.overflow[a]}),e.hide&&f(d).hide();if(e.hide||e.show)for(var i in e.animatedProperties)f.style(d,i,e.orig[i]);e.complete.call(d)}return!1}e.duration==Infinity?this.now=b:(h=b-this.startTime,this.state=h/e.duration,this.pos=f.easing[e.animatedProperties[this.prop]](this.state,h,0,1,e.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){for(var a=f.timers,b=0;b<a.length;++b)a[b]()||a.splice(b--,1);a.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cl),cl=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var ct=/^t(?:able|d|h)$/i,cu=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cv(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);f.offset.initialize();var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.offset.doesNotAddBorder&&(!f.offset.doesAddBorderForTableAndCells||!ct.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={initialize:function(){var a=c.body,b=c.createElement("div"),d,e,g,h,i=parseFloat(f.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";f.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),d=b.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,this.doesNotAddBorder=e.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,e.style.position="fixed",e.style.top="20px",this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),f.offset.initialize=f.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.offset.initialize(),f.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cu.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cu.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cv(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cv(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a&&a.style?parseFloat(f.css(a,d,"padding")):null},f.fn["outer"+c]=function(a){var b=this[0];return b&&b.style?parseFloat(f.css(b,d,a?"margin":"border")):null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c];return e.document.compatMode==="CSS1Compat"&&g||e.document.body["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var h=f.css(e,d),i=parseFloat(h);return f.isNaN(i)?h:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window); |
components/modal/subscriptions-modal/dataset-manager/component.js | resource-watch/resource-watch | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import isEqual from 'lodash/isEqual';
// components
import CustomSelect from 'components/ui/CustomSelect';
import Field from 'components/form/Field';
import Input from 'components/form/Input';
const EMPTY_DATASET = {
id: null,
label: '',
value: '',
subscriptions: [],
threshold: 1,
};
class DatasetManager extends Component {
static propTypes = {
datasets: PropTypes.array.isRequired,
activeArea: PropTypes.object,
selectedDatasets: PropTypes.array.isRequired,
setUserSelection: PropTypes.func.isRequired,
}
static defaultProps = { activeArea: null }
state = { selectedDatasets: this.props.selectedDatasets };
UNSAFE_componentWillReceiveProps(nextProps) {
const { selectedDatasets } = this.props;
const { selectedDatasets: nextSelectedDatasets } = nextProps;
const selectedDatasetsChanged = !isEqual(selectedDatasets, nextSelectedDatasets);
if (selectedDatasetsChanged) this.setState({ selectedDatasets: nextSelectedDatasets });
}
onAddDataset = (dataset, index) => {
const { setUserSelection } = this.props;
const { selectedDatasets } = this.state;
if (selectedDatasets[index]) {
// by default, when the user selects a dataset for first time, selects the first subscriptions
const updatedSubscriptions = dataset.subscriptions;
updatedSubscriptions[0] = {
...updatedSubscriptions[0],
selected: true,
};
const updatedDataset = {
...dataset,
subscriptions: updatedSubscriptions,
};
selectedDatasets[index] = updatedDataset;
this.setState({ selectedDatasets: [...selectedDatasets] }, () => {
setUserSelection({
datasets: selectedDatasets
.filter((_dataset) => _dataset.id !== null),
});
});
} else {
this.setState({ selectedDatasets: [...selectedDatasets, ...[dataset]] }, () => {
setUserSelection({
datasets: selectedDatasets
.filter((_dataset) => _dataset.id !== null),
});
});
}
}
onAddNewSubscription = () => {
const { setUserSelection } = this.props;
const { selectedDatasets } = this.state;
this.setState({ selectedDatasets: [...selectedDatasets, ...[EMPTY_DATASET]] }, () => {
setUserSelection({
datasets: selectedDatasets
.filter((_dataset) => _dataset.id !== null),
});
});
}
onSetSubscription = ({ value }, index) => {
const { setUserSelection } = this.props;
const { selectedDatasets } = this.state;
if (selectedDatasets[index]) {
selectedDatasets[index] = {
...selectedDatasets[index],
subscriptions: selectedDatasets[index].subscriptions.map((_subscription) => ({
..._subscription,
...{ selected: _subscription.value === value },
})),
};
this.setState({ selectedDatasets: [...selectedDatasets] }, () => {
setUserSelection({
datasets: selectedDatasets
.filter((_dataset) => _dataset.id !== null),
});
});
}
}
onSetthreshold = (value, index) => {
const { setUserSelection } = this.props;
const { selectedDatasets } = this.state;
if (selectedDatasets[index]) {
selectedDatasets[index] = {
...selectedDatasets[index],
threshold: value,
};
this.setState({ selectedDatasets: [...selectedDatasets] }, () => {
setUserSelection({
datasets: selectedDatasets
.filter((_dataset) => _dataset.id !== null),
});
});
}
}
onRemoveDataset = (index) => {
const { setUserSelection } = this.props;
const { selectedDatasets } = this.state;
const filteredDatasets = selectedDatasets
.filter((elem, _index) => _index !== index);
this.setState({ selectedDatasets: filteredDatasets }, () => {
setUserSelection({ datasets: filteredDatasets });
});
}
render() {
const { datasets, activeArea } = this.props;
const { selectedDatasets } = this.state;
return (
<div className="c-dataset-manager">
{selectedDatasets.map((_selectedDataset, index) => (
<div
key={index}
className="selectors-container"
>
<Field
properties={{
name: index === 0 ? 'dataset' : null,
label: index === 0 ? 'Dataset' : null,
}}
>
<CustomSelect
placeholder="Select a dataset"
className={classnames({ '-disabled': activeArea !== null ? false : index === 0 && _selectedDataset.value })}
options={datasets}
clearable={false}
onValueChange={(val) => this.onAddDataset(val, index)}
allowNonLeafSelection={false}
value={_selectedDataset && _selectedDataset.value}
/>
</Field>
<Field
properties={{
name: index === 0 ? 'type' : null,
label: index === 0 ? 'Type' : null,
}}
>
<CustomSelect
placeholder="Select a subscription type"
className={classnames({ '-disabled': !_selectedDataset.subscriptions.length })}
options={_selectedDataset.subscriptions}
onValueChange={(val) => this.onSetSubscription(val, index)}
allowNonLeafSelection={false}
clearable={false}
value={(_selectedDataset.subscriptions
.find((_subscription) => _subscription.selected)
|| _selectedDataset.subscriptions[0] || {}).value}
/>
</Field>
<Field
className="threshold-input"
onChange={(val) => this.onSetthreshold(val, index)}
properties={{
name: 'threshold',
label: index === 0 ? 'Minimum' : null,
type: 'number',
default: _selectedDataset.threshold,
value: _selectedDataset.threshold,
}}
>
{Input}
</Field>
<Field
properties={{
name: 'delete',
label: index === 0 ? ' ' : null,
}}
>
<button
className="c-btn -secondary"
onClick={() => this.onRemoveDataset(index)}
>
Delete
</button>
</Field>
</div>
))}
<div className="subscription-btn-container">
<button
className={classnames('c-btn -b -fullwidth',
{ '-disabled': selectedDatasets.find((_selectedDataset) => _selectedDataset.id === null) })}
onClick={this.onAddNewSubscription}
>
Add subscription
</button>
</div>
</div>
);
}
}
export default DatasetManager;
|
test/regressions/site/src/tests/Checkbox/SimpleCheckbox.js | und3fined/material-ui | // @flow weak
import React from 'react';
import Checkbox from 'material-ui/Checkbox';
export default function SimpleCheckbox() {
return <Checkbox />;
}
|
files/highcharts/4.1.1/highcharts.src.js | Swatinem/jsdelivr | // ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
/**
* @license Highcharts JS v4.1.1 (2015-02-17)
*
* (c) 2009-2014 Torstein Honsi
*
* License: www.highcharts.com/license
*/
// JSLint options:
/*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */
/*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */
(function () {
// encapsulated variables
var UNDEFINED,
doc = document,
win = window,
math = Math,
mathRound = math.round,
mathFloor = math.floor,
mathCeil = math.ceil,
mathMax = math.max,
mathMin = math.min,
mathAbs = math.abs,
mathCos = math.cos,
mathSin = math.sin,
mathPI = math.PI,
deg2rad = mathPI * 2 / 360,
// some variables
userAgent = navigator.userAgent,
isOpera = win.opera,
isIE = /(msie|trident)/i.test(userAgent) && !isOpera,
docMode8 = doc.documentMode === 8,
isWebKit = /AppleWebKit/.test(userAgent),
isFirefox = /Firefox/.test(userAgent),
isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent),
SVG_NS = 'http://www.w3.org/2000/svg',
hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38
useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext,
Renderer,
hasTouch,
symbolSizes = {},
idCounter = 0,
garbageBin,
defaultOptions,
dateFormat, // function
globalAnimation,
pathAnim,
timeUnits,
noop = function () { return UNDEFINED; },
charts = [],
chartCount = 0,
PRODUCT = 'Highcharts',
VERSION = '4.1.1',
// some constants for frequently used strings
DIV = 'div',
ABSOLUTE = 'absolute',
RELATIVE = 'relative',
HIDDEN = 'hidden',
PREFIX = 'highcharts-',
VISIBLE = 'visible',
PX = 'px',
NONE = 'none',
M = 'M',
L = 'L',
numRegex = /^[0-9]+$/,
NORMAL_STATE = '',
HOVER_STATE = 'hover',
SELECT_STATE = 'select',
marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
// Object for extending Axis
AxisPlotLineOrBandExtension,
// constants for attributes
STROKE_WIDTH = 'stroke-width',
// time methods, changed based on whether or not UTC is used
Date, // Allow using a different Date class
makeTime,
timezoneOffset,
getTimezoneOffset,
getMinutes,
getHours,
getDay,
getDate,
getMonth,
getFullYear,
setMinutes,
setHours,
setDate,
setMonth,
setFullYear,
// lookup over the types and the associated classes
seriesTypes = {},
Highcharts;
// The Highcharts namespace
Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {};
Highcharts.seriesTypes = seriesTypes;
/**
* Extend an object with the members of another
* @param {Object} a The object to be extended
* @param {Object} b The object to add to the first one
*/
var extend = Highcharts.extend = function (a, b) {
var n;
if (!a) {
a = {};
}
for (n in b) {
a[n] = b[n];
}
return a;
};
/**
* Deep merge two or more objects and return a third object. If the first argument is
* true, the contents of the second object is copied into the first object.
* Previously this function redirected to jQuery.extend(true), but this had two limitations.
* First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
* it copied properties from extended prototypes.
*/
function merge() {
var i,
args = arguments,
len,
ret = {},
doCopy = function (copy, original) {
var value, key;
// An object is replacing a primitive
if (typeof copy !== 'object') {
copy = {};
}
for (key in original) {
if (original.hasOwnProperty(key)) {
value = original[key];
// Copy the contents of objects, but not arrays or DOM nodes
if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'
&& key !== 'renderTo' && typeof value.nodeType !== 'number') {
copy[key] = doCopy(copy[key] || {}, value);
// Primitives and arrays are copied over directly
} else {
copy[key] = original[key];
}
}
}
return copy;
};
// If first argument is true, copy into the existing object. Used in setOptions.
if (args[0] === true) {
ret = args[1];
args = Array.prototype.slice.call(args, 2);
}
// For each argument, extend the return
len = args.length;
for (i = 0; i < len; i++) {
ret = doCopy(ret, args[i]);
}
return ret;
}
/**
* Shortcut for parseInt
* @param {Object} s
* @param {Number} mag Magnitude
*/
function pInt(s, mag) {
return parseInt(s, mag || 10);
}
/**
* Check for string
* @param {Object} s
*/
function isString(s) {
return typeof s === 'string';
}
/**
* Check for object
* @param {Object} obj
*/
function isObject(obj) {
return obj && typeof obj === 'object';
}
/**
* Check for array
* @param {Object} obj
*/
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
/**
* Check for number
* @param {Object} n
*/
function isNumber(n) {
return typeof n === 'number';
}
function log2lin(num) {
return math.log(num) / math.LN10;
}
function lin2log(num) {
return math.pow(10, num);
}
/**
* Remove last occurence of an item from an array
* @param {Array} arr
* @param {Mixed} item
*/
function erase(arr, item) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
arr.splice(i, 1);
break;
}
}
//return arr;
}
/**
* Returns true if the object is not null or undefined. Like MooTools' $.defined.
* @param {Object} obj
*/
function defined(obj) {
return obj !== UNDEFINED && obj !== null;
}
/**
* Set or get an attribute or an object of attributes. Can't use jQuery attr because
* it attempts to set expando properties on the SVG element, which is not allowed.
*
* @param {Object} elem The DOM element to receive the attribute(s)
* @param {String|Object} prop The property or an abject of key-value pairs
* @param {String} value The value if a single property is set
*/
function attr(elem, prop, value) {
var key,
ret;
// if the prop is a string
if (isString(prop)) {
// set the value
if (defined(value)) {
elem.setAttribute(prop, value);
// get the value
} else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
ret = elem.getAttribute(prop);
}
// else if prop is defined, it is a hash of key/value pairs
} else if (defined(prop) && isObject(prop)) {
for (key in prop) {
elem.setAttribute(key, prop[key]);
}
}
return ret;
}
/**
* Check if an element is an array, and if not, make it into an array. Like
* MooTools' $.splat.
*/
function splat(obj) {
return isArray(obj) ? obj : [obj];
}
/**
* Return the first value that is defined. Like MooTools' $.pick.
*/
var pick = Highcharts.pick = function () {
var args = arguments,
i,
arg,
length = args.length;
for (i = 0; i < length; i++) {
arg = args[i];
if (arg !== UNDEFINED && arg !== null) {
return arg;
}
}
};
/**
* Set CSS on a given element
* @param {Object} el
* @param {Object} styles Style object with camel case property names
*/
function css(el, styles) {
if (isIE && !hasSVG) { // #2686
if (styles && styles.opacity !== UNDEFINED) {
styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
}
}
extend(el.style, styles);
}
/**
* Utility function to create element with attributes and styles
* @param {Object} tag
* @param {Object} attribs
* @param {Object} styles
* @param {Object} parent
* @param {Object} nopad
*/
function createElement(tag, attribs, styles, parent, nopad) {
var el = doc.createElement(tag);
if (attribs) {
extend(el, attribs);
}
if (nopad) {
css(el, {padding: 0, border: NONE, margin: 0});
}
if (styles) {
css(el, styles);
}
if (parent) {
parent.appendChild(el);
}
return el;
}
/**
* Extend a prototyped class by new members
* @param {Object} parent
* @param {Object} members
*/
function extendClass(parent, members) {
var object = function () { return UNDEFINED; };
object.prototype = new parent();
extend(object.prototype, members);
return object;
}
/**
* Pad a string to a given length by adding 0 to the beginning
* @param {Number} number
* @param {Number} length
*/
function pad(number, length) {
// Create an array of the remaining length +1 and join it with 0's
return new Array((length || 2) + 1 - String(number).length).join(0) + number;
}
/**
* Wrap a method with extended functionality, preserving the original function
* @param {Object} obj The context object that the method belongs to
* @param {String} method The name of the method to extend
* @param {Function} func A wrapper function callback. This function is called with the same arguments
* as the original function, except that the original function is unshifted and passed as the first
* argument.
*/
var wrap = Highcharts.wrap = function (obj, method, func) {
var proceed = obj[method];
obj[method] = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(proceed);
return func.apply(this, args);
};
};
function getTZOffset(timestamp) {
return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000;
}
/**
* Based on http://www.php.net/manual/en/function.strftime.php
* @param {String} format
* @param {Number} timestamp
* @param {Boolean} capitalize
*/
dateFormat = function (format, timestamp, capitalize) {
if (!defined(timestamp) || isNaN(timestamp)) {
return 'Invalid date';
}
format = pick(format, '%Y-%m-%d %H:%M:%S');
var date = new Date(timestamp - getTZOffset(timestamp)),
key, // used in for constuct below
// get the basic time values
hours = date[getHours](),
day = date[getDay](),
dayOfMonth = date[getDate](),
month = date[getMonth](),
fullYear = date[getFullYear](),
lang = defaultOptions.lang,
langWeekdays = lang.weekdays,
// List all format keys. Custom formats can be added from the outside.
replacements = extend({
// Day
'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
'A': langWeekdays[day], // Long weekday, like 'Monday'
'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
'e': dayOfMonth, // Day of the month, 1 through 31
'w': day,
// Week (none implemented)
//'W': weekNumber(),
// Month
'b': lang.shortMonths[month], // Short month, like 'Jan'
'B': lang.months[month], // Long month, like 'January'
'm': pad(month + 1), // Two digit month number, 01 through 12
// Year
'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
'Y': fullYear, // Four digits year, like 2009
// Time
'H': pad(hours), // Two digits hours in 24h format, 00 through 23
'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
}, Highcharts.dateFormats);
// do the replaces
for (key in replacements) {
while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
}
}
// Optionally capitalize the string and return
return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
};
/**
* Format a single variable. Similar to sprintf, without the % prefix.
*/
function formatSingle(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
if (val !== null) {
val = Highcharts.numberFormat(
val,
decimals,
lang.decimalPoint,
format.indexOf(',') > -1 ? lang.thousandsSep : ''
);
}
} else {
val = dateFormat(format, val);
}
return val;
}
/**
* Format a string according to a subset of the rules of Python's String.format method.
*/
function format(str, ctx) {
var splitter = '{',
isInside = false,
segment,
valueAndFormat,
path,
i,
len,
ret = [],
val,
index;
while ((index = str.indexOf(splitter)) !== -1) {
segment = str.slice(0, index);
if (isInside) { // we're on the closing bracket looking back
valueAndFormat = segment.split(':');
path = valueAndFormat.shift().split('.'); // get first and leave format
len = path.length;
val = ctx;
// Assign deeper paths
for (i = 0; i < len; i++) {
val = val[path[i]];
}
// Format the replacement
if (valueAndFormat.length) {
val = formatSingle(valueAndFormat.join(':'), val);
}
// Push the result and advance the cursor
ret.push(val);
} else {
ret.push(segment);
}
str = str.slice(index + 1); // the rest
isInside = !isInside; // toggle
splitter = isInside ? '}' : '{'; // now look for next matching bracket
}
ret.push(str);
return ret.join('');
}
/**
* Get the magnitude of a number
*/
function getMagnitude(num) {
return math.pow(10, mathFloor(math.log(num) / math.LN10));
}
/**
* Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
* @param {Number} interval
* @param {Array} multiples
* @param {Number} magnitude
* @param {Object} options
*/
function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) {
var normalized,
i,
retInterval = interval;
// round to a tenfold of 1, 2, 2.5 or 5
magnitude = pick(magnitude, 1);
normalized = interval / magnitude;
// multiples for a linear scale
if (!multiples) {
multiples = [1, 2, 2.5, 5, 10];
// the allowDecimals option
if (allowDecimals === false) {
if (magnitude === 1) {
multiples = [1, 2, 5, 10];
} else if (magnitude <= 0.1) {
multiples = [1 / magnitude];
}
}
}
// normalize the interval to the nearest multiple
for (i = 0; i < multiples.length; i++) {
retInterval = multiples[i];
if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural
(!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) {
break;
}
}
// multiply back to the correct magnitude
retInterval *= magnitude;
return retInterval;
}
/**
* Utility method that sorts an object array and keeping the order of equal items.
* ECMA script standard does not specify the behaviour when items are equal.
*/
function stableSort(arr, sortFunction) {
var length = arr.length,
sortValue,
i;
// Add index to each item
for (i = 0; i < length; i++) {
arr[i].ss_i = i; // stable sort index
}
arr.sort(function (a, b) {
sortValue = sortFunction(a, b);
return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
});
// Remove index from items
for (i = 0; i < length; i++) {
delete arr[i].ss_i; // stable sort index
}
}
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
function arrayMin(data) {
var i = data.length,
min = data[0];
while (i--) {
if (data[i] < min) {
min = data[i];
}
}
return min;
}
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
function arrayMax(data) {
var i = data.length,
max = data[0];
while (i--) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
/**
* Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
* It loops all properties and invokes destroy if there is a destroy method. The property is
* then delete'ed.
* @param {Object} The object to destroy properties on
* @param {Object} Exception, do not destroy this property, only delete it.
*/
function destroyObjectProperties(obj, except) {
var n;
for (n in obj) {
// If the object is non-null and destroy is defined
if (obj[n] && obj[n] !== except && obj[n].destroy) {
// Invoke the destroy
obj[n].destroy();
}
// Delete the property from the object.
delete obj[n];
}
}
/**
* Discard an element by moving it to the bin and delete
* @param {Object} The HTML node to discard
*/
function discardElement(element) {
// create a garbage bin element, not part of the DOM
if (!garbageBin) {
garbageBin = createElement(DIV);
}
// move the node and empty bin
if (element) {
garbageBin.appendChild(element);
}
garbageBin.innerHTML = '';
}
/**
* Provide error messages for debugging, with links to online explanation
*/
function error (code, stop) {
var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
if (stop) {
throw msg;
}
// else ...
if (win.console) {
console.log(msg);
}
}
/**
* Fix JS round off float errors
* @param {Number} num
*/
function correctFloat(num) {
return parseFloat(
num.toPrecision(14)
);
}
/**
* Set the global animation to either a given value, or fall back to the
* given chart's animation option
* @param {Object} animation
* @param {Object} chart
*/
function setAnimation(animation, chart) {
globalAnimation = pick(animation, chart.animation);
}
/**
* The time unit lookup
*/
timeUnits = {
millisecond: 1,
second: 1000,
minute: 60000,
hour: 3600000,
day: 24 * 3600000,
week: 7 * 24 * 3600000,
month: 28 * 24 * 3600000,
year: 364 * 24 * 3600000
};
/**
* Format a number and return a string based on input settings
* @param {Number} number The input number to format
* @param {Number} decimals The amount of decimals
* @param {String} decPoint The decimal point, defaults to the one given in the lang options
* @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
*/
Highcharts.numberFormat = function (number, decimals, decPoint, thousandsSep) {
var lang = defaultOptions.lang,
// http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
n = +number || 0,
c = decimals === -1 ?
(n.toString().split('.')[1] || '').length : // preserve decimals
(isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
d = decPoint === undefined ? lang.decimalPoint : decPoint,
t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
s = n < 0 ? "-" : "",
i = String(pInt(n = mathAbs(n).toFixed(c))),
j = i.length > 3 ? i.length % 3 : 0;
return (s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
(c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""));
};
/**
* Path interpolation algorithm used across adapters
*/
pathAnim = {
/**
* Prepare start and end values so that the path can be animated one to one
*/
init: function (elem, fromD, toD) {
fromD = fromD || '';
var shift = elem.shift,
bezier = fromD.indexOf('C') > -1,
numParams = bezier ? 7 : 3,
endLength,
slice,
i,
start = fromD.split(' '),
end = [].concat(toD), // copy
startBaseLine,
endBaseLine,
sixify = function (arr) { // in splines make move points have six parameters like bezier curves
i = arr.length;
while (i--) {
if (arr[i] === M) {
arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
}
}
};
if (bezier) {
sixify(start);
sixify(end);
}
// pull out the base lines before padding
if (elem.isArea) {
startBaseLine = start.splice(start.length - 6, 6);
endBaseLine = end.splice(end.length - 6, 6);
}
// if shifting points, prepend a dummy point to the end path
if (shift <= end.length / numParams && start.length === end.length) {
while (shift--) {
end = [].concat(end).splice(0, numParams).concat(end);
}
}
elem.shift = 0; // reset for following animations
// copy and append last point until the length matches the end length
if (start.length) {
endLength = end.length;
while (start.length < endLength) {
//bezier && sixify(start);
slice = [].concat(start).splice(start.length - numParams, numParams);
if (bezier) { // disable first control point
slice[numParams - 6] = slice[numParams - 2];
slice[numParams - 5] = slice[numParams - 1];
}
start = start.concat(slice);
}
}
if (startBaseLine) { // append the base lines for areas
start = start.concat(startBaseLine);
end = end.concat(endBaseLine);
}
return [start, end];
},
/**
* Interpolate each value of the path and return the array
*/
step: function (start, end, pos, complete) {
var ret = [],
i = start.length,
startVal;
if (pos === 1) { // land on the final path without adjustment points appended in the ends
ret = complete;
} else if (i === end.length && pos < 1) {
while (i--) {
startVal = parseFloat(start[i]);
ret[i] =
isNaN(startVal) ? // a letter instruction like M or L
start[i] :
pos * (parseFloat(end[i] - startVal)) + startVal;
}
} else { // if animation is finished or length not matching, land on right value
ret = end;
}
return ret;
}
};
(function ($) {
/**
* The default HighchartsAdapter for jQuery
*/
win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
/**
* Initialize the adapter by applying some extensions to jQuery
*/
init: function (pathAnim) {
// extend the animate function to allow SVG animations
var Fx = $.fx;
/*jslint unparam: true*//* allow unused param x in this function */
$.extend($.easing, {
easeOutQuad: function (x, t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
}
});
/*jslint unparam: false*/
// extend some methods to check for elem.attr, which means it is a Highcharts SVG object
$.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
var obj = Fx.step,
base;
// Handle different parent objects
if (fn === 'cur') {
obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
} else if (fn === '_default' && $.Tween) { // jQuery 1.8 model
obj = $.Tween.propHooks[fn];
fn = 'set';
}
// Overwrite the method
base = obj[fn];
if (base) { // step.width and step.height don't exist in jQuery < 1.7
// create the extended function replacement
obj[fn] = function (fx) {
var elem;
// Fx.prototype.cur does not use fx argument
fx = i ? fx : this;
// Don't run animations on textual properties like align (#1821)
if (fx.prop === 'align') {
return;
}
// shortcut
elem = fx.elem;
// Fx.prototype.cur returns the current value. The other ones are setters
// and returning a value has no effect.
return elem.attr ? // is SVG element wrapper
elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
base.apply(this, arguments); // use jQuery's built-in method
};
}
});
// Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+
wrap($.cssHooks.opacity, 'get', function (proceed, elem, computed) {
return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed);
});
// Define the setter function for d (path definitions)
this.addAnimSetter('d', function (fx) {
var elem = fx.elem,
ends;
// Normally start and end should be set in state == 0, but sometimes,
// for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
// in these cases
if (!fx.started) {
ends = pathAnim.init(elem, elem.d, elem.toD);
fx.start = ends[0];
fx.end = ends[1];
fx.started = true;
}
// Interpolate each value of the path
elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
});
/**
* Utility for iterating over an array. Parameters are reversed compared to jQuery.
* @param {Array} arr
* @param {Function} fn
*/
this.each = Array.prototype.forEach ?
function (arr, fn) { // modern browsers
return Array.prototype.forEach.call(arr, fn);
} :
function (arr, fn) { // legacy
var i,
len = arr.length;
for (i = 0; i < len; i++) {
if (fn.call(arr[i], arr[i], i, arr) === false) {
return i;
}
}
};
/**
* Register Highcharts as a plugin in the respective framework
*/
$.fn.highcharts = function () {
var constr = 'Chart', // default constructor
args = arguments,
options,
ret,
chart;
if (this[0]) {
if (isString(args[0])) {
constr = args[0];
args = Array.prototype.slice.call(args, 1);
}
options = args[0];
// Create the chart
if (options !== UNDEFINED) {
/*jslint unused:false*/
options.chart = options.chart || {};
options.chart.renderTo = this[0];
chart = new Highcharts[constr](options, args[1]);
ret = this;
/*jslint unused:true*/
}
// When called without parameters or with the return argument, get a predefined chart
if (options === UNDEFINED) {
ret = charts[attr(this[0], 'data-highcharts-chart')];
}
}
return ret;
};
},
/**
* Add an animation setter for a specific property
*/
addAnimSetter: function (prop, setter) {
// jQuery 1.8 style
if ($.Tween) {
$.Tween.propHooks[prop] = {
set: setter
};
// pre 1.8
} else {
$.fx.step[prop] = setter;
}
},
/**
* Downloads a script and executes a callback when done.
* @param {String} scriptLocation
* @param {Function} callback
*/
getScript: $.getScript,
/**
* Return the index of an item in an array, or -1 if not found
*/
inArray: $.inArray,
/**
* A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
* @param {Object} elem The HTML element
* @param {String} method Which method to run on the wrapped element
*/
adapterRun: function (elem, method) {
return $(elem)[method]();
},
/**
* Filter an array
*/
grep: $.grep,
/**
* Map an array
* @param {Array} arr
* @param {Function} fn
*/
map: function (arr, fn) {
//return jQuery.map(arr, fn);
var results = [],
i = 0,
len = arr.length;
for (; i < len; i++) {
results[i] = fn.call(arr[i], arr[i], i, arr);
}
return results;
},
/**
* Get the position of an element relative to the top left of the page
*/
offset: function (el) {
return $(el).offset();
},
/**
* Add an event listener
* @param {Object} el A HTML element or custom object
* @param {String} event The event type
* @param {Function} fn The event handler
*/
addEvent: function (el, event, fn) {
$(el).bind(event, fn);
},
/**
* Remove event added with addEvent
* @param {Object} el The object
* @param {String} eventType The event type. Leave blank to remove all events.
* @param {Function} handler The function to remove
*/
removeEvent: function (el, eventType, handler) {
// workaround for jQuery issue with unbinding custom events:
// http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
if (doc[func] && el && !el[func]) {
el[func] = function () {};
}
$(el).unbind(eventType, handler);
},
/**
* Fire an event on a custom object
* @param {Object} el
* @param {String} type
* @param {Object} eventArguments
* @param {Function} defaultFunction
*/
fireEvent: function (el, type, eventArguments, defaultFunction) {
var event = $.Event(type),
detachedType = 'detached' + type,
defaultPrevented;
// Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts
// never uses these properties, Chrome includes them in the default click event and
// raises the warning when they are copied over in the extend statement below.
//
// To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
// testing if they are there (warning in chrome) the only option is to test if running IE.
if (!isIE && eventArguments) {
delete eventArguments.layerX;
delete eventArguments.layerY;
delete eventArguments.returnValue;
}
extend(event, eventArguments);
// Prevent jQuery from triggering the object method that is named the
// same as the event. For example, if the event is 'select', jQuery
// attempts calling el.select and it goes into a loop.
if (el[type]) {
el[detachedType] = el[type];
el[type] = null;
}
// Wrap preventDefault and stopPropagation in try/catch blocks in
// order to prevent JS errors when cancelling events on non-DOM
// objects. #615.
/*jslint unparam: true*/
$.each(['preventDefault', 'stopPropagation'], function (i, fn) {
var base = event[fn];
event[fn] = function () {
try {
base.call(event);
} catch (e) {
if (fn === 'preventDefault') {
defaultPrevented = true;
}
}
};
});
/*jslint unparam: false*/
// trigger it
$(el).trigger(event);
// attach the method
if (el[detachedType]) {
el[type] = el[detachedType];
el[detachedType] = null;
}
if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
defaultFunction(event);
}
},
/**
* Extension method needed for MooTools
*/
washMouseEvent: function (e) {
var ret = e.originalEvent || e;
// computed by jQuery, needed by IE8
if (ret.pageX === UNDEFINED) { // #1236
ret.pageX = e.pageX;
ret.pageY = e.pageY;
}
return ret;
},
/**
* Animate a HTML element or SVG element wrapper
* @param {Object} el
* @param {Object} params
* @param {Object} options jQuery-like animation options: duration, easing, callback
*/
animate: function (el, params, options) {
var $el = $(el);
if (!el.style) {
el.style = {}; // #1881
}
if (params.d) {
el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
params.d = 1; // because in jQuery, animating to an array has a different meaning
}
$el.stop();
if (params.opacity !== UNDEFINED && el.attr) {
params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161)
}
el.hasAnim = 1; // #3342
$el.animate(params, options);
},
/**
* Stop running animation
*/
stop: function (el) {
if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy
$(el).stop();
}
}
});
}(win.jQuery));
// check for a custom HighchartsAdapter defined prior to this file
var globalAdapter = win.HighchartsAdapter,
adapter = globalAdapter || {};
// Initialize the adapter
if (globalAdapter) {
globalAdapter.init.call(globalAdapter, pathAnim);
}
// Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
// and all the utility functions will be null. In that case they are populated by the
// default adapters below.
var adapterRun = adapter.adapterRun,
getScript = adapter.getScript,
inArray = adapter.inArray,
each = Highcharts.each = adapter.each,
grep = adapter.grep,
offset = adapter.offset,
map = adapter.map,
addEvent = adapter.addEvent,
removeEvent = adapter.removeEvent,
fireEvent = adapter.fireEvent,
washMouseEvent = adapter.washMouseEvent,
animate = adapter.animate,
stop = adapter.stop;
/* ****************************************************************************
* Handle the options *
*****************************************************************************/
defaultOptions = {
colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c',
'#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'],
symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
lang: {
loading: 'Loading...',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
decimalPoint: '.',
numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
resetZoom: 'Reset zoom',
resetZoomTitle: 'Reset zoom level 1:1',
thousandsSep: ' '
},
global: {
useUTC: true,
//timezoneOffset: 0,
canvasToolsURL: 'http://code.highcharts.com/4.1.1/modules/canvas-tools.js',
VMLRadialGradientURL: 'http://code.highcharts.com/4.1.1/gfx/vml-radial-gradient.png'
},
chart: {
//animation: true,
//alignTicks: false,
//reflow: true,
//className: null,
//events: { load, selection },
//margin: [null],
//marginTop: null,
//marginRight: null,
//marginBottom: null,
//marginLeft: null,
borderColor: '#4572A7',
//borderWidth: 0,
borderRadius: 0,
defaultSeriesType: 'line',
ignoreHiddenSeries: true,
//inverted: false,
//shadow: false,
spacing: [10, 10, 15, 10],
//spacingTop: 10,
//spacingRight: 10,
//spacingBottom: 15,
//spacingLeft: 10,
//style: {
// fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
// fontSize: '12px'
//},
backgroundColor: '#FFFFFF',
//plotBackgroundColor: null,
plotBorderColor: '#C0C0C0',
//plotBorderWidth: 0,
//plotShadow: false,
//zoomType: ''
resetZoomButton: {
theme: {
zIndex: 20
},
position: {
align: 'right',
x: -10,
//verticalAlign: 'top',
y: 10
}
// relativeTo: 'plot'
}
},
title: {
text: 'Chart title',
align: 'center',
// floating: false,
margin: 15,
// x: 0,
// verticalAlign: 'top',
// y: null,
style: {
color: '#333333',
fontSize: '18px'
}
},
subtitle: {
text: '',
align: 'center',
// floating: false
// x: 0,
// verticalAlign: 'top',
// y: null,
style: {
color: '#555555'
}
},
plotOptions: {
line: { // base series options
allowPointSelect: false,
showCheckbox: false,
animation: {
duration: 1000
},
//connectNulls: false,
//cursor: 'default',
//clip: true,
//dashStyle: null,
//enableMouseTracking: true,
events: {},
//legendIndex: 0,
//linecap: 'round',
lineWidth: 2,
//shadow: false,
// stacking: null,
marker: {
//enabled: true,
//symbol: null,
lineWidth: 0,
radius: 4,
lineColor: '#FFFFFF',
//fillColor: null,
states: { // states for a single point
hover: {
enabled: true,
lineWidthPlus: 1,
radiusPlus: 2
},
select: {
fillColor: '#FFFFFF',
lineColor: '#000000',
lineWidth: 2
}
}
},
point: {
events: {}
},
dataLabels: {
align: 'center',
// defer: true,
// enabled: false,
formatter: function () {
return this.y === null ? '' : Highcharts.numberFormat(this.y, -1);
},
style: {
color: 'contrast',
fontSize: '11px',
fontWeight: 'bold',
textShadow: '0 0 6px contrast, 0 0 3px contrast'
},
verticalAlign: 'bottom', // above singular point
x: 0,
y: 0,
// backgroundColor: undefined,
// borderColor: undefined,
// borderRadius: undefined,
// borderWidth: undefined,
padding: 5
// shadow: false
},
cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
pointRange: 0,
//pointStart: 0,
//pointInterval: 1,
//showInLegend: null, // auto: true for standalone series, false for linked series
states: { // states for the entire series
hover: {
//enabled: false,
lineWidthPlus: 1,
marker: {
// lineWidth: base + 1,
// radius: base + 1
},
halo: {
size: 10,
opacity: 0.25
}
},
select: {
marker: {}
}
},
stickyTracking: true,
//tooltip: {
//pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>'
//valueDecimals: null,
//xDateFormat: '%A, %b %e, %Y',
//valuePrefix: '',
//ySuffix: ''
//}
turboThreshold: 1000
// zIndex: null
}
},
labels: {
//items: [],
style: {
//font: defaultFont,
position: ABSOLUTE,
color: '#3E576F'
}
},
legend: {
enabled: true,
align: 'center',
//floating: false,
layout: 'horizontal',
labelFormatter: function () {
return this.name;
},
//borderWidth: 0,
borderColor: '#909090',
borderRadius: 0,
navigation: {
// animation: true,
activeColor: '#274b6d',
// arrowSize: 12
inactiveColor: '#CCC'
// style: {} // text styles
},
// margin: 20,
// reversed: false,
shadow: false,
// backgroundColor: null,
/*style: {
padding: '5px'
},*/
itemStyle: {
color: '#333333',
fontSize: '12px',
fontWeight: 'bold'
},
itemHoverStyle: {
//cursor: 'pointer', removed as of #601
color: '#000'
},
itemHiddenStyle: {
color: '#CCC'
},
itemCheckboxStyle: {
position: ABSOLUTE,
width: '13px', // for IE precision
height: '13px'
},
// itemWidth: undefined,
// symbolRadius: 0,
// symbolWidth: 16,
symbolPadding: 5,
verticalAlign: 'bottom',
// width: undefined,
x: 0,
y: 0,
title: {
//text: null,
style: {
fontWeight: 'bold'
}
}
},
loading: {
// hideDuration: 100,
labelStyle: {
fontWeight: 'bold',
position: RELATIVE,
top: '45%'
},
// showDuration: 0,
style: {
position: ABSOLUTE,
backgroundColor: 'white',
opacity: 0.5,
textAlign: 'center'
}
},
tooltip: {
enabled: true,
animation: hasSVG,
//crosshairs: null,
backgroundColor: 'rgba(249, 249, 249, .85)',
borderWidth: 1,
borderRadius: 3,
dateTimeLabelFormats: {
millisecond: '%A, %b %e, %H:%M:%S.%L',
second: '%A, %b %e, %H:%M:%S',
minute: '%A, %b %e, %H:%M',
hour: '%A, %b %e, %H:%M',
day: '%A, %b %e, %Y',
week: 'Week from %A, %b %e, %Y',
month: '%B %Y',
year: '%Y'
},
footerFormat: '',
//formatter: defaultFormatter,
headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>',
shadow: true,
//shape: 'callout',
//shared: false,
snap: isTouchDevice ? 25 : 10,
style: {
color: '#333333',
cursor: 'default',
fontSize: '12px',
padding: '8px',
whiteSpace: 'nowrap'
}
//xDateFormat: '%A, %b %e, %Y',
//valueDecimals: null,
//valuePrefix: '',
//valueSuffix: ''
},
credits: {
enabled: true,
text: 'Highcharts.com',
href: 'http://www.highcharts.com',
position: {
align: 'right',
x: -10,
verticalAlign: 'bottom',
y: -5
},
style: {
cursor: 'pointer',
color: '#909090',
fontSize: '9px'
}
}
};
// Series defaults
var defaultPlotOptions = defaultOptions.plotOptions,
defaultSeriesOptions = defaultPlotOptions.line;
// set the default time methods
setTimeMethods();
/**
* Set the time methods globally based on the useUTC option. Time method can be either
* local time or UTC (default).
*/
function setTimeMethods() {
var globalOptions = defaultOptions.global,
useUTC = globalOptions.useUTC,
GET = useUTC ? 'getUTC' : 'get',
SET = useUTC ? 'setUTC' : 'set';
Date = globalOptions.Date || window.Date;
timezoneOffset = useUTC && globalOptions.timezoneOffset;
getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset;
makeTime = function (year, month, date, hours, minutes, seconds) {
var d;
if (useUTC) {
d = Date.UTC.apply(0, arguments);
d += getTZOffset(d);
} else {
d = new Date(
year,
month,
pick(date, 1),
pick(hours, 0),
pick(minutes, 0),
pick(seconds, 0)
).getTime();
}
return d;
};
getMinutes = GET + 'Minutes';
getHours = GET + 'Hours';
getDay = GET + 'Day';
getDate = GET + 'Date';
getMonth = GET + 'Month';
getFullYear = GET + 'FullYear';
setMinutes = SET + 'Minutes';
setHours = SET + 'Hours';
setDate = SET + 'Date';
setMonth = SET + 'Month';
setFullYear = SET + 'FullYear';
}
/**
* Merge the default options with custom options and return the new options structure
* @param {Object} options The new custom options
*/
function setOptions(options) {
// Copy in the default options
defaultOptions = merge(true, defaultOptions, options);
// Apply UTC
setTimeMethods();
return defaultOptions;
}
/**
* Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules
* wasn't enough because the setOptions method created a new object.
*/
function getOptions() {
return defaultOptions;
}
/**
* Handle color operations. The object methods are chainable.
* @param {String} input The input color in either rbga or hex format
*/
var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,
hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/;
var Color = function (input) {
// declare variables
var rgba = [], result, stops;
/**
* Parse the input color to rgba array
* @param {String} input
*/
function init(input) {
// Gradients
if (input && input.stops) {
stops = map(input.stops, function (stop) {
return Color(stop[1]);
});
// Solid colors
} else {
// rgba
result = rgbaRegEx.exec(input);
if (result) {
rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
} else {
// hex
result = hexRegEx.exec(input);
if (result) {
rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
} else {
// rgb
result = rgbRegEx.exec(input);
if (result) {
rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
}
}
}
}
}
/**
* Return the color a specified format
* @param {String} format
*/
function get(format) {
var ret;
if (stops) {
ret = merge(input);
ret.stops = [].concat(ret.stops);
each(stops, function (stop, i) {
ret.stops[i] = [ret.stops[i][0], stop.get(format)];
});
// it's NaN if gradient colors on a column chart
} else if (rgba && !isNaN(rgba[0])) {
if (format === 'rgb') {
ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
} else if (format === 'a') {
ret = rgba[3];
} else {
ret = 'rgba(' + rgba.join(',') + ')';
}
} else {
ret = input;
}
return ret;
}
/**
* Brighten the color
* @param {Number} alpha
*/
function brighten(alpha) {
if (stops) {
each(stops, function (stop) {
stop.brighten(alpha);
});
} else if (isNumber(alpha) && alpha !== 0) {
var i;
for (i = 0; i < 3; i++) {
rgba[i] += pInt(alpha * 255);
if (rgba[i] < 0) {
rgba[i] = 0;
}
if (rgba[i] > 255) {
rgba[i] = 255;
}
}
}
return this;
}
/**
* Set the color's opacity to a given alpha value
* @param {Number} alpha
*/
function setOpacity(alpha) {
rgba[3] = alpha;
return this;
}
// initialize: parse the input
init(input);
// public methods
return {
get: get,
brighten: brighten,
rgba: rgba,
setOpacity: setOpacity
};
};
/**
* A wrapper object for SVG elements
*/
function SVGElement() {}
SVGElement.prototype = {
// Default base for animation
opacity: 1,
// For labels, these CSS properties are applied to the <text> node directly
textProps: ['fontSize', 'fontWeight', 'fontFamily', 'color',
'lineHeight', 'width', 'textDecoration', 'textShadow'],
/**
* Initialize the SVG renderer
* @param {Object} renderer
* @param {String} nodeName
*/
init: function (renderer, nodeName) {
var wrapper = this;
wrapper.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(SVG_NS, nodeName);
wrapper.renderer = renderer;
},
/**
* Animate a given attribute
* @param {Object} params
* @param {Number} options The same options as in jQuery animation
* @param {Function} complete Function to perform at the end of animation
*/
animate: function (params, options, complete) {
var animOptions = pick(options, globalAnimation, true);
stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
if (animOptions) {
animOptions = merge(animOptions, {}); //#2625
if (complete) { // allows using a callback with the global animation without overwriting it
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params);
if (complete) {
complete();
}
}
return this;
},
/**
* Build an SVG gradient out of a common JavaScript configuration object
*/
colorGradient: function (color, prop, elem) {
var renderer = this.renderer,
colorObject,
gradName,
gradAttr,
gradients,
gradientObject,
stops,
stopColor,
stopOpacity,
radialReference,
n,
id,
key = [];
// Apply linear or radial gradients
if (color.linearGradient) {
gradName = 'linearGradient';
} else if (color.radialGradient) {
gradName = 'radialGradient';
}
if (gradName) {
gradAttr = color[gradName];
gradients = renderer.gradients;
stops = color.stops;
radialReference = elem.radialReference;
// Keep < 2.2 kompatibility
if (isArray(gradAttr)) {
color[gradName] = gradAttr = {
x1: gradAttr[0],
y1: gradAttr[1],
x2: gradAttr[2],
y2: gradAttr[3],
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
gradAttr = merge(gradAttr, {
cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
r: gradAttr.r * radialReference[2],
gradientUnits: 'userSpaceOnUse'
});
}
// Build the unique key to detect whether we need to create a new element (#1282)
for (n in gradAttr) {
if (n !== 'id') {
key.push(n, gradAttr[n]);
}
}
for (n in stops) {
key.push(stops[n]);
}
key = key.join(',');
// Check if a gradient object with the same config object is created within this renderer
if (gradients[key]) {
id = gradients[key].attr('id');
} else {
// Set the id and create the element
gradAttr.id = id = PREFIX + idCounter++;
gradients[key] = gradientObject = renderer.createElement(gradName)
.attr(gradAttr)
.add(renderer.defs);
// The gradient needs to keep a list of stops to be able to destroy them
gradientObject.stops = [];
each(stops, function (stop) {
var stopObject;
if (stop[1].indexOf('rgba') === 0) {
colorObject = Color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
}
// Set the reference to the gradient object
elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')');
}
},
/**
* Apply a polyfill to the text-stroke CSS property, by copying the text element
* and apply strokes to the copy.
*
* docs: update default, document the polyfill and the limitations on hex colors and pixel values, document contrast pseudo-color
* TODO:
* - update defaults
*/
applyTextShadow: function (textShadow) {
var elem = this.element,
tspans,
hasContrast = textShadow.indexOf('contrast') !== -1,
// Safari suffers from the double display bug (#3649)
isSafari = userAgent.indexOf('Safari') > 0 && userAgent.indexOf('Chrome') === -1,
// IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check
// this again with new IE release.
supports = elem.style.textShadow !== UNDEFINED && !isIE && !isSafari;
// When the text shadow is set to contrast, use dark stroke for light text and vice versa
if (hasContrast) {
textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill));
}
/* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/)
if (elem.textContent.indexOf('2.') === 0) {
elem.style['text-shadow'] = 'none';
supports = false;
}
// */
// No reason to polyfill, we've got native support
if (supports) {
if (hasContrast) { // Apply the altered style
css(elem, {
textShadow: textShadow
});
}
} else {
// In order to get the right y position of the clones,
// copy over the y setter
this.ySetter = this.xSetter;
tspans = [].slice.call(elem.getElementsByTagName('tspan'));
each(textShadow.split(/\s?,\s?/g), function (textShadow) {
var firstChild = elem.firstChild,
color,
strokeWidth;
textShadow = textShadow.split(' ');
color = textShadow[textShadow.length - 1];
// Approximately tune the settings to the text-shadow behaviour
strokeWidth = textShadow[textShadow.length - 2];
if (strokeWidth) {
each(tspans, function (tspan, y) {
var clone;
// Let the first line start at the correct X position
if (y === 0) {
tspan.setAttribute('x', elem.getAttribute('x'));
y = elem.getAttribute('y');
tspan.setAttribute('y', y || 0);
if (y === null) {
elem.setAttribute('y', 0);
}
}
// Create the clone and apply shadow properties
clone = tspan.cloneNode(1);
attr(clone, {
'stroke': color,
'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3),
'stroke-width': strokeWidth,
'stroke-linejoin': 'round'
});
elem.insertBefore(clone, firstChild);
});
}
});
}
},
/**
* Set or get a given attribute
* @param {Object|String} hash
* @param {Mixed|Undefined} val
*/
attr: function (hash, val) {
var key,
value,
element = this.element,
hasSetSymbolSize,
ret = this,
skipAttr;
// single key-value pair
if (typeof hash === 'string' && val !== UNDEFINED) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (typeof hash === 'string') {
ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element);
// setter
} else {
for (key in hash) {
value = hash[key];
skipAttr = false;
if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
if (!hasSetSymbolSize) {
this.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
}
if (this.rotation && (key === 'x' || key === 'y')) {
this.doTransform = true;
}
if (!skipAttr) {
(this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element);
}
// Let the shadow follow the main element
if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
this.updateShadows(key, value);
}
}
// Update transform. Do this outside the loop to prevent redundant updating for batch setting
// of attributes.
if (this.doTransform) {
this.updateTransform();
this.doTransform = false;
}
}
return ret;
},
updateShadows: function (key, value) {
var shadows = this.shadows,
i = shadows.length;
while (i--) {
shadows[i].setAttribute(
key,
key === 'height' ?
mathMax(value - (shadows[i].cutHeight || 0), 0) :
key === 'd' ? this.d : value
);
}
},
/**
* Add a class name to an element
*/
addClass: function (className) {
var element = this.element,
currentClassName = attr(element, 'class') || '';
if (currentClassName.indexOf(className) === -1) {
attr(element, 'class', currentClassName + ' ' + className);
}
return this;
},
/* hasClass and removeClass are not (yet) needed
hasClass: function (className) {
return attr(this.element, 'class').indexOf(className) !== -1;
},
removeClass: function (className) {
attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
return this;
},
*/
/**
* If one of the symbol size affecting parameters are changed,
* check all the others only once for each call to an element's
* .attr() method
* @param {Object} hash
*/
symbolAttr: function (hash) {
var wrapper = this;
each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
wrapper[key] = pick(hash[key], wrapper[key]);
});
wrapper.attr({
d: wrapper.renderer.symbols[wrapper.symbolName](
wrapper.x,
wrapper.y,
wrapper.width,
wrapper.height,
wrapper
)
});
},
/**
* Apply a clipping path to this object
* @param {String} id
*/
clip: function (clipRect) {
return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
},
/**
* Calculate the coordinates needed for drawing a rectangle crisply and return the
* calculated attributes
* @param {Number} strokeWidth
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
crisp: function (rect) {
var wrapper = this,
key,
attribs = {},
normalizer,
strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0;
normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
// normalize for crisp edges
rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer;
rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer;
rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer);
rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer);
rect.strokeWidth = strokeWidth;
for (key in rect) {
if (wrapper[key] !== rect[key]) { // only set attribute if changed
wrapper[key] = attribs[key] = rect[key];
}
}
return attribs;
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: function (styles) {
var elemWrapper = this,
oldStyles = elemWrapper.styles,
newStyles = {},
elem = elemWrapper.element,
textWidth,
n,
serializedCss = '',
hyphenate,
hasNew = !oldStyles;
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Filter out existing styles to increase performance (#2640)
if (oldStyles) {
for (n in styles) {
if (styles[n] !== oldStyles[n]) {
newStyles[n] = styles[n];
hasNew = true;
}
}
}
if (hasNew) {
textWidth = elemWrapper.textWidth =
(styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) ||
elemWrapper.textWidth; // #3501
// Merge the new styles with the old ones
if (oldStyles) {
styles = extend(
oldStyles,
newStyles
);
}
// store object
elemWrapper.styles = styles;
if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) {
delete styles.width;
}
// serialize and set style attribute
if (isIE && !hasSVG) {
css(elemWrapper.element, styles);
} else {
/*jslint unparam: true*/
hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
/*jslint unparam: false*/
for (n in styles) {
serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
}
attr(elem, 'style', serializedCss); // #1881
}
// re-build text
if (textWidth && elemWrapper.added) {
elemWrapper.renderer.buildText(elemWrapper);
}
}
return elemWrapper;
},
/**
* Add an event listener
* @param {String} eventType
* @param {Function} handler
*/
on: function (eventType, handler) {
var svgElement = this,
element = svgElement.element;
// touch
if (hasTouch && eventType === 'click') {
element.ontouchstart = function (e) {
svgElement.touchEventFired = Date.now();
e.preventDefault();
handler.call(element, e);
};
element.onclick = function (e) {
if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
handler.call(element, e);
}
};
} else {
// simplest possible event model for internal use
element['on' + eventType] = handler;
}
return this;
},
/**
* Set the coordinates needed to draw a consistent radial gradient across
* pie slices regardless of positioning inside the chart. The format is
* [centerX, centerY, diameter] in pixels.
*/
setRadialReference: function (coordinates) {
this.element.radialReference = coordinates;
return this;
},
/**
* Move an object and its children by x and y values
* @param {Number} x
* @param {Number} y
*/
translate: function (x, y) {
return this.attr({
translateX: x,
translateY: y
});
},
/**
* Invert a group, rotate and flip
*/
invert: function () {
var wrapper = this;
wrapper.inverted = true;
wrapper.updateTransform();
return wrapper;
},
/**
* Private method to update the transform attribute based on internal
* properties
*/
updateTransform: function () {
var wrapper = this,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
scaleX = wrapper.scaleX,
scaleY = wrapper.scaleY,
inverted = wrapper.inverted,
rotation = wrapper.rotation,
element = wrapper.element,
transform;
// flipping affects translate as adjustment for flipping around the group's axis
if (inverted) {
translateX += wrapper.attr('width');
translateY += wrapper.attr('height');
}
// Apply translate. Nearly all transformed elements have translation, so instead
// of checking for translate = 0, do it always (#1767, #1846).
transform = ['translate(' + translateX + ',' + translateY + ')'];
// apply rotation
if (inverted) {
transform.push('rotate(90) scale(-1,1)');
} else if (rotation) { // text rotation
transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')');
// Delete bBox memo when the rotation changes
//delete wrapper.bBox;
}
// apply scale
if (defined(scaleX) || defined(scaleY)) {
transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
}
if (transform.length) {
element.setAttribute('transform', transform.join(' '));
}
},
/**
* Bring the element to the front
*/
toFront: function () {
var element = this.element;
element.parentNode.appendChild(element);
return this;
},
/**
* Break down alignment options like align, verticalAlign, x and y
* to x and y relative to the chart.
*
* @param {Object} alignOptions
* @param {Boolean} alignByTranslate
* @param {String[Object} box The box to align to, needs a width and height. When the
* box is a string, it refers to an object in the Renderer. For example, when
* box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
* x and y properties.
*
*/
align: function (alignOptions, alignByTranslate, box) {
var align,
vAlign,
x,
y,
attribs = {},
alignTo,
renderer = this.renderer,
alignedObjects = renderer.alignedObjects;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) { // boxes other than renderer handle this internally
this.alignTo = alignTo = box || 'renderer';
erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
alignedObjects.push(this);
box = null; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(box, renderer[alignTo], renderer);
// Assign variables
align = alignOptions.align;
vAlign = alignOptions.verticalAlign;
x = (box.x || 0) + (alignOptions.x || 0); // default: left align
y = (box.y || 0) + (alignOptions.y || 0); // default: top align
// Align
if (align === 'right' || align === 'center') {
x += (box.width - (alignOptions.width || 0)) /
{ right: 1, center: 2 }[align];
}
attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
// Vertical align
if (vAlign === 'bottom' || vAlign === 'middle') {
y += (box.height - (alignOptions.height || 0)) /
({ bottom: 1, middle: 2 }[vAlign] || 1);
}
attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
// Animate only if already placed
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
this.alignAttr = attribs;
return this;
},
/**
* Get the bounding box (width, height, x and y) for the element
*/
getBBox: function (reload) {
var wrapper = this,
bBox,// = wrapper.bBox,
renderer = wrapper.renderer,
width,
height,
rotation = wrapper.rotation,
element = wrapper.element,
styles = wrapper.styles,
rad = rotation * deg2rad,
textStr = wrapper.textStr,
cacheKey;
if (textStr !== UNDEFINED) {
// Properties that affect bounding box
cacheKey = ['', rotation || 0, styles && styles.fontSize, element.style.width].join(',');
// Since numbers are monospaced, and numerical labels appear a lot in a chart,
// we assume that a label of n characters has the same bounding box as others
// of the same length.
if (textStr === '' || numRegex.test(textStr)) {
cacheKey = 'num:' + textStr.toString().length + cacheKey;
// Caching all strings reduces rendering time by 4-5%.
} else {
cacheKey = textStr + cacheKey;
}
}
if (cacheKey && !reload) {
bBox = renderer.cache[cacheKey];
}
// No cache found
if (!bBox) {
// SVG elements
if (element.namespaceURI === SVG_NS || renderer.forExport) {
try { // Fails in Firefox if the container has display: none.
bBox = element.getBBox ?
// SVG: use extend because IE9 is not allowed to change width and height in case
// of rotation (below)
extend({}, element.getBBox()) :
// Canvas renderer and legacy IE in export mode
{
width: element.offsetWidth,
height: element.offsetHeight
};
} catch (e) {}
// If the bBox is not set, the try-catch block above failed. The other condition
// is for Opera that returns a width of -Infinity on hidden elements.
if (!bBox || bBox.width < 0) {
bBox = { width: 0, height: 0 };
}
// VML Renderer or useHTML within SVG
} else {
bBox = wrapper.htmlGetBBox();
}
// True SVG elements as well as HTML elements in modern browsers using the .useHTML option
// need to compensated for rotation
if (renderer.isSVG) {
width = bBox.width;
height = bBox.height;
// Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568)
if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') {
bBox.height = height = 14;
}
// Adjust for rotated text
if (rotation) {
bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
}
}
// Cache it
renderer.cache[cacheKey] = bBox;
}
return bBox;
},
/**
* Show the element
*/
show: function (inherit) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881)
if (inherit && this.element.namespaceURI === SVG_NS) {
this.element.removeAttribute('visibility');
} else {
this.attr({ visibility: inherit ? 'inherit' : VISIBLE });
}
return this;
},
/**
* Hide the element
*/
hide: function () {
return this.attr({ visibility: HIDDEN });
},
fadeOut: function (duration) {
var elemWrapper = this;
elemWrapper.animate({
opacity: 0
}, {
duration: duration || 150,
complete: function () {
elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips
}
});
},
/**
* Add the element
* @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
* to append the element to the renderer.box.
*/
add: function (parent) {
var renderer = this.renderer,
element = this.element,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// Mark as added
this.added = true;
// If we're adding to renderer root, or other elements in the group
// have a z index, we need to handle it
if (!parent || parent.handleZ || this.zIndex) {
inserted = this.zIndexSetter();
}
// If zIndex is not handled, append at the end
if (!inserted) {
(parent ? parent.element : renderer.box).appendChild(element);
}
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
},
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function (element) {
var parentNode = element.parentNode;
if (parentNode) {
parentNode.removeChild(element);
}
},
/**
* Destroy the element and element wrapper
*/
destroy: function () {
var wrapper = this,
element = wrapper.element || {},
shadows = wrapper.shadows,
parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
grandParent,
key,
i;
// remove events
element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
stop(wrapper); // stop running animations
if (wrapper.clipPath) {
wrapper.clipPath = wrapper.clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if (wrapper.stops) {
for (i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper.safeRemoveChild(element);
// destroy shadows
if (shadows) {
each(shadows, function (shadow) {
wrapper.safeRemoveChild(shadow);
});
}
// In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697).
while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) {
grandParent = parentToClean.parentGroup;
wrapper.safeRemoveChild(parentToClean.div);
delete parentToClean.div;
parentToClean = grandParent;
}
// remove from alignObjects
if (wrapper.alignTo) {
erase(wrapper.renderer.alignedObjects, wrapper);
}
for (key in wrapper) {
delete wrapper[key];
}
return null;
},
/**
* Add a shadow to the element. Must be done after the element is added to the DOM
* @param {Boolean|Object} shadowOptions
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
shadow,
element = this.element,
strokeWidth,
shadowWidth,
shadowElementOpacity,
// compensate for inverted plot area
transform;
if (shadowOptions) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
transform = this.parentInverted ?
'(-1,-1)' :
'(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
for (i = 1; i <= shadowWidth; i++) {
shadow = element.cloneNode(0);
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
attr(shadow, {
'isShadow': 'true',
'stroke': shadowOptions.color || 'black',
'stroke-opacity': shadowElementOpacity * i,
'stroke-width': strokeWidth,
'transform': 'translate' + transform,
'fill': NONE
});
if (cutOff) {
attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
shadow.cutHeight = strokeWidth;
}
if (group) {
group.element.appendChild(shadow);
} else {
element.parentNode.insertBefore(shadow, element);
}
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
},
xGetter: function (key) {
if (this.element.nodeName === 'circle') {
key = { x: 'cx', y: 'cy' }[key] || key;
}
return this._defaultGetter(key);
},
/**
* Get the current value of an attribute or pseudo attribute, used mainly
* for animation.
*/
_defaultGetter: function (key) {
var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
},
dSetter: function (value, key, element) {
if (value && value.join) { // join path
value = value.join(' ');
}
if (/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
element.setAttribute(key, value);
this[key] = value;
},
dashstyleSetter: function (value) {
var i;
value = value && value.toLowerCase();
if (value) {
value = value
.replace('shortdashdotdot', '3,1,1,1,1,1,')
.replace('shortdashdot', '3,1,1,1')
.replace('shortdot', '1,1,')
.replace('shortdash', '3,1,')
.replace('longdash', '8,3,')
.replace(/dot/g, '1,3,')
.replace('dash', '4,3,')
.replace(/,$/, '')
.split(','); // ending comma
i = value.length;
while (i--) {
value[i] = pInt(value[i]) * this['stroke-width'];
}
value = value.join(',')
.replace('NaN', 'none'); // #3226
this.element.setAttribute('stroke-dasharray', value);
}
},
alignSetter: function (value) {
this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]);
},
opacitySetter: function (value, key, element) {
this[key] = value;
element.setAttribute(key, value);
},
titleSetter: function (value) {
var titleNode = this.element.getElementsByTagName('title')[0];
if (!titleNode) {
titleNode = doc.createElementNS(SVG_NS, 'title');
this.element.appendChild(titleNode);
}
titleNode.textContent = pick(value, '').replace(/<[^>]*>/g, ''); // #3276
},
textSetter: function (value) {
if (value !== this.textStr) {
// Delete bBox memo when the text changes
delete this.bBox;
this.textStr = value;
if (this.added) {
this.renderer.buildText(this);
}
}
},
fillSetter: function (value, key, element) {
if (typeof value === 'string') {
element.setAttribute(key, value);
} else if (value) {
this.colorGradient(value, key, element);
}
},
zIndexSetter: function (value, key) {
var renderer = this.renderer,
parentGroup = this.parentGroup,
parentWrapper = parentGroup || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
otherElement,
otherZIndex,
element = this.element,
inserted,
i;
if (defined(value)) {
element.setAttribute(key, value); // So we can read it for other elements in the group
this[key] = +value;
}
// Insert according to this and other elements' zIndex. Before .add() is called,
// nothing is done. Then on add, or by later calls to zIndexSetter, the node
// is placed on the right place in the DOM.
if (this.added) {
value = this.zIndex;
if (value && parentGroup) {
parentGroup.handleZ = true;
}
childNodes = parentNode.childNodes;
for (i = 0; i < childNodes.length && !inserted; i++) {
otherElement = childNodes[i];
otherZIndex = attr(otherElement, 'zIndex');
if (otherElement !== element && (
// Insert before the first element with a higher zIndex
pInt(otherZIndex) > value ||
// If no zIndex given, insert before the first element with a zIndex
(!defined(value) && defined(otherZIndex))
)) {
parentNode.insertBefore(element, otherElement);
inserted = true;
}
}
if (!inserted) {
parentNode.appendChild(element);
}
}
return inserted;
},
_defaultSetter: function (value, key, element) {
element.setAttribute(key, value);
}
};
// Some shared setters and getters
SVGElement.prototype.yGetter = SVGElement.prototype.xGetter;
SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter =
SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter =
SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) {
this[key] = value;
this.doTransform = true;
};
// WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the
// stroke attribute altogether. #1270, #1369, #3065, #3072.
SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) {
this[key] = value;
// Only apply the stroke attribute if the stroke width is defined and larger than 0
if (this.stroke && this['stroke-width']) {
this.strokeWidth = this['stroke-width'];
SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden
element.setAttribute('stroke-width', this['stroke-width']);
this.hasStroke = true;
} else if (key === 'stroke-width' && value === 0 && this.hasStroke) {
element.removeAttribute('stroke');
this.hasStroke = false;
}
};
/**
* The default SVG renderer
*/
var SVGRenderer = function () {
this.init.apply(this, arguments);
};
SVGRenderer.prototype = {
Element: SVGElement,
/**
* Initialize the SVGRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
* @param {Boolean} forExport
*/
init: function (container, width, height, style, forExport) {
var renderer = this,
loc = location,
boxWrapper,
element,
desc;
boxWrapper = renderer.createElement('svg')
.attr({
version: '1.1'
})
.css(this.getStyle(style));
element = boxWrapper.element;
container.appendChild(element);
// For browsers other than IE, add the namespace attribute (#1978)
if (container.innerHTML.indexOf('xmlns') === -1) {
attr(element, 'xmlns', SVG_NS);
}
// object properties
renderer.isSVG = true;
renderer.box = element;
renderer.boxWrapper = boxWrapper;
renderer.alignedObjects = [];
// Page url used for internal references. #24, #672, #1070
renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
loc.href
.replace(/#.*?$/, '') // remove the hash
.replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
.replace(/ /g, '%20') : // replace spaces (needed for Safari only)
'';
// Add description
desc = this.createElement('desc').add();
desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
renderer.defs = this.createElement('defs').add();
renderer.forExport = forExport;
renderer.gradients = {}; // Object where gradient SvgElements are stored
renderer.cache = {}; // Cache for numerical bounding boxes
renderer.setSize(width, height, false);
// Issue 110 workaround:
// In Firefox, if a div is positioned by percentage, its pixel position may land
// between pixels. The container itself doesn't display this, but an SVG element
// inside this container will be drawn at subpixel precision. In order to draw
// sharp lines, this must be compensated for. This doesn't seem to work inside
// iframes though (like in jsFiddle).
var subPixelFix, rect;
if (isFirefox && container.getBoundingClientRect) {
renderer.subPixelFix = subPixelFix = function () {
css(container, { left: 0, top: 0 });
rect = container.getBoundingClientRect();
css(container, {
left: (mathCeil(rect.left) - rect.left) + PX,
top: (mathCeil(rect.top) - rect.top) + PX
});
};
// run the fix now
subPixelFix();
// run it on resize
addEvent(win, 'resize', subPixelFix);
}
},
getStyle: function (style) {
return (this.style = extend({
fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font
fontSize: '12px'
}, style));
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none. #608.
*/
isHidden: function () {
return !this.boxWrapper.getBBox().width;
},
/**
* Destroys the renderer and its allocated members.
*/
destroy: function () {
var renderer = this,
rendererDefs = renderer.defs;
renderer.box = null;
renderer.boxWrapper = renderer.boxWrapper.destroy();
// Call destroy on all gradient elements
destroyObjectProperties(renderer.gradients || {});
renderer.gradients = null;
// Defs are null in VMLRenderer
// Otherwise, destroy them here.
if (rendererDefs) {
renderer.defs = rendererDefs.destroy();
}
// Remove sub pixel fix handler
// We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
// See issue #982
if (renderer.subPixelFix) {
removeEvent(win, 'resize', renderer.subPixelFix);
}
renderer.alignedObjects = null;
return null;
},
/**
* Create a wrapper for an SVG element
* @param {Object} nodeName
*/
createElement: function (nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
},
/**
* Dummy function for use in canvas renderer
*/
draw: function () {},
/**
* Parse a simple HTML string into SVG tspans
*
* @param {Object} textNode The parent text SVG node
*/
buildText: function (wrapper) {
var textNode = wrapper.element,
renderer = this,
forExport = renderer.forExport,
textStr = pick(wrapper.textStr, '').toString(),
hasMarkup = textStr.indexOf('<') !== -1,
lines,
childNodes = textNode.childNodes,
styleRegex,
hrefRegex,
parentX = attr(textNode, 'x'),
textStyles = wrapper.styles,
width = wrapper.textWidth,
textLineHeight = textStyles && textStyles.lineHeight,
textShadow = textStyles && textStyles.textShadow,
ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
i = childNodes.length,
tempParent = width && !wrapper.added && this.box,
getLineHeight = function (tspan) {
return textLineHeight ?
pInt(textLineHeight) :
renderer.fontMetrics(
/(px|em)$/.test(tspan && tspan.style.fontSize) ?
tspan.style.fontSize :
((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12),
tspan
).h;
},
unescapeAngleBrackets = function (inputStr) {
return inputStr.replace(/</g, '<').replace(/>/g, '>');
};
/// remove old text
while (i--) {
textNode.removeChild(childNodes[i]);
}
// Skip tspans, add text directly to text node. The forceTSpan is a hook
// used in text outline hack.
if (!hasMarkup && !textShadow && !ellipsis && textStr.indexOf(' ') === -1) {
textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr)));
return;
// Complex strings, add more logic
} else {
styleRegex = /<.*style="([^"]+)".*>/;
hrefRegex = /<.*href="(http[^"]+)".*>/;
if (tempParent) {
tempParent.appendChild(textNode); // attach it to the DOM to read offset width
}
if (hasMarkup) {
lines = textStr
.replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
.replace(/<(i|em)>/g, '<span style="font-style:italic">')
.replace(/<a/g, '<span')
.replace(/<\/(b|strong|i|em|a)>/g, '</span>')
.split(/<br.*?>/g);
} else {
lines = [textStr];
}
// remove empty line at end
if (lines[lines.length - 1] === '') {
lines.pop();
}
// build the lines
each(lines, function (line, lineNo) {
var spans, spanNo = 0;
line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
spans = line.split('|||');
each(spans, function (span) {
if (span !== '' || spans.length === 1) {
var attributes = {},
tspan = doc.createElementNS(SVG_NS, 'tspan'),
spanStyle; // #390
if (styleRegex.test(span)) {
spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
attr(tspan, 'style', spanStyle);
}
if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
css(tspan, { cursor: 'pointer' });
}
span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' ');
// Nested tags aren't supported, and cause crash in Safari (#1596)
if (span !== ' ') {
// add the text node
tspan.appendChild(doc.createTextNode(span));
if (!spanNo) { // first span in a line, align it to the left
if (lineNo && parentX !== null) {
attributes.x = parentX;
}
} else {
attributes.dx = 0; // #16
}
// add attributes
attr(tspan, attributes);
// Append it
textNode.appendChild(tspan);
// first span on subsequent line, add the line height
if (!spanNo && lineNo) {
// allow getting the right offset height in exporting in IE
if (!hasSVG && forExport) {
css(tspan, { display: 'block' });
}
// Set the line height based on the font size of either
// the text element or the tspan element
attr(
tspan,
'dy',
getLineHeight(tspan)
);
}
/*if (width) {
renderer.breakText(wrapper, width);
}*/
// Check width and apply soft breaks or ellipsis
if (width) {
var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'),
tooLong,
wasTooLong,
actualWidth,
rest = [],
dy = getLineHeight(tspan),
softLineNo = 1,
rotation = wrapper.rotation,
wordStr = span, // for ellipsis
cursor = wordStr.length, // binary search cursor
bBox;
while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) {
wrapper.rotation = 0; // discard rotation when computing box
bBox = wrapper.getBBox(true);
actualWidth = bBox.width;
// Old IE cannot measure the actualWidth for SVG elements (#2314)
if (!hasSVG && renderer.forExport) {
actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
}
tooLong = actualWidth > width;
// For ellipsis, do a binary search for the correct string length
if (wasTooLong === undefined) {
wasTooLong = tooLong; // First time
}
if (ellipsis && wasTooLong) {
cursor /= 2;
if (wordStr === '' || (!tooLong && cursor < 0.5)) {
words = []; // All ok, break out
} else {
if (tooLong) {
wasTooLong = true;
}
wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor));
words = [wordStr + '\u2026'];
tspan.removeChild(tspan.firstChild);
}
// Looping down, this is the first word sequence that is not too long,
// so we can move on to build the next line.
} else if (!tooLong || words.length === 1) {
words = rest;
rest = [];
if (words.length) {
softLineNo++;
tspan = doc.createElementNS(SVG_NS, 'tspan');
attr(tspan, {
dy: dy,
x: parentX
});
if (spanStyle) { // #390
attr(tspan, 'style', spanStyle);
}
textNode.appendChild(tspan);
}
if (actualWidth > width) { // a single word is pressing it out
width = actualWidth;
}
} else { // append to existing line tspan
tspan.removeChild(tspan.firstChild);
rest.unshift(words.pop());
}
if (words.length) {
tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
}
}
if (wasTooLong) {
wrapper.attr('title', wrapper.textStr);
}
wrapper.rotation = rotation;
}
spanNo++;
}
}
});
});
if (tempParent) {
tempParent.removeChild(textNode); // attach it to the DOM to read offset width
}
// Apply the text shadow
if (textShadow && wrapper.applyTextShadow) {
wrapper.applyTextShadow(textShadow);
}
}
},
/*
breakText: function (wrapper, width) {
var bBox = wrapper.getBBox(),
node = wrapper.element,
textLength = node.textContent.length,
pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width
increment = 0,
finalPos;
if (bBox.width > width) {
while (finalPos === undefined) {
textLength = node.getSubStringLength(0, pos);
if (textLength <= width) {
if (increment === -1) {
finalPos = pos;
} else {
increment = 1;
}
} else {
if (increment === 1) {
finalPos = pos - 1;
} else {
increment = -1;
}
}
pos += increment;
}
}
console.log(finalPos, node.getSubStringLength(0, finalPos))
},
*/
/**
* Returns white for dark colors and black for bright colors
*/
getContrast: function (color) {
color = Color(color).rgba;
return color[0] + color[1] + color[2] > 384 ? '#000' : '#FFF';
},
/**
* Create a button with preset states
* @param {String} text
* @param {Number} x
* @param {Number} y
* @param {Function} callback
* @param {Object} normalState
* @param {Object} hoverState
* @param {Object} pressedState
*/
button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
curState = 0,
stateOptions,
stateStyle,
normalStyle,
hoverStyle,
pressedStyle,
disabledStyle,
verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
// Normal state - prepare the attributes
normalState = merge({
'stroke-width': 1,
stroke: '#CCCCCC',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#FEFEFE'],
[1, '#F6F6F6']
]
},
r: 2,
padding: 5,
style: {
color: 'black'
}
}, normalState);
normalStyle = normalState.style;
delete normalState.style;
// Hover state
hoverState = merge(normalState, {
stroke: '#68A',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#FFF'],
[1, '#ACF']
]
}
}, hoverState);
hoverStyle = hoverState.style;
delete hoverState.style;
// Pressed state
pressedState = merge(normalState, {
stroke: '#68A',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#9BD'],
[1, '#CDF']
]
}
}, pressedState);
pressedStyle = pressedState.style;
delete pressedState.style;
// Disabled state
disabledState = merge(normalState, {
style: {
color: '#CCC'
}
}, disabledState);
disabledStyle = disabledState.style;
delete disabledState.style;
// Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () {
if (curState !== 3) {
label.attr(hoverState)
.css(hoverStyle);
}
});
addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () {
if (curState !== 3) {
stateOptions = [normalState, hoverState, pressedState][curState];
stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
label.attr(stateOptions)
.css(stateStyle);
}
});
label.setState = function (state) {
label.state = curState = state;
if (!state) {
label.attr(normalState)
.css(normalStyle);
} else if (state === 2) {
label.attr(pressedState)
.css(pressedStyle);
} else if (state === 3) {
label.attr(disabledState)
.css(disabledStyle);
}
};
return label
.on('click', function () {
if (curState !== 3) {
callback.call(label);
}
})
.attr(normalState)
.css(extend({ cursor: 'default' }, normalStyle));
},
/**
* Make a straight line crisper by not spilling out to neighbour pixels
* @param {Array} points
* @param {Number} width
*/
crispLine: function (points, width) {
// points format: [M, 0, 0, L, 100, 0]
// normalize to a crisp line
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave the same.
points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
}
return points;
},
/**
* Draw a path
* @param {Array} path An SVG path in array form
*/
path: function (path) {
var attr = {
fill: NONE
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
return this.createElement('path').attr(attr);
},
/**
* Draw and return an SVG circle
* @param {Number} x The x position
* @param {Number} y The y position
* @param {Number} r The radius
*/
circle: function (x, y, r) {
var attr = isObject(x) ?
x :
{
x: x,
y: y,
r: r
},
wrapper = this.createElement('circle');
wrapper.xSetter = function (value) {
this.element.setAttribute('cx', value);
};
wrapper.ySetter = function (value) {
this.element.setAttribute('cy', value);
};
return wrapper.attr(attr);
},
/**
* Draw and return an arc
* @param {Number} x X position
* @param {Number} y Y position
* @param {Number} r Radius
* @param {Number} innerR Inner radius like used in donut charts
* @param {Number} start Starting angle
* @param {Number} end Ending angle
*/
arc: function (x, y, r, innerR, start, end) {
var arc;
if (isObject(x)) {
y = x.y;
r = x.r;
innerR = x.innerR;
start = x.start;
end = x.end;
x = x.x;
}
// Arcs are defined as symbols for the ability to set
// attributes in attr and animate
arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
innerR: innerR || 0,
start: start || 0,
end: end || 0
});
arc.r = r; // #959
return arc;
},
/**
* Draw and return a rectangle
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Number} width
* @param {Number} height
* @param {Number} r Border corner radius
* @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
*/
rect: function (x, y, width, height, r, strokeWidth) {
r = isObject(x) ? x.r : r;
var wrapper = this.createElement('rect'),
attribs = isObject(x) ? x : x === UNDEFINED ? {} : {
x: x,
y: y,
width: mathMax(width, 0),
height: mathMax(height, 0)
};
if (strokeWidth !== UNDEFINED) {
attribs.strokeWidth = strokeWidth;
attribs = wrapper.crisp(attribs);
}
if (r) {
attribs.r = r;
}
wrapper.rSetter = function (value) {
attr(this.element, {
rx: value,
ry: value
});
};
return wrapper.attr(attribs);
},
/**
* Resize the box and re-align all aligned elements
* @param {Object} width
* @param {Object} height
* @param {Boolean} animate
*
*/
setSize: function (width, height, animate) {
var renderer = this,
alignedObjects = renderer.alignedObjects,
i = alignedObjects.length;
renderer.width = width;
renderer.height = height;
renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
width: width,
height: height
});
while (i--) {
alignedObjects[i].align();
}
},
/**
* Create a group
* @param {String} name The group will be given a class name of 'highcharts-{name}'.
* This can be used for styling and scripting.
*/
g: function (name) {
var elem = this.createElement('g');
return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
},
/**
* Display an image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function (src, x, y, width, height) {
var attribs = {
preserveAspectRatio: NONE
},
elemWrapper;
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// set the href in the xlink namespace
if (elemWrapper.element.setAttributeNS) {
elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
'href', src);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under, requries regex shim to fix later
elemWrapper.element.setAttribute('hc-svg-href', src);
}
return elemWrapper;
},
/**
* Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
*
* @param {Object} symbol
* @param {Object} x
* @param {Object} y
* @param {Object} radius
* @param {Object} options
*/
symbol: function (symbol, x, y, width, height, options) {
var obj,
// get the symbol definition function
symbolFn = this.symbols[symbol],
// check if there's a path defined for this symbol
path = symbolFn && symbolFn(
mathRound(x),
mathRound(y),
width,
height,
options
),
imageElement,
imageRegex = /^url\((.*?)\)$/,
imageSrc,
imageSize,
centerImage;
if (path) {
obj = this.path(path);
// expando properties for use in animate and attr
extend(obj, {
symbolName: symbol,
x: x,
y: y,
width: width,
height: height
});
if (options) {
extend(obj, options);
}
// image symbols
} else if (imageRegex.test(symbol)) {
// On image load, set the size and position
centerImage = function (img, size) {
if (img.element) { // it may be destroyed in the meantime (#1390)
img.attr({
width: size[0],
height: size[1]
});
if (!img.alignByTranslate) { // #185
img.translate(
mathRound((width - size[0]) / 2), // #1378
mathRound((height - size[1]) / 2)
);
}
}
};
imageSrc = symbol.match(imageRegex)[1];
imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]);
// Ireate the image synchronously, add attribs async
obj = this.image(imageSrc)
.attr({
x: x,
y: y
});
obj.isImg = true;
if (imageSize) {
centerImage(obj, imageSize);
} else {
// Initialize image to be 0 size so export will still function if there's no cached sizes.
obj.attr({ width: 0, height: 0 });
// Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
// the created element must be assigned to a variable in order to load (#292).
imageElement = createElement('img', {
onload: function () {
centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
},
src: imageSrc
});
}
}
return obj;
},
/**
* An extendable collection of functions for defining symbol paths.
*/
symbols: {
'circle': function (x, y, w, h) {
var cpw = 0.166 * w;
return [
M, x + w / 2, y,
'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
'Z'
];
},
'square': function (x, y, w, h) {
return [
M, x, y,
L, x + w, y,
x + w, y + h,
x, y + h,
'Z'
];
},
'triangle': function (x, y, w, h) {
return [
M, x + w / 2, y,
L, x + w, y + h,
x, y + h,
'Z'
];
},
'triangle-down': function (x, y, w, h) {
return [
M, x, y,
L, x + w, y,
x + w / 2, y + h,
'Z'
];
},
'diamond': function (x, y, w, h) {
return [
M, x + w / 2, y,
L, x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2,
'Z'
];
},
'arc': function (x, y, w, h, options) {
var start = options.start,
radius = options.r || w || h,
end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
innerRadius = options.innerR,
open = options.open,
cosStart = mathCos(start),
sinStart = mathSin(start),
cosEnd = mathCos(end),
sinEnd = mathSin(end),
longArc = options.end - start < mathPI ? 0 : 1;
return [
M,
x + radius * cosStart,
y + radius * sinStart,
'A', // arcTo
radius, // x radius
radius, // y radius
0, // slanting
longArc, // long or short arc
1, // clockwise
x + radius * cosEnd,
y + radius * sinEnd,
open ? M : L,
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A', // arcTo
innerRadius, // x radius
innerRadius, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
x + innerRadius * cosStart,
y + innerRadius * sinStart,
open ? '' : 'Z' // close
];
},
/**
* Callout shape used for default tooltips, also used for rounded rectangles in VML
*/
callout: function (x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = mathMin((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path,
normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors;
x += normalizer;
y += normalizer;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-right corner
];
if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
} else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
path.splice(33, 3,
'L', x, anchorY + halfDistance,
x - arrowLength, anchorY,
x, anchorY - halfDistance,
x, y + r
);
} else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
path.splice(23, 3,
'L', anchorX + halfDistance, y + h,
anchorX, y + h + arrowLength,
anchorX - halfDistance, y + h,
x + r, y + h
);
} else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
path.splice(3, 3,
'L', anchorX - halfDistance, y,
anchorX, y - arrowLength,
anchorX + halfDistance, y,
w - r, y
);
}
return path;
}
},
/**
* Define a clipping rectangle
* @param {String} id
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function (x, y, width, height) {
var wrapper,
id = PREFIX + idCounter++,
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
wrapper.count = 0;
return wrapper;
},
/**
* Add text to the SVG object
* @param {String} str
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Boolean} useHTML Use HTML to render the text
*/
text: function (str, x, y, useHTML) {
// declare variables
var renderer = this,
fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
wrapper,
attr = {};
if (useHTML && !renderer.forExport) {
return renderer.html(str, x, y);
}
attr.x = Math.round(x || 0); // X is always needed for line-wrap logic
if (y) {
attr.y = Math.round(y);
}
if (str || str === 0) {
attr.text = str;
}
wrapper = renderer.createElement('text')
.attr(attr);
// Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
if (fakeSVG) {
wrapper.css({
position: ABSOLUTE
});
}
if (!useHTML) {
wrapper.xSetter = function (value, key, element) {
var tspans = element.getElementsByTagName('tspan'),
tspan,
parentVal = element.getAttribute(key),
i;
for (i = 0; i < tspans.length; i++) {
tspan = tspans[i];
// If the x values are equal, the tspan represents a linebreak
if (tspan.getAttribute(key) === parentVal) {
tspan.setAttribute(key, value);
}
}
element.setAttribute(key, value);
};
}
return wrapper;
},
/**
* Utility to return the baseline offset and total line height from the font size
*/
fontMetrics: function (fontSize, elem) {
fontSize = fontSize || this.style.fontSize;
if (elem && win.getComputedStyle) {
elem = elem.element || elem; // SVGElement
fontSize = win.getComputedStyle(elem, "").fontSize;
}
fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12;
// Empirical values found by comparing font size and bounding box height.
// Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
var lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2),
baseline = mathRound(lineHeight * 0.8);
return {
h: lineHeight,
b: baseline,
f: fontSize
};
},
/**
* Correct X and Y positioning of a label for rotation (#1764)
*/
rotCorr: function (baseline, rotation, alterY) {
var y = baseline;
if (rotation && alterY) {
y = mathMax(y * mathCos(rotation * deg2rad), 4);
}
return {
x: (-baseline / 3) * mathSin(rotation * deg2rad),
y: y
};
},
/**
* Add a label, a text item that can hold a colored or gradient background
* as well as a border and shadow.
* @param {string} str
* @param {Number} x
* @param {Number} y
* @param {String} shape
* @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
* coordinates it should be pinned to
* @param {Number} anchorY
* @param {Boolean} baseline Whether to position the label relative to the text baseline,
* like renderer.text, or to the upper border of the rectangle.
* @param {String} className Class name for the group
*/
label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
var renderer = this,
wrapper = renderer.g(className),
text = renderer.text('', 0, 0, useHTML)
.attr({
zIndex: 1
}),
//.add(wrapper),
box,
bBox,
alignFactor = 0,
padding = 3,
paddingLeft = 0,
width,
height,
wrapperX,
wrapperY,
crispAdjust = 0,
deferredAttr = {},
baselineOffset,
needsBox;
/**
* This function runs after the label is added to the DOM (when the bounding box is
* available), and after the text of the label is updated to detect the new bounding
* box and reflect it in the border box.
*/
function updateBoxSize() {
var boxX,
boxY,
style = text.element.style;
bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) &&
text.getBBox(); //#3295 && 3514 box failure when string equals 0
wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
wrapper.height = (height || bBox.height || 0) + 2 * padding;
// update the label-scoped y offset
baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b;
if (needsBox) {
// create the border box if it is not already present
if (!box) {
boxX = mathRound(-alignFactor * padding);
boxY = baseline ? -baselineOffset : 0;
wrapper.box = box = shape ?
renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) :
renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
box.attr('fill', NONE).add(wrapper);
}
// apply the box attributes
if (!box.isImg) { // #1630
box.attr(extend({
width: mathRound(wrapper.width),
height: mathRound(wrapper.height)
}, deferredAttr));
}
deferredAttr = null;
}
}
/**
* This function runs after setting text or padding, but only if padding is changed
*/
function updateTextPadding() {
var styles = wrapper.styles,
textAlign = styles && styles.textAlign,
x = paddingLeft + padding * (1 - alignFactor),
y;
// determin y based on the baseline
y = baseline ? 0 : baselineOffset;
// compensate for alignment
if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) {
x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
}
// update if anything changed
if (x !== text.x || y !== text.y) {
text.attr('x', x);
if (y !== UNDEFINED) {
text.attr('y', y);
}
}
// record current values
text.x = x;
text.y = y;
}
/**
* Set a box attribute, or defer it if the box is not yet created
* @param {Object} key
* @param {Object} value
*/
function boxAttr(key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
}
/**
* After the text element is added, get the desired size of the border box
* and add it before the text in the DOM.
*/
wrapper.onAdd = function () {
text.add(wrapper);
wrapper.attr({
text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value
x: x,
y: y
});
if (box && defined(anchorX)) {
wrapper.attr({
anchorX: anchorX,
anchorY: anchorY
});
}
};
/*
* Add specific attribute setters.
*/
// only change local variables
wrapper.widthSetter = function (value) {
width = value;
};
wrapper.heightSetter = function (value) {
height = value;
};
wrapper.paddingSetter = function (value) {
if (defined(value) && value !== padding) {
padding = wrapper.padding = value;
updateTextPadding();
}
};
wrapper.paddingLeftSetter = function (value) {
if (defined(value) && value !== paddingLeft) {
paddingLeft = value;
updateTextPadding();
}
};
// change local variable and prevent setting attribute on the group
wrapper.alignSetter = function (value) {
alignFactor = { left: 0, center: 0.5, right: 1 }[value];
};
// apply these to the box and the text alike
wrapper.textSetter = function (value) {
if (value !== UNDEFINED) {
text.textSetter(value);
}
updateBoxSize();
updateTextPadding();
};
// apply these to the box but not to the text
wrapper['stroke-widthSetter'] = function (value, key) {
if (value) {
needsBox = true;
}
crispAdjust = value % 2 / 2;
boxAttr(key, value);
};
wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) {
if (key === 'fill' && value) {
needsBox = true;
}
boxAttr(key, value);
};
wrapper.anchorXSetter = function (value, key) {
anchorX = value;
boxAttr(key, value + crispAdjust - wrapperX);
};
wrapper.anchorYSetter = function (value, key) {
anchorY = value;
boxAttr(key, value - wrapperY);
};
// rename attributes
wrapper.xSetter = function (value) {
wrapper.x = value; // for animation getter
if (alignFactor) {
value -= alignFactor * ((width || bBox.width) + padding);
}
wrapperX = mathRound(value);
wrapper.attr('translateX', wrapperX);
};
wrapper.ySetter = function (value) {
wrapperY = wrapper.y = mathRound(value);
wrapper.attr('translateY', wrapperY);
};
// Redirect certain methods to either the box or the text
var baseCss = wrapper.css;
return extend(wrapper, {
/**
* Pick up some properties and apply them to the text instead of the wrapper
*/
css: function (styles) {
if (styles) {
var textStyles = {};
styles = merge(styles); // create a copy to avoid altering the original object (#537)
each(wrapper.textProps, function (prop) {
if (styles[prop] !== UNDEFINED) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
}
return baseCss.call(wrapper, styles);
},
/**
* Return the bounding box of the box, not the group
*/
getBBox: function () {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
},
/**
* Apply the shadow to the box
*/
shadow: function (b) {
if (box) {
box.shadow(b);
}
return wrapper;
},
/**
* Destroy and release memory.
*/
destroy: function () {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
}
});
}
}; // end SVGRenderer
// general renderer
Renderer = SVGRenderer;
// extend SvgElement for useHTML option
extend(SVGElement.prototype, {
/**
* Apply CSS to HTML elements. This is used in text within SVG rendering and
* by the VML renderer
*/
htmlCss: function (styles) {
var wrapper = this,
element = wrapper.element,
textWidth = styles && element.tagName === 'SPAN' && styles.width;
if (textWidth) {
delete styles.width;
wrapper.textWidth = textWidth;
wrapper.updateTransform();
}
if (styles && styles.textOverflow === 'ellipsis') {
styles.whiteSpace = 'nowrap';
styles.overflow = 'hidden';
}
wrapper.styles = extend(wrapper.styles, styles);
css(wrapper.element, styles);
return wrapper;
},
/**
* VML and useHTML method for calculating the bounding box based on offsets
* @param {Boolean} refresh Whether to force a fresh value from the DOM or to
* use the cached value
*
* @return {Object} A hash containing values for x, y, width and height
*/
htmlGetBBox: function () {
var wrapper = this,
element = wrapper.element;
// faking getBBox in exported SVG in legacy IE
// faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
if (element.nodeName === 'text') {
element.style.position = ABSOLUTE;
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
},
/**
* VML override private method to update elements based on internal
* properties based on SVG transform
*/
htmlUpdateTransform: function () {
// aligning non added elements is expensive
if (!this.added) {
this.alignOnAdd = true;
return;
}
var wrapper = this,
renderer = wrapper.renderer,
elem = wrapper.element,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
x = wrapper.x || 0,
y = wrapper.y || 0,
align = wrapper.textAlign || 'left',
alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
shadows = wrapper.shadows,
styles = wrapper.styles;
// apply translate
css(elem, {
marginLeft: translateX,
marginTop: translateY
});
if (shadows) { // used in labels/tooltip
each(shadows, function (shadow) {
css(shadow, {
marginLeft: translateX + 1,
marginTop: translateY + 1
});
});
}
// apply inversion
if (wrapper.inverted) { // wrapper is a group
each(elem.childNodes, function (child) {
renderer.invertChild(child, elem);
});
}
if (elem.tagName === 'SPAN') {
var width,
rotation = wrapper.rotation,
baseline,
textWidth = pInt(wrapper.textWidth),
currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(',');
if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
baseline = renderer.fontMetrics(elem.style.fontSize).b;
// Renderer specific handling of span rotation
if (defined(rotation)) {
wrapper.setSpanRotation(rotation, alignCorrection, baseline);
}
width = pick(wrapper.elemWidth, elem.offsetWidth);
// Update textWidth
if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
css(elem, {
width: textWidth + PX,
display: 'block',
whiteSpace: (styles && styles.whiteSpace) || 'normal' // #3331
});
width = textWidth;
}
wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align);
}
// apply position with correction
css(elem, {
left: (x + (wrapper.xCorr || 0)) + PX,
top: (y + (wrapper.yCorr || 0)) + PX
});
// force reflow in webkit to apply the left and top on useHTML element (#1249)
if (isWebKit) {
baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose
}
// record current text transform
wrapper.cTT = currentTextTransform;
}
},
/**
* Set the rotation of an individual HTML span
*/
setSpanRotation: function (rotation, alignCorrection, baseline) {
var rotationStyle = {},
cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px';
css(this.element, rotationStyle);
},
/**
* Get the correction in X and Y positioning as the element is rotated.
*/
getSpanCorrection: function (width, baseline, alignCorrection) {
this.xCorr = -width * alignCorrection;
this.yCorr = -baseline;
}
});
// Extend SvgRenderer for useHTML option.
extend(SVGRenderer.prototype, {
/**
* Create HTML text node. This is used by the VML renderer as well as the SVG
* renderer through the useHTML option.
*
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
html: function (str, x, y) {
var wrapper = this.createElement('span'),
element = wrapper.element,
renderer = wrapper.renderer;
// Text setter
wrapper.textSetter = function (value) {
if (value !== element.innerHTML) {
delete this.bBox;
}
element.innerHTML = this.textStr = value;
};
// Various setters which rely on update transform
wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) {
if (key === 'align') {
key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
}
wrapper[key] = value;
wrapper.htmlUpdateTransform();
};
// Set the default attributes
wrapper.attr({
text: str,
x: mathRound(x),
y: mathRound(y)
})
.css({
position: ABSOLUTE,
fontFamily: this.style.fontFamily,
fontSize: this.style.fontSize
});
// Keep the whiteSpace style outside the wrapper.styles collection
element.style.whiteSpace = 'nowrap';
// Use the HTML specific .css method
wrapper.css = wrapper.htmlCss;
// This is specific for HTML within SVG
if (renderer.isSVG) {
wrapper.add = function (svgGroupWrapper) {
var htmlGroup,
container = renderer.box.parentNode,
parentGroup,
parents = [];
this.parentGroup = svgGroupWrapper;
// Create a mock group to hold the HTML elements
if (svgGroupWrapper) {
htmlGroup = svgGroupWrapper.div;
if (!htmlGroup) {
// Read the parent chain into an array and read from top down
parentGroup = svgGroupWrapper;
while (parentGroup) {
parents.push(parentGroup);
// Move up to the next parent group
parentGroup = parentGroup.parentGroup;
}
// Ensure dynamically updating position when any parent is translated
each(parents.reverse(), function (parentGroup) {
var htmlGroupStyle;
// Create a HTML div and append it to the parent div to emulate
// the SVG group structure
htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
className: attr(parentGroup.element, 'class')
}, {
position: ABSOLUTE,
left: (parentGroup.translateX || 0) + PX,
top: (parentGroup.translateY || 0) + PX
}, htmlGroup || container); // the top group is appended to container
// Shortcut
htmlGroupStyle = htmlGroup.style;
// Set listeners to update the HTML div's position whenever the SVG group
// position is changed
extend(parentGroup, {
translateXSetter: function (value, key) {
htmlGroupStyle.left = value + PX;
parentGroup[key] = value;
parentGroup.doTransform = true;
},
translateYSetter: function (value, key) {
htmlGroupStyle.top = value + PX;
parentGroup[key] = value;
parentGroup.doTransform = true;
},
visibilitySetter: function (value, key) {
htmlGroupStyle[key] = value;
}
});
});
}
} else {
htmlGroup = container;
}
htmlGroup.appendChild(element);
// Shared with VML:
wrapper.added = true;
if (wrapper.alignOnAdd) {
wrapper.htmlUpdateTransform();
}
return wrapper;
};
}
return wrapper;
}
});
/* ****************************************************************************
* *
* START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
* *
* For applications and websites that don't need IE support, like platform *
* targeted mobile apps and web apps, this code can be removed. *
* *
*****************************************************************************/
/**
* @constructor
*/
var VMLRenderer, VMLElement;
if (!hasSVG && !useCanVG) {
/**
* The VML element wrapper.
*/
VMLElement = {
/**
* Initialize a new VML element wrapper. It builds the markup as a string
* to minimize DOM traffic.
* @param {Object} renderer
* @param {Object} nodeName
*/
init: function (renderer, nodeName) {
var wrapper = this,
markup = ['<', nodeName, ' filled="f" stroked="f"'],
style = ['position: ', ABSOLUTE, ';'],
isDiv = nodeName === DIV;
// divs and shapes need size
if (nodeName === 'shape' || isDiv) {
style.push('left:0;top:0;width:1px;height:1px;');
}
style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
markup.push(' style="', style.join(''), '"/>');
// create element with default attributes and style
if (nodeName) {
markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
markup.join('')
: renderer.prepVML(markup);
wrapper.element = createElement(markup);
}
wrapper.renderer = renderer;
},
/**
* Add the node to the given parent
* @param {Object} parent
*/
add: function (parent) {
var wrapper = this,
renderer = wrapper.renderer,
element = wrapper.element,
box = renderer.box,
inverted = parent && parent.inverted,
// get the parent node
parentNode = parent ?
parent.element || parent :
box;
// if the parent group is inverted, apply inversion on all children
if (inverted) { // only on groups
renderer.invertChild(element, parentNode);
}
// append it
parentNode.appendChild(element);
// align text after adding to be able to read offset
wrapper.added = true;
if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
wrapper.updateTransform();
}
// fire an event for internal hooks
if (wrapper.onAdd) {
wrapper.onAdd();
}
return wrapper;
},
/**
* VML always uses htmlUpdateTransform
*/
updateTransform: SVGElement.prototype.htmlUpdateTransform,
/**
* Set the rotation of a span with oldIE's filter
*/
setSpanRotation: function () {
// Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
// but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
// has support for CSS3 transform. The getBBox method also needs to be updated
// to compensate for the rotation, like it currently does for SVG.
// Test case: http://jsfiddle.net/highcharts/Ybt44/
var rotation = this.rotation,
costheta = mathCos(rotation * deg2rad),
sintheta = mathSin(rotation * deg2rad);
css(this.element, {
filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
', sizingMethod=\'auto expand\')'].join('') : NONE
});
},
/**
* Get the positioning correction for the span after rotating.
*/
getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) {
var costheta = rotation ? mathCos(rotation * deg2rad) : 1,
sintheta = rotation ? mathSin(rotation * deg2rad) : 0,
height = pick(this.elemHeight, this.element.offsetHeight),
quad,
nonLeft = align && align !== 'left';
// correct x and y
this.xCorr = costheta < 0 && -width;
this.yCorr = sintheta < 0 && -height;
// correct for baseline and corners spilling out after rotation
quad = costheta * sintheta < 0;
this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
// correct for the length/height of the text
if (nonLeft) {
this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
if (rotation) {
this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
}
css(this.element, {
textAlign: align
});
}
},
/**
* Converts a subset of an SVG path definition to its VML counterpart. Takes an array
* as the parameter and returns a string.
*/
pathToVML: function (value) {
// convert paths
var i = value.length,
path = [];
while (i--) {
// Multiply by 10 to allow subpixel precision.
// Substracting half a pixel seems to make the coordinates
// align with SVG, but this hasn't been tested thoroughly
if (isNumber(value[i])) {
path[i] = mathRound(value[i] * 10) - 5;
} else if (value[i] === 'Z') { // close the path
path[i] = 'x';
} else {
path[i] = value[i];
// When the start X and end X coordinates of an arc are too close,
// they are rounded to the same value above. In this case, substract or
// add 1 from the end X and Y positions. #186, #760, #1371, #1410.
if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
// Start and end X
if (path[i + 5] === path[i + 7]) {
path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1;
}
// Start and end Y
if (path[i + 6] === path[i + 8]) {
path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1;
}
}
}
}
// Loop up again to handle path shortcuts (#2132)
/*while (i++ < path.length) {
if (path[i] === 'H') { // horizontal line to
path[i] = 'L';
path.splice(i + 2, 0, path[i - 1]);
} else if (path[i] === 'V') { // vertical line to
path[i] = 'L';
path.splice(i + 1, 0, path[i - 2]);
}
}*/
return path.join(' ') || 'x';
},
/**
* Set the element's clipping to a predefined rectangle
*
* @param {String} id The id of the clip rectangle
*/
clip: function (clipRect) {
var wrapper = this,
clipMembers,
cssRet;
if (clipRect) {
clipMembers = clipRect.members;
erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
clipMembers.push(wrapper);
wrapper.destroyClip = function () {
erase(clipMembers, wrapper);
};
cssRet = clipRect.getCSS(wrapper);
} else {
if (wrapper.destroyClip) {
wrapper.destroyClip();
}
cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
}
return wrapper.css(cssRet);
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: SVGElement.prototype.htmlCss,
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function (element) {
// discardElement will detach the node from its parent before attaching it
// to the garbage bin. Therefore it is important that the node is attached and have parent.
if (element.parentNode) {
discardElement(element);
}
},
/**
* Extend element.destroy by removing it from the clip members array
*/
destroy: function () {
if (this.destroyClip) {
this.destroyClip();
}
return SVGElement.prototype.destroy.apply(this);
},
/**
* Add an event listener. VML override for normalizing event parameters.
* @param {String} eventType
* @param {Function} handler
*/
on: function (eventType, handler) {
// simplest possible event model for internal use
this.element['on' + eventType] = function () {
var evt = win.event;
evt.target = evt.srcElement;
handler(evt);
};
return this;
},
/**
* In stacked columns, cut off the shadows so that they don't overlap
*/
cutOffPath: function (path, length) {
var len;
path = path.split(/[ ,]/);
len = path.length;
if (len === 9 || len === 11) {
path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
}
return path.join(' ');
},
/**
* Apply a drop shadow by copying elements and giving them different strokes
* @param {Boolean|Object} shadowOptions
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
element = this.element,
renderer = this.renderer,
shadow,
elemStyle = element.style,
markup,
path = element.path,
strokeWidth,
modifiedPath,
shadowWidth,
shadowElementOpacity;
// some times empty paths are not strings
if (path && typeof path.value !== 'string') {
path = 'x';
}
modifiedPath = path;
if (shadowOptions) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
for (i = 1; i <= 3; i++) {
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
// Cut off shadows for stacked column items
if (cutOff) {
modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
}
markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
'" filled="false" path="', modifiedPath,
'" coordsize="10 10" style="', element.style.cssText, '" />'];
shadow = createElement(renderer.prepVML(markup),
null, {
left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
}
);
if (cutOff) {
shadow.cutOff = strokeWidth + 1;
}
// apply the opacity
markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
createElement(renderer.prepVML(markup), null, null, shadow);
// insert it
if (group) {
group.element.appendChild(shadow);
} else {
element.parentNode.insertBefore(shadow, element);
}
// record it
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
},
updateShadows: noop, // Used in SVG only
setAttr: function (key, value) {
if (docMode8) { // IE8 setAttribute bug
this.element[key] = value;
} else {
this.element.setAttribute(key, value);
}
},
classSetter: function (value) {
// IE8 Standards mode has problems retrieving the className unless set like this
this.element.className = value;
},
dashstyleSetter: function (value, key, element) {
var strokeElem = element.getElementsByTagName('stroke')[0] ||
createElement(this.renderer.prepVML(['<stroke/>']), null, null, element);
strokeElem[key] = value || 'solid';
this[key] = value; /* because changing stroke-width will change the dash length
and cause an epileptic effect */
},
dSetter: function (value, key, element) {
var i,
shadows = this.shadows;
value = value || [];
this.d = value.join && value.join(' '); // used in getter for animation
element.path = value = this.pathToVML(value);
// update shadows
if (shadows) {
i = shadows.length;
while (i--) {
shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
}
}
this.setAttr(key, value);
},
fillSetter: function (value, key, element) {
var nodeName = element.nodeName;
if (nodeName === 'SPAN') { // text color
element.style.color = value;
} else if (nodeName !== 'IMG') { // #1336
element.filled = value !== NONE;
this.setAttr('fillcolor', this.renderer.color(value, element, key, this));
}
},
opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts
rotationSetter: function (value, key, element) {
var style = element.style;
this[key] = style[key] = value; // style is for #1873
// Correction for the 1x1 size of the shape container. Used in gauge needles.
style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
style.top = mathRound(mathCos(value * deg2rad)) + PX;
},
strokeSetter: function (value, key, element) {
this.setAttr('strokecolor', this.renderer.color(value, element, key));
},
'stroke-widthSetter': function (value, key, element) {
element.stroked = !!value; // VML "stroked" attribute
this[key] = value; // used in getter, issue #113
if (isNumber(value)) {
value += PX;
}
this.setAttr('strokeweight', value);
},
titleSetter: function (value, key) {
this.setAttr(key, value);
},
visibilitySetter: function (value, key, element) {
// Handle inherited visibility
if (value === 'inherit') {
value = VISIBLE;
}
// Let the shadow follow the main element
if (this.shadows) {
each(this.shadows, function (shadow) {
shadow.style[key] = value;
});
}
// Instead of toggling the visibility CSS property, move the div out of the viewport.
// This works around #61 and #586
if (element.nodeName === 'DIV') {
value = value === HIDDEN ? '-999em' : 0;
// In order to redraw, IE7 needs the div to be visible when tucked away
// outside the viewport. So the visibility is actually opposite of
// the expected value. This applies to the tooltip only.
if (!docMode8) {
element.style[key] = value ? VISIBLE : HIDDEN;
}
key = 'top';
}
element.style[key] = value;
},
xSetter: function (value, key, element) {
this[key] = value; // used in getter
if (key === 'x') {
key = 'left';
} else if (key === 'y') {
key = 'top';
}/* else {
value = mathMax(0, value); // don't set width or height below zero (#311)
}*/
// clipping rectangle special
if (this.updateClipping) {
this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
this.updateClipping();
} else {
// normal
element.style[key] = value;
}
},
zIndexSetter: function (value, key, element) {
element.style[key] = value;
}
};
Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement);
// Some shared setters
VMLElement.prototype.ySetter =
VMLElement.prototype.widthSetter =
VMLElement.prototype.heightSetter =
VMLElement.prototype.xSetter;
/**
* The VML renderer
*/
var VMLRendererExtension = { // inherit SVGRenderer
Element: VMLElement,
isIE8: userAgent.indexOf('MSIE 8.0') > -1,
/**
* Initialize the VMLRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
*/
init: function (container, width, height, style) {
var renderer = this,
boxWrapper,
box,
css;
renderer.alignedObjects = [];
boxWrapper = renderer.createElement(DIV)
.css(extend(this.getStyle(style), { position: RELATIVE}));
box = boxWrapper.element;
container.appendChild(boxWrapper.element);
// generate the containing box
renderer.isVML = true;
renderer.box = box;
renderer.boxWrapper = boxWrapper;
renderer.cache = {};
renderer.setSize(width, height, false);
// The only way to make IE6 and IE7 print is to use a global namespace. However,
// with IE8 the only way to make the dynamic shapes visible in screen and print mode
// seems to be to add the xmlns attribute and the behaviour style inline.
if (!doc.namespaces.hcv) {
doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
// Setup default CSS (#2153, #2368, #2384)
css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
'{ behavior:url(#default#VML); display: inline-block; } ';
try {
doc.createStyleSheet().cssText = css;
} catch (e) {
doc.styleSheets[0].cssText += css;
}
}
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none
*/
isHidden: function () {
return !this.box.offsetWidth;
},
/**
* Define a clipping rectangle. In VML it is accomplished by storing the values
* for setting the CSS style to all associated members.
*
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function (x, y, width, height) {
// create a dummy element
var clipRect = this.createElement(),
isObj = isObject(x);
// mimic a rectangle with its style object for automatic updating in attr
return extend(clipRect, {
members: [],
count: 0,
left: (isObj ? x.x : x) + 1,
top: (isObj ? x.y : y) + 1,
width: (isObj ? x.width : width) - 1,
height: (isObj ? x.height : height) - 1,
getCSS: function (wrapper) {
var element = wrapper.element,
nodeName = element.nodeName,
isShape = nodeName === 'shape',
inverted = wrapper.inverted,
rect = this,
top = rect.top - (isShape ? element.offsetTop : 0),
left = rect.left,
right = left + rect.width,
bottom = top + rect.height,
ret = {
clip: 'rect(' +
mathRound(inverted ? left : top) + 'px,' +
mathRound(inverted ? bottom : right) + 'px,' +
mathRound(inverted ? right : bottom) + 'px,' +
mathRound(inverted ? top : left) + 'px)'
};
// issue 74 workaround
if (!inverted && docMode8 && nodeName === 'DIV') {
extend(ret, {
width: right + PX,
height: bottom + PX
});
}
return ret;
},
// used in attr and animation to update the clipping of all members
updateClipping: function () {
each(clipRect.members, function (member) {
if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do.
member.css(clipRect.getCSS(member));
}
});
}
});
},
/**
* Take a color and return it if it's a string, make it a gradient if it's a
* gradient configuration object, and apply opacity.
*
* @param {Object} color The color or config object
*/
color: function (color, elem, prop, wrapper) {
var renderer = this,
colorObject,
regexRgba = /^rgba/,
markup,
fillType,
ret = NONE;
// Check for linear or radial gradient
if (color && color.linearGradient) {
fillType = 'gradient';
} else if (color && color.radialGradient) {
fillType = 'pattern';
}
if (fillType) {
var stopColor,
stopOpacity,
gradient = color.linearGradient || color.radialGradient,
x1,
y1,
x2,
y2,
opacity1,
opacity2,
color1,
color2,
fillAttr = '',
stops = color.stops,
firstStop,
lastStop,
colors = [],
addFillNode = function () {
// Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
// are reversed.
markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
'" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
createElement(renderer.prepVML(markup), null, null, elem);
};
// Extend from 0 to 1
firstStop = stops[0];
lastStop = stops[stops.length - 1];
if (firstStop[0] > 0) {
stops.unshift([
0,
firstStop[1]
]);
}
if (lastStop[0] < 1) {
stops.push([
1,
lastStop[1]
]);
}
// Compute the stops
each(stops, function (stop, i) {
if (regexRgba.test(stop[1])) {
colorObject = Color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
// Build the color attribute
colors.push((stop[0] * 100) + '% ' + stopColor);
// Only start and end opacities are allowed, so we use the first and the last
if (!i) {
opacity1 = stopOpacity;
color2 = stopColor;
} else {
opacity2 = stopOpacity;
color1 = stopColor;
}
});
// Apply the gradient to fills only.
if (prop === 'fill') {
// Handle linear gradient angle
if (fillType === 'gradient') {
x1 = gradient.x1 || gradient[0] || 0;
y1 = gradient.y1 || gradient[1] || 0;
x2 = gradient.x2 || gradient[2] || 0;
y2 = gradient.y2 || gradient[3] || 0;
fillAttr = 'angle="' + (90 - math.atan(
(y2 - y1) / // y vector
(x2 - x1) // x vector
) * 180 / mathPI) + '"';
addFillNode();
// Radial (circular) gradient
} else {
var r = gradient.r,
sizex = r * 2,
sizey = r * 2,
cx = gradient.cx,
cy = gradient.cy,
radialReference = elem.radialReference,
bBox,
applyRadialGradient = function () {
if (radialReference) {
bBox = wrapper.getBBox();
cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
sizex *= radialReference[2] / bBox.width;
sizey *= radialReference[2] / bBox.height;
}
fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
'size="' + sizex + ',' + sizey + '" ' +
'origin="0.5,0.5" ' +
'position="' + cx + ',' + cy + '" ' +
'color2="' + color2 + '" ';
addFillNode();
};
// Apply radial gradient
if (wrapper.added) {
applyRadialGradient();
} else {
// We need to know the bounding box to get the size and position right
wrapper.onAdd = applyRadialGradient;
}
// The fill element's color attribute is broken in IE8 standards mode, so we
// need to set the parent shape's fillcolor attribute instead.
ret = color1;
}
// Gradients are not supported for VML stroke, return the first color. #722.
} else {
ret = stopColor;
}
// if the color is an rgba color, split it and add a fill node
// to hold the opacity component
} else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
colorObject = Color(color);
markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
createElement(this.prepVML(markup), null, null, elem);
ret = colorObject.get('rgb');
} else {
var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
if (propNodes.length) {
propNodes[0].opacity = 1;
propNodes[0].type = 'solid';
}
ret = color;
}
return ret;
},
/**
* Take a VML string and prepare it for either IE8 or IE6/IE7.
* @param {Array} markup A string array of the VML markup to prepare
*/
prepVML: function (markup) {
var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
isIE8 = this.isIE8;
markup = markup.join('');
if (isIE8) { // add xmlns and style inline
markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
if (markup.indexOf('style="') === -1) {
markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
} else {
markup = markup.replace('style="', 'style="' + vmlStyle);
}
} else { // add namespace
markup = markup.replace('<', '<hcv:');
}
return markup;
},
/**
* Create rotated and aligned text
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
text: SVGRenderer.prototype.html,
/**
* Create and return a path element
* @param {Array} path
*/
path: function (path) {
var attr = {
// subpixel precision down to 0.1 (width and height = 1px)
coordsize: '10 10'
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
// create the shape
return this.createElement('shape').attr(attr);
},
/**
* Create and return a circle element. In VML circles are implemented as
* shapes, which is faster than v:oval
* @param {Number} x
* @param {Number} y
* @param {Number} r
*/
circle: function (x, y, r) {
var circle = this.symbol('circle');
if (isObject(x)) {
r = x.r;
y = x.y;
x = x.x;
}
circle.isCircle = true; // Causes x and y to mean center (#1682)
circle.r = r;
return circle.attr({ x: x, y: y });
},
/**
* Create a group using an outer div and an inner v:group to allow rotating
* and flipping. A simple v:group would have problems with positioning
* child HTML elements and CSS clip.
*
* @param {String} name The name of the group
*/
g: function (name) {
var wrapper,
attribs;
// set the class name
if (name) {
attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
}
// the div to hold HTML and clipping
wrapper = this.createElement(DIV).attr(attribs);
return wrapper;
},
/**
* VML override to create a regular HTML image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function (src, x, y, width, height) {
var obj = this.createElement('img')
.attr({ src: src });
if (arguments.length > 1) {
obj.attr({
x: x,
y: y,
width: width,
height: height
});
}
return obj;
},
/**
* For rectangles, VML uses a shape for rect to overcome bugs and rotation problems
*/
createElement: function (nodeName) {
return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName);
},
/**
* In the VML renderer, each child of an inverted div (group) is inverted
* @param {Object} element
* @param {Object} parentNode
*/
invertChild: function (element, parentNode) {
var ren = this,
parentStyle = parentNode.style,
imgStyle = element.tagName === 'IMG' && element.style; // #1111
css(element, {
flip: 'x',
left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1),
top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1),
rotation: -90
});
// Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806.
each(element.childNodes, function (child) {
ren.invertChild(child, element);
});
},
/**
* Symbol definitions that override the parent SVG renderer's symbols
*
*/
symbols: {
// VML specific arc function
arc: function (x, y, w, h, options) {
var start = options.start,
end = options.end,
radius = options.r || w || h,
innerRadius = options.innerR,
cosStart = mathCos(start),
sinStart = mathSin(start),
cosEnd = mathCos(end),
sinEnd = mathSin(end),
ret;
if (end - start === 0) { // no angle, don't show it.
return ['x'];
}
ret = [
'wa', // clockwise arc to
x - radius, // left
y - radius, // top
x + radius, // right
y + radius, // bottom
x + radius * cosStart, // start x
y + radius * sinStart, // start y
x + radius * cosEnd, // end x
y + radius * sinEnd // end y
];
if (options.open && !innerRadius) {
ret.push(
'e',
M,
x,// - innerRadius,
y// - innerRadius
);
}
ret.push(
'at', // anti clockwise arc to
x - innerRadius, // left
y - innerRadius, // top
x + innerRadius, // right
y + innerRadius, // bottom
x + innerRadius * cosEnd, // start x
y + innerRadius * sinEnd, // start y
x + innerRadius * cosStart, // end x
y + innerRadius * sinStart, // end y
'x', // finish path
'e' // close
);
ret.isArc = true;
return ret;
},
// Add circle symbol path. This performs significantly faster than v:oval.
circle: function (x, y, w, h, wrapper) {
if (wrapper) {
w = h = 2 * wrapper.r;
}
// Center correction, #1682
if (wrapper && wrapper.isCircle) {
x -= w / 2;
y -= h / 2;
}
// Return the path
return [
'wa', // clockwisearcto
x, // left
y, // top
x + w, // right
y + h, // bottom
x + w, // start x
y + h / 2, // start y
x + w, // end x
y + h / 2, // end y
//'x', // finish path
'e' // close
];
},
/**
* Add rectangle symbol path which eases rotation and omits arcsize problems
* compared to the built-in VML roundrect shape. When borders are not rounded,
* use the simpler square path, else use the callout path without the arrow.
*/
rect: function (x, y, w, h, options) {
return SVGRenderer.prototype.symbols[
!defined(options) || !options.r ? 'square' : 'callout'
].call(0, x, y, w, h, options);
}
}
};
Highcharts.VMLRenderer = VMLRenderer = function () {
this.init.apply(this, arguments);
};
VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
// general renderer
Renderer = VMLRenderer;
}
// This method is used with exporting in old IE, when emulating SVG (see #2314)
SVGRenderer.prototype.measureSpanWidth = function (text, styles) {
var measuringSpan = doc.createElement('span'),
offsetWidth,
textNode = doc.createTextNode(text);
measuringSpan.appendChild(textNode);
css(measuringSpan, styles);
this.box.appendChild(measuringSpan);
offsetWidth = measuringSpan.offsetWidth;
discardElement(measuringSpan); // #2463
return offsetWidth;
};
/* ****************************************************************************
* *
* END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
* *
*****************************************************************************/
/* ****************************************************************************
* *
* START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
* TARGETING THAT SYSTEM. *
* *
*****************************************************************************/
var CanVGRenderer,
CanVGController;
if (useCanVG) {
/**
* The CanVGRenderer is empty from start to keep the source footprint small.
* When requested, the CanVGController downloads the rest of the source packaged
* together with the canvg library.
*/
Highcharts.CanVGRenderer = CanVGRenderer = function () {
// Override the global SVG namespace to fake SVG/HTML that accepts CSS
SVG_NS = 'http://www.w3.org/1999/xhtml';
};
/**
* Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
* the implementation from SvgRenderer will not be merged in until first render.
*/
CanVGRenderer.prototype.symbols = {};
/**
* Handles on demand download of canvg rendering support.
*/
CanVGController = (function () {
// List of renderering calls
var deferredRenderCalls = [];
/**
* When downloaded, we are ready to draw deferred charts.
*/
function drawDeferred() {
var callLength = deferredRenderCalls.length,
callIndex;
// Draw all pending render calls
for (callIndex = 0; callIndex < callLength; callIndex++) {
deferredRenderCalls[callIndex]();
}
// Clear the list
deferredRenderCalls = [];
}
return {
push: function (func, scriptLocation) {
// Only get the script once
if (deferredRenderCalls.length === 0) {
getScript(scriptLocation, drawDeferred);
}
// Register render call
deferredRenderCalls.push(func);
}
};
}());
Renderer = CanVGRenderer;
} // end CanVGRenderer
/* ****************************************************************************
* *
* END OF ANDROID < 3 SPECIFIC CODE *
* *
*****************************************************************************/
/**
* The Tick class
*/
function Tick(axis, pos, type, noLabel) {
this.axis = axis;
this.pos = pos;
this.type = type || '';
this.isNew = true;
if (!type && !noLabel) {
this.addLabel();
}
}
Tick.prototype = {
/**
* Write the tick label
*/
addLabel: function () {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
categories = axis.categories,
names = axis.names,
pos = tick.pos,
labelOptions = options.labels,
str,
tickPositions = axis.tickPositions,
isFirst = pos === tickPositions[0],
isLast = pos === tickPositions[tickPositions.length - 1],
value = categories ?
pick(categories[pos], names[pos], pos) :
pos,
label = tick.label,
tickPositionInfo = tickPositions.info,
dateTimeLabelFormat;
// Set the datetime label format. If a higher rank is set for this position, use that. If not,
// use the general format.
if (axis.isDatetimeAxis && tickPositionInfo) {
dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
}
// set properties for access in render method
tick.isFirst = isFirst;
tick.isLast = isLast;
// get the string
str = axis.labelFormatter.call({
axis: axis,
chart: chart,
isFirst: isFirst,
isLast: isLast,
dateTimeLabelFormat: dateTimeLabelFormat,
value: axis.isLog ? correctFloat(lin2log(value)) : value
});
// prepare CSS
//css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
// first call
if (!defined(label)) {
tick.label = label =
defined(str) && labelOptions.enabled ?
chart.renderer.text(
str,
0,
0,
labelOptions.useHTML
)
//.attr(attr)
// without position absolute, IE export sometimes is wrong
.css(merge(labelOptions.style))
.add(axis.labelGroup) :
null;
tick.labelLength = label && label.getBBox().width; // Un-rotated length
tick.rotation = 0; // Base value to detect change for new calls to getBBox
// update
} else if (label) {
label.attr({ text: str });
}
},
/**
* Get the offset height or width of the label
*/
getLabelSize: function () {
return this.label ?
this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
0;
},
/**
* Handle the label overflow by adjusting the labels to the left and right edge, or
* hide them if they collide into the neighbour label.
*/
handleOverflow: function (xy) {
var axis = this.axis,
pxPos = xy.x,
chartWidth = axis.chart.chartWidth,
spacing = axis.chart.spacing,
leftBound = pick(axis.labelLeft, spacing[3]),
rightBound = pick(axis.labelRight, chartWidth - spacing[1]),
label = this.label,
rotation = this.rotation,
factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign],
labelWidth = label.getBBox().width,
slotWidth = axis.slotWidth,
leftPos,
rightPos,
textWidth;
// Check if the label overshoots the chart spacing box. If it does, move it.
// If it now overshoots the slotWidth, add ellipsis.
if (!rotation) {
leftPos = pxPos - factor * labelWidth;
rightPos = pxPos + factor * labelWidth;
if (leftPos < leftBound) {
slotWidth -= leftBound - leftPos;
xy.x = leftBound;
label.attr({ align: 'left' });
} else if (rightPos > rightBound) {
slotWidth -= rightPos - rightBound;
xy.x = rightBound;
label.attr({ align: 'right' });
}
if (labelWidth > slotWidth) {
textWidth = slotWidth;
}
// Add ellipsis to prevent rotated labels to be clipped against the edge of the chart
} else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) {
textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound);
} else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) {
textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad));
}
if (textWidth) {
label.css({
width: textWidth,
textOverflow: 'ellipsis'
});
}
},
/**
* Get the x and y position for ticks and labels
*/
getPosition: function (horiz, pos, tickmarkOffset, old) {
var axis = this.axis,
chart = axis.chart,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
return {
x: horiz ?
axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
y: horiz ?
cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
};
},
/**
* Get the x, y position of the tick label
*/
getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
var axis = this.axis,
transA = axis.transA,
reversed = axis.reversed,
staggerLines = axis.staggerLines,
rotCorr = axis.tickRotCorr || { x: 0, y: 0 },
yOffset = pick(labelOptions.y, rotCorr.y + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))),
line;
x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ?
tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
y = y + yOffset - (tickmarkOffset && !horiz ?
tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
// Correct for staggered labels
if (staggerLines) {
line = (index / (step || 1) % staggerLines);
y += line * (axis.labelOffset / staggerLines);
}
return {
x: x,
y: mathRound(y)
};
},
/**
* Extendible method to return the path of the marker
*/
getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
return renderer.crispLine([
M,
x,
y,
L,
x + (horiz ? 0 : -tickLength),
y + (horiz ? tickLength : 0)
], tickWidth);
},
/**
* Put everything in place
*
* @param index {Number}
* @param old {Boolean} Use old coordinates to prepare an animation into new position
*/
render: function (index, old, opacity) {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
renderer = chart.renderer,
horiz = axis.horiz,
type = tick.type,
label = tick.label,
pos = tick.pos,
labelOptions = options.labels,
gridLine = tick.gridLine,
gridPrefix = type ? type + 'Grid' : 'grid',
tickPrefix = type ? type + 'Tick' : 'tick',
gridLineWidth = options[gridPrefix + 'LineWidth'],
gridLineColor = options[gridPrefix + 'LineColor'],
dashStyle = options[gridPrefix + 'LineDashStyle'],
tickLength = options[tickPrefix + 'Length'],
tickWidth = options[tickPrefix + 'Width'] || 0,
tickColor = options[tickPrefix + 'Color'],
tickPosition = options[tickPrefix + 'Position'],
gridLinePath,
mark = tick.mark,
markPath,
step = /*axis.labelStep || */labelOptions.step,
attribs,
show = true,
tickmarkOffset = axis.tickmarkOffset,
xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
x = xy.x,
y = xy.y,
reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
opacity = pick(opacity, 1);
this.isActive = true;
// create the grid line
if (gridLineWidth) {
gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
if (gridLine === UNDEFINED) {
attribs = {
stroke: gridLineColor,
'stroke-width': gridLineWidth
};
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
if (!type) {
attribs.zIndex = 1;
}
if (old) {
attribs.opacity = 0;
}
tick.gridLine = gridLine =
gridLineWidth ?
renderer.path(gridLinePath)
.attr(attribs).add(axis.gridGroup) :
null;
}
// If the parameter 'old' is set, the current call will be followed
// by another call, therefore do not do any animations this time
if (!old && gridLine && gridLinePath) {
gridLine[tick.isNew ? 'attr' : 'animate']({
d: gridLinePath,
opacity: opacity
});
}
}
// create the tick mark
if (tickWidth && tickLength) {
// negate the length
if (tickPosition === 'inside') {
tickLength = -tickLength;
}
if (axis.opposite) {
tickLength = -tickLength;
}
markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
if (mark) { // updating
mark.animate({
d: markPath,
opacity: opacity
});
} else { // first time
tick.mark = renderer.path(
markPath
).attr({
stroke: tickColor,
'stroke-width': tickWidth,
opacity: opacity
}).add(axis.axisGroup);
}
}
// the label is created on init - now move it into place
if (label && !isNaN(x)) {
label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
// Apply show first and show last. If the tick is both first and last, it is
// a single centered tick, in which case we show the label anyway (#2100).
if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
(tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
show = false;
// Handle label overflow and show or hide accordingly
} else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) {
tick.handleOverflow(xy);
}
// apply step
if (step && index % step) {
// show those indices dividable by step
show = false;
}
// Set the new position, and show or hide
if (show && !isNaN(xy.y)) {
xy.opacity = opacity;
label[tick.isNew ? 'attr' : 'animate'](xy);
tick.isNew = false;
} else {
label.attr('y', -9999); // #1338
}
}
},
/**
* Destructor for the tick prototype
*/
destroy: function () {
destroyObjectProperties(this, this.axis);
}
};
/**
* The object wrapper for plot lines and plot bands
* @param {Object} options
*/
Highcharts.PlotLineOrBand = function (axis, options) {
this.axis = axis;
if (options) {
this.options = options;
this.id = options.id;
}
};
Highcharts.PlotLineOrBand.prototype = {
/**
* Render the plot line or plot band. If it is already existing,
* move it.
*/
render: function () {
var plotLine = this,
axis = plotLine.axis,
horiz = axis.horiz,
options = plotLine.options,
optionsLabel = options.label,
label = plotLine.label,
width = options.width,
to = options.to,
from = options.from,
isBand = defined(from) && defined(to),
value = options.value,
dashStyle = options.dashStyle,
svgElem = plotLine.svgElem,
path = [],
addEvent,
eventType,
xs,
ys,
x,
y,
color = options.color,
zIndex = options.zIndex,
events = options.events,
attribs = {},
renderer = axis.chart.renderer;
// logarithmic conversion
if (axis.isLog) {
from = log2lin(from);
to = log2lin(to);
value = log2lin(value);
}
// plot line
if (width) {
path = axis.getPlotLinePath(value, width);
attribs = {
stroke: color,
'stroke-width': width
};
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
} else if (isBand) { // plot band
path = axis.getPlotBandPath(from, to, options);
if (color) {
attribs.fill = color;
}
if (options.borderWidth) {
attribs.stroke = options.borderColor;
attribs['stroke-width'] = options.borderWidth;
}
} else {
return;
}
// zIndex
if (defined(zIndex)) {
attribs.zIndex = zIndex;
}
// common for lines and bands
if (svgElem) {
if (path) {
svgElem.animate({
d: path
}, null, svgElem.onGetPath);
} else {
svgElem.hide();
svgElem.onGetPath = function () {
svgElem.show();
};
if (label) {
plotLine.label = label = label.destroy();
}
}
} else if (path && path.length) {
plotLine.svgElem = svgElem = renderer.path(path)
.attr(attribs).add();
// events
if (events) {
addEvent = function (eventType) {
svgElem.on(eventType, function (e) {
events[eventType].apply(plotLine, [e]);
});
};
for (eventType in events) {
addEvent(eventType);
}
}
}
// the plot band/line label
if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
// apply defaults
optionsLabel = merge({
align: horiz && isBand && 'center',
x: horiz ? !isBand && 4 : 10,
verticalAlign : !horiz && isBand && 'middle',
y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
rotation: horiz && !isBand && 90
}, optionsLabel);
// add the SVG element
if (!label) {
attribs = {
align: optionsLabel.textAlign || optionsLabel.align,
rotation: optionsLabel.rotation
};
if (defined(zIndex)) {
attribs.zIndex = zIndex;
}
plotLine.label = label = renderer.text(
optionsLabel.text,
0,
0,
optionsLabel.useHTML
)
.attr(attribs)
.css(optionsLabel.style)
.add();
}
// get the bounding box and align the label
// #3000 changed to better handle choice between plotband or plotline
xs = [path[1], path[4], (isBand ? path[6] : path[1])];
ys = [path[2], path[5], (isBand ? path[7] : path[2])];
x = arrayMin(xs);
y = arrayMin(ys);
label.align(optionsLabel, false, {
x: x,
y: y,
width: arrayMax(xs) - x,
height: arrayMax(ys) - y
});
label.show();
} else if (label) { // move out of sight
label.hide();
}
// chainable
return plotLine;
},
/**
* Remove the plot line or band
*/
destroy: function () {
// remove it from the lookup
erase(this.axis.plotLinesAndBands, this);
delete this.axis;
destroyObjectProperties(this);
}
};
/**
* Object with members for extending the Axis prototype
*/
AxisPlotLineOrBandExtension = {
/**
* Create the path for a plot band
*/
getPlotBandPath: function (from, to) {
var toPath = this.getPlotLinePath(to, null, null, true),
path = this.getPlotLinePath(from, null, null, true);
if (path && toPath) {
path.push(
toPath[4],
toPath[5],
toPath[1],
toPath[2]
);
} else { // outside the axis area
path = null;
}
return path;
},
addPlotBand: function (options) {
return this.addPlotBandOrLine(options, 'plotBands');
},
addPlotLine: function (options) {
return this.addPlotBandOrLine(options, 'plotLines');
},
/**
* Add a plot band or plot line after render time
*
* @param options {Object} The plotBand or plotLine configuration object
*/
addPlotBandOrLine: function (options, coll) {
var obj = new Highcharts.PlotLineOrBand(this, options).render(),
userOptions = this.userOptions;
if (obj) { // #2189
// Add it to the user options for exporting and Axis.update
if (coll) {
userOptions[coll] = userOptions[coll] || [];
userOptions[coll].push(options);
}
this.plotLinesAndBands.push(obj);
}
return obj;
},
/**
* Remove a plot band or plot line from the chart by id
* @param {Object} id
*/
removePlotBandOrLine: function (id) {
var plotLinesAndBands = this.plotLinesAndBands,
options = this.options,
userOptions = this.userOptions,
i = plotLinesAndBands.length;
while (i--) {
if (plotLinesAndBands[i].id === id) {
plotLinesAndBands[i].destroy();
}
}
each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) {
i = arr.length;
while (i--) {
if (arr[i].id === id) {
erase(arr, arr[i]);
}
}
});
}
};
/**
* Create a new axis object
* @param {Object} chart
* @param {Object} options
*/
var Axis = Highcharts.Axis = function () {
this.init.apply(this, arguments);
};
Axis.prototype = {
/**
* Default options for the X axis - the Y axis has extended defaults
*/
defaultOptions: {
// allowDecimals: null,
// alternateGridColor: null,
// categories: [],
dateTimeLabelFormats: {
millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
},
endOnTick: false,
gridLineColor: '#D8D8D8',
// gridLineDashStyle: 'solid',
// gridLineWidth: 0,
// reversed: false,
labels: {
enabled: true,
// rotation: 0,
// align: 'center',
// step: null,
style: {
color: '#606060',
cursor: 'default',
fontSize: '11px'
},
x: 0,
y: 15
/*formatter: function () {
return this.value;
},*/
},
lineColor: '#C0D0E0',
lineWidth: 1,
//linkedTo: null,
//max: undefined,
//min: undefined,
minPadding: 0.01,
maxPadding: 0.01,
//minRange: null,
minorGridLineColor: '#E0E0E0',
// minorGridLineDashStyle: null,
minorGridLineWidth: 1,
minorTickColor: '#A0A0A0',
//minorTickInterval: null,
minorTickLength: 2,
minorTickPosition: 'outside', // inside or outside
//minorTickWidth: 0,
//opposite: false,
//offset: 0,
//plotBands: [{
// events: {},
// zIndex: 1,
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//plotLines: [{
// events: {}
// dashStyle: {}
// zIndex:
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//reversed: false,
// showFirstLabel: true,
// showLastLabel: true,
startOfWeek: 1,
startOnTick: false,
tickColor: '#C0D0E0',
//tickInterval: null,
tickLength: 10,
tickmarkPlacement: 'between', // on or between
tickPixelInterval: 100,
tickPosition: 'outside',
tickWidth: 1,
title: {
//text: null,
align: 'middle', // low, middle or high
//margin: 0 for horizontal, 10 for vertical axes,
//rotation: 0,
//side: 'outside',
style: {
color: '#707070'
}
//x: 0,
//y: 0
},
type: 'linear' // linear, logarithmic or datetime
},
/**
* This options set extends the defaultOptions for Y axes
*/
defaultYAxisOptions: {
endOnTick: true,
gridLineWidth: 1,
tickPixelInterval: 72,
showLastLabel: true,
labels: {
x: -8,
y: 3
},
lineWidth: 0,
maxPadding: 0.05,
minPadding: 0.05,
startOnTick: true,
tickWidth: 0,
title: {
rotation: 270,
text: 'Values'
},
stackLabels: {
enabled: false,
//align: dynamic,
//y: dynamic,
//x: dynamic,
//verticalAlign: dynamic,
//textAlign: dynamic,
//rotation: 0,
formatter: function () {
return Highcharts.numberFormat(this.total, -1);
},
style: defaultPlotOptions.line.dataLabels.style
}
},
/**
* These options extend the defaultOptions for left axes
*/
defaultLeftAxisOptions: {
labels: {
x: -15,
y: null
},
title: {
rotation: 270
}
},
/**
* These options extend the defaultOptions for right axes
*/
defaultRightAxisOptions: {
labels: {
x: 15,
y: null
},
title: {
rotation: 90
}
},
/**
* These options extend the defaultOptions for bottom axes
*/
defaultBottomAxisOptions: {
labels: {
autoRotation: [-45],
x: 0,
y: null // based on font size
// overflow: undefined,
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* These options extend the defaultOptions for top axes
*/
defaultTopAxisOptions: {
labels: {
autoRotation: [-45],
x: 0,
y: -15
// overflow: undefined
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* Initialize the axis
*/
init: function (chart, userOptions) {
var isXAxis = userOptions.isX,
axis = this;
// Flag, is the axis horizontal
axis.horiz = chart.inverted ? !isXAxis : isXAxis;
// Flag, isXAxis
axis.isXAxis = isXAxis;
axis.coll = isXAxis ? 'xAxis' : 'yAxis';
axis.opposite = userOptions.opposite; // needed in setOptions
axis.side = userOptions.side || (axis.horiz ?
(axis.opposite ? 0 : 2) : // top : bottom
(axis.opposite ? 1 : 3)); // right : left
axis.setOptions(userOptions);
var options = this.options,
type = options.type,
isDatetimeAxis = type === 'datetime';
axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
// Flag, stagger lines or not
axis.userOptions = userOptions;
//axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
axis.minPixelPadding = 0;
//axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series
//axis.ignoreMaxPadding = UNDEFINED;
axis.chart = chart;
axis.reversed = options.reversed;
axis.zoomEnabled = options.zoomEnabled !== false;
// Initial categories
axis.categories = options.categories || type === 'category';
axis.names = [];
// Elements
//axis.axisGroup = UNDEFINED;
//axis.gridGroup = UNDEFINED;
//axis.axisTitle = UNDEFINED;
//axis.axisLine = UNDEFINED;
// Shorthand types
axis.isLog = type === 'logarithmic';
axis.isDatetimeAxis = isDatetimeAxis;
// Flag, if axis is linked to another axis
axis.isLinked = defined(options.linkedTo);
// Linked axis.
//axis.linkedParent = UNDEFINED;
// Tick positions
//axis.tickPositions = UNDEFINED; // array containing predefined positions
// Tick intervals
//axis.tickInterval = UNDEFINED;
//axis.minorTickInterval = UNDEFINED;
// Major ticks
axis.ticks = {};
axis.labelEdge = [];
// Minor ticks
axis.minorTicks = {};
// List of plotLines/Bands
axis.plotLinesAndBands = [];
// Alternate bands
axis.alternateBands = {};
// Axis metrics
//axis.left = UNDEFINED;
//axis.top = UNDEFINED;
//axis.width = UNDEFINED;
//axis.height = UNDEFINED;
//axis.bottom = UNDEFINED;
//axis.right = UNDEFINED;
//axis.transA = UNDEFINED;
//axis.transB = UNDEFINED;
//axis.oldTransA = UNDEFINED;
axis.len = 0;
//axis.oldMin = UNDEFINED;
//axis.oldMax = UNDEFINED;
//axis.oldUserMin = UNDEFINED;
//axis.oldUserMax = UNDEFINED;
//axis.oldAxisLength = UNDEFINED;
axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
axis.range = options.range;
axis.offset = options.offset || 0;
// Dictionary for stacks
axis.stacks = {};
axis.oldStacks = {};
// Min and max in the data
//axis.dataMin = UNDEFINED,
//axis.dataMax = UNDEFINED,
// The axis range
axis.max = null;
axis.min = null;
// User set min and max
//axis.userMin = UNDEFINED,
//axis.userMax = UNDEFINED,
// Crosshair options
axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false);
// Run Axis
var eventType,
events = axis.options.events;
// Register
if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
if (isXAxis && !this.isColorAxis) { // #2713
chart.axes.splice(chart.xAxis.length, 0, axis);
} else {
chart.axes.push(axis);
}
chart[axis.coll].push(axis);
}
axis.series = axis.series || []; // populated by Series
// inverted charts have reversed xAxes as default
if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
axis.reversed = true;
}
axis.removePlotBand = axis.removePlotBandOrLine;
axis.removePlotLine = axis.removePlotBandOrLine;
// register event listeners
for (eventType in events) {
addEvent(axis, eventType, events[eventType]);
}
// extend logarithmic axis
if (axis.isLog) {
axis.val2lin = log2lin;
axis.lin2val = lin2log;
}
},
/**
* Merge and set options
*/
setOptions: function (userOptions) {
this.options = merge(
this.defaultOptions,
this.isXAxis ? {} : this.defaultYAxisOptions,
[this.defaultTopAxisOptions, this.defaultRightAxisOptions,
this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
merge(
defaultOptions[this.coll], // if set in setOptions (#1053)
userOptions
)
);
},
/**
* The default label formatter. The context is a special config object for the label.
*/
defaultLabelFormatter: function () {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
while (i-- && ret === UNDEFINED) {
multi = Math.pow(1000, i + 1);
if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i];
}
}
}
if (ret === UNDEFINED) {
if (mathAbs(value) >= 10000) { // add thousands separators
ret = Highcharts.numberFormat(value, 0);
} else { // small numbers
ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466
}
}
return ret;
},
/**
* Get the minimum and maximum for the series of each axis
*/
getSeriesExtremes: function () {
var axis = this,
chart = axis.chart;
axis.hasVisibleSeries = false;
// Reset properties in case we're redrawing (#3353)
axis.dataMin = axis.dataMax = axis.ignoreMinPadding = axis.ignoreMaxPadding = null;
if (axis.buildStacks) {
axis.buildStacks();
}
// loop through this axis' series
each(axis.series, function (series) {
if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
var seriesOptions = series.options,
xData,
threshold = seriesOptions.threshold,
seriesDataMin,
seriesDataMax;
axis.hasVisibleSeries = true;
// Validate threshold in logarithmic axes
if (axis.isLog && threshold <= 0) {
threshold = null;
}
// Get dataMin and dataMax for X axes
if (axis.isXAxis) {
xData = series.xData;
if (xData.length) {
axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
}
// Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
} else {
// Get this particular series extremes
series.getExtremes();
seriesDataMax = series.dataMax;
seriesDataMin = series.dataMin;
// Get the dataMin and dataMax so far. If percentage is used, the min and max are
// always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
// doesn't have active y data, we continue with nulls
if (defined(seriesDataMin) && defined(seriesDataMax)) {
axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
}
// Adjust to threshold
if (defined(threshold)) {
if (axis.dataMin >= threshold) {
axis.dataMin = threshold;
axis.ignoreMinPadding = true;
} else if (axis.dataMax < threshold) {
axis.dataMax = threshold;
axis.ignoreMaxPadding = true;
}
}
}
}
});
},
/**
* Translate from axis value to pixel position on the chart, or back
*
*/
translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this,
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
postTranslate = (axis.postTranslate || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axis.len;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * (axis.sector || axis.len);
}
// From pixels to value
if (backwards) { // reverse translation
val = val * sign + cvsOffset;
val -= minPixelPadding;
returnValue = val / localA + localMin; // from chart pixel to value
if (postTranslate) { // log and ordinal axes
returnValue = axis.lin2val(returnValue);
}
// From value to pixels
} else {
if (postTranslate) { // log and ordinal axes
val = axis.val2lin(val);
}
if (pointPlacement === 'between') {
pointPlacement = 0.5;
}
returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
(isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
}
return returnValue;
},
/**
* Utility method to translate an axis value to pixel position.
* @param {Number} value A value in terms of axis units
* @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
* or just the axis/pane itself.
*/
toPixels: function (value, paneCoordinates) {
return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
},
/*
* Utility method to translate a pixel position in to an axis value
* @param {Number} pixel The pixel value coordinate
* @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
* axis/pane itself.
*/
toValue: function (pixel, paneCoordinates) {
return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
},
/**
* Create the path for a plot line that goes from the given value on
* this axis, across the plot to the opposite side
* @param {Number} value
* @param {Number} lineWidth Used for calculation crisp line
* @param {Number] old Use old coordinates (for resizing and rescaling)
*/
getPlotLinePath: function (value, lineWidth, old, force, translatedValue) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB,
/**
* Check if x is between a and b. If not, either move to a/b or skip,
* depending on the force parameter.
*/
between = function (x, a, b) {
if (x < a || x > b) {
if (force) {
x = mathMin(mathMax(a, x), b);
} else {
skip = true;
}
}
return x;
};
translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
x1 = x2 = mathRound(translatedValue + transB);
y1 = y2 = mathRound(cHeight - translatedValue - transB);
if (isNaN(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
x1 = x2 = between(x1, axisLeft, axisLeft + axis.width);
} else {
x1 = axisLeft;
x2 = cWidth - axis.right;
y1 = y2 = between(y1, axisTop, axisTop + axis.height);
}
return skip && !force ?
null :
chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1);
},
/**
* Set the tick positions of a linear axis to round values like whole tens or every five.
*/
getLinearTickPositions: function (tickInterval, min, max) {
var pos,
lastPos,
roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
tickPositions = [];
// For single points, add a tick regardless of the relative position (#2662)
if (min === max && isNumber(min)) {
return [min];
}
// Populate the intermediate values
pos = roundedMin;
while (pos <= roundedMax) {
// Place the tick on the rounded value
tickPositions.push(pos);
// Always add the raw tickInterval, not the corrected one.
pos = correctFloat(pos + tickInterval);
// If the interval is not big enough in the current min - max range to actually increase
// the loop variable, we need to break out to prevent endless loop. Issue #619
if (pos === lastPos) {
break;
}
// Record the last value
lastPos = pos;
}
return tickPositions;
},
/**
* Return the minor tick positions. For logarithmic axes, reuse the same logic
* as for major ticks.
*/
getMinorTickPositions: function () {
var axis = this,
options = axis.options,
tickPositions = axis.tickPositions,
minorTickInterval = axis.minorTickInterval,
minorTickPositions = [],
pos,
i,
min = axis.min,
max = axis.max,
len;
// If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them.
if ((max - min) / minorTickInterval < axis.len / 3) {
if (axis.isLog) {
len = tickPositions.length;
for (i = 1; i < len; i++) {
minorTickPositions = minorTickPositions.concat(
axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
);
}
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
axis.getTimeTicks(
axis.normalizeTimeTickInterval(minorTickInterval),
min,
max,
options.startOfWeek
)
);
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
axis.getTimeTicks(
axis.normalizeTimeTickInterval(minorTickInterval),
axis.min,
axis.max,
options.startOfWeek
)
);
} else {
for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) {
minorTickPositions.push(pos);
}
}
}
axis.trimTicks(minorTickPositions); // #3652 #3743
return minorTickPositions;
},
/**
* Adjust the min and max for the minimum range. Keep in mind that the series data is
* not yet processed, so we don't have information on data cropping and grouping, or
* updated axis.pointRange or series.pointRange. The data can't be processed until
* we have finally established min and max.
*/
adjustForMinRange: function () {
var axis = this,
options = axis.options,
min = axis.min,
max = axis.max,
zoomOffset,
spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
closestDataRange,
i,
distance,
xData,
loopLength,
minArgs,
maxArgs;
// Set the automatic minimum range based on the closest point distance
if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
if (defined(options.min) || defined(options.max)) {
axis.minRange = null; // don't do this again
} else {
// Find the closest distance between raw data points, as opposed to
// closestPointRange that applies to processed points (cropped and grouped)
each(axis.series, function (series) {
xData = series.xData;
loopLength = series.xIncrement ? 1 : xData.length - 1;
for (i = loopLength; i > 0; i--) {
distance = xData[i] - xData[i - 1];
if (closestDataRange === UNDEFINED || distance < closestDataRange) {
closestDataRange = distance;
}
}
});
axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
}
}
// if minRange is exceeded, adjust
if (max - min < axis.minRange) {
var minRange = axis.minRange;
zoomOffset = (minRange - max + min) / 2;
// if min and max options have been set, don't go beyond it
minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
if (spaceAvailable) { // if space is available, stay within the data range
minArgs[2] = axis.dataMin;
}
min = arrayMax(minArgs);
maxArgs = [min + minRange, pick(options.max, min + minRange)];
if (spaceAvailable) { // if space is availabe, stay within the data range
maxArgs[2] = axis.dataMax;
}
max = arrayMin(maxArgs);
// now if the max is adjusted, adjust the min back
if (max - min < minRange) {
minArgs[0] = max - minRange;
minArgs[1] = pick(options.min, max - minRange);
min = arrayMax(minArgs);
}
}
// Record modified extremes
axis.min = min;
axis.max = max;
},
/**
* Update translation information
*/
setAxisTranslation: function (saveOld) {
var axis = this,
range = axis.max - axis.min,
pointRange = axis.axisPointRange || 0,
closestPointRange,
minPointOffset = 0,
pointRangePadding = 0,
linkedParent = axis.linkedParent,
ordinalCorrection,
hasCategories = !!axis.categories,
transA = axis.transA;
// Adjust translation for padding. Y axis with categories need to go through the same (#1784).
if (axis.isXAxis || hasCategories || pointRange) {
if (linkedParent) {
minPointOffset = linkedParent.minPointOffset;
pointRangePadding = linkedParent.pointRangePadding;
} else {
each(axis.series, function (series) {
var seriesPointRange = hasCategories ? 1 : (axis.isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806
pointPlacement = series.options.pointPlacement,
seriesClosestPointRange = series.closestPointRange;
if (seriesPointRange > range) { // #1446
seriesPointRange = 0;
}
pointRange = mathMax(pointRange, seriesPointRange);
if (!axis.single) {
// minPointOffset is the value padding to the left of the axis in order to make
// room for points with a pointRange, typically columns. When the pointPlacement option
// is 'between' or 'on', this padding does not apply.
minPointOffset = mathMax(
minPointOffset,
isString(pointPlacement) ? 0 : seriesPointRange / 2
);
// Determine the total padding needed to the length of the axis to make room for the
// pointRange. If the series' pointPlacement is 'on', no padding is added.
pointRangePadding = mathMax(
pointRangePadding,
pointPlacement === 'on' ? 0 : seriesPointRange
);
}
// Set the closestPointRange
if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
closestPointRange = defined(closestPointRange) ?
mathMin(closestPointRange, seriesClosestPointRange) :
seriesClosestPointRange;
}
});
}
// Record minPointOffset and pointRangePadding
ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
// pointRange means the width reserved for each point, like in a column chart
axis.pointRange = mathMin(pointRange, range);
// closestPointRange means the closest distance between points. In columns
// it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
// is some other value
axis.closestPointRange = closestPointRange;
}
// Secondary values
if (saveOld) {
axis.oldTransA = transA;
}
axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
axis.minPixelPadding = transA * minPointOffset;
},
/**
* Set the tick positions to round values and optionally extend the extremes
* to the nearest tick
*/
setTickInterval: function (secondPass) {
var axis = this,
chart = axis.chart,
options = axis.options,
isLog = axis.isLog,
isDatetimeAxis = axis.isDatetimeAxis,
isXAxis = axis.isXAxis,
isLinked = axis.isLinked,
maxPadding = options.maxPadding,
minPadding = options.minPadding,
length,
linkedParentExtremes,
tickIntervalOption = options.tickInterval,
minTickInterval,
tickPixelIntervalOption = options.tickPixelInterval,
categories = axis.categories;
if (!isDatetimeAxis && !categories && !isLinked) {
this.getTickAmount();
}
// linked axis gets the extremes from the parent axis
if (isLinked) {
axis.linkedParent = chart[axis.coll][options.linkedTo];
linkedParentExtremes = axis.linkedParent.getExtremes();
axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
if (options.type !== axis.linkedParent.options.type) {
error(11, 1); // Can't link axes of different type
}
} else { // initial min and max from the extreme data values
axis.min = pick(axis.userMin, options.min, axis.dataMin);
axis.max = pick(axis.userMax, options.max, axis.dataMax);
}
if (isLog) {
if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
error(10, 1); // Can't plot negative values on log axis
}
axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934
axis.max = correctFloat(log2lin(axis.max));
}
// handle zoomed range
if (axis.range && defined(axis.max)) {
axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618
axis.userMax = axis.max;
axis.range = null; // don't use it when running setExtremes
}
// Hook for adjusting this.min and this.max. Used by bubble series.
if (axis.beforePadding) {
axis.beforePadding();
}
// adjust min and max for the minimum range
axis.adjustForMinRange();
// Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
// into account, we do this after computing tick interval (#1337).
if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
length = axis.max - axis.min;
if (length) {
if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) {
axis.min -= length * minPadding;
}
if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) {
axis.max += length * maxPadding;
}
}
}
// Stay within floor and ceiling
if (isNumber(options.floor)) {
axis.min = mathMax(axis.min, options.floor);
}
if (isNumber(options.ceiling)) {
axis.max = mathMin(axis.max, options.ceiling);
}
// get tickInterval
if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
axis.tickInterval = 1;
} else if (isLinked && !tickIntervalOption &&
tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
axis.tickInterval = axis.linkedParent.tickInterval;
} else {
axis.tickInterval = pick(
tickIntervalOption,
this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined,
categories ? // for categoried axis, 1 is default, for linear axis use tickPix
1 :
// don't let it be more than the data range
(axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
);
}
// Now we're finished detecting min and max, crop and group series data. This
// is in turn needed in order to find tick positions in ordinal axes.
if (isXAxis && !secondPass) {
each(axis.series, function (series) {
series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
});
}
// set the translation factor used in translate function
axis.setAxisTranslation(true);
// hook for ordinal axes and radial axes
if (axis.beforeSetTickPositions) {
axis.beforeSetTickPositions();
}
// hook for extensions, used in Highstock ordinal axes
if (axis.postProcessTickInterval) {
axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
}
// In column-like charts, don't cramp in more ticks than there are points (#1943)
if (axis.pointRange) {
axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
}
// Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange);
if (!tickIntervalOption && axis.tickInterval < minTickInterval) {
axis.tickInterval = minTickInterval;
}
// for linear axes, get magnitude and normalize the interval
if (!isDatetimeAxis && !isLog) { // linear
if (!tickIntervalOption) {
axis.tickInterval = normalizeTickInterval(
axis.tickInterval,
null,
getMagnitude(axis.tickInterval),
// If the tick interval is between 0.5 and 5 and the axis max is in the order of
// thousands, chances are we are dealing with years. Don't allow decimals. #3363.
pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)),
!!this.tickAmount
);
}
}
// Prevent ticks from getting so close that we can't draw the labels
if (!this.tickAmount && this.len) { // Color axis with disabled legend has no length
axis.tickInterval = axis.unsquish();
}
this.setTickPositions();
},
/**
* Now we have computed the normalized tickInterval, get the tick positions
*/
setTickPositions: function () {
var options = this.options,
tickPositions,
tickPositionsOption = options.tickPositions,
tickPositioner = options.tickPositioner,
startOnTick = options.startOnTick,
endOnTick = options.endOnTick,
single;
// Set the tickmarkOffset
this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' &&
this.tickInterval === 1) ? 0.5 : 0; // #3202
// get minorTickInterval
this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ?
this.tickInterval / 5 : options.minorTickInterval;
// Find the tick positions
this.tickPositions = tickPositions = options.tickPositions && options.tickPositions.slice(); // Work on a copy (#1565)
if (!tickPositions) {
if (this.isDatetimeAxis) {
tickPositions = this.getTimeTicks(
this.normalizeTimeTickInterval(this.tickInterval, options.units),
this.min,
this.max,
options.startOfWeek,
this.ordinalPositions,
this.closestPointRange,
true
);
} else if (this.isLog) {
tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max);
} else {
tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max);
}
this.tickPositions = tickPositions;
// Run the tick positioner callback, that allows modifying auto tick positions.
if (tickPositioner) {
tickPositioner = tickPositioner.apply(this, [this.min, this.max]);
if (tickPositioner) {
this.tickPositions = tickPositions = tickPositioner;
}
}
}
if (!this.isLinked) {
// reset min/max or remove extremes based on start/end on tick
this.trimTicks(tickPositions, startOnTick, endOnTick);
// When there is only one point, or all points have the same value on this axis, then min
// and max are equal and tickPositions.length is 0 or 1. In this case, add some padding
// in order to center the point, but leave it with one tick. #1337.
if (this.min === this.max && defined(this.min) && !this.tickAmount) {
// Substract half a unit (#2619, #2846, #2515, #3390)
single = true;
this.min -= 0.5;
this.max += 0.5;
}
this.single = single;
if (!tickPositionsOption && !tickPositioner) {
this.adjustTickAmount();
}
}
},
/**
* Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max
*/
trimTicks: function (tickPositions, startOnTick, endOnTick) {
var roundedMin = tickPositions[0],
roundedMax = tickPositions[tickPositions.length - 1],
minPointOffset = this.minPointOffset || 0;
if (startOnTick) {
this.min = roundedMin;
} else if (this.min - minPointOffset > roundedMin) {
tickPositions.shift();
}
if (endOnTick) {
this.max = roundedMax;
} else if (this.max + minPointOffset < roundedMax) {
tickPositions.pop();
}
// If no tick are left, set one tick in the middle (#3195)
if (tickPositions.length === 0 && defined(roundedMin)) {
tickPositions.push((roundedMax + roundedMin) / 2);
}
},
/**
* Set the max ticks of either the x and y axis collection
*/
getTickAmount: function () {
var others = {}, // Whether there is another axis to pair with this one
hasOther,
options = this.options,
tickAmount = options.tickAmount,
tickPixelInterval = options.tickPixelInterval;
if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial &&
!this.isLog && options.startOnTick && options.endOnTick) {
tickAmount = 2;
}
if (!tickAmount && this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) {
// Check if there are multiple axes in the same pane
each(this.chart[this.coll], function (axis) {
var options = axis.options,
horiz = axis.horiz,
key = [horiz ? options.left : options.top, horiz ? options.width : options.height, options.pane].join(',');
if (others[key]) {
hasOther = true;
} else {
others[key] = 1;
}
});
if (hasOther) {
// Add 1 because 4 tick intervals require 5 ticks (including first and last)
tickAmount = mathCeil(this.len / tickPixelInterval) + 1;
}
}
// For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This
// prevents the axis from adding ticks that are too far away from the data extremes.
if (tickAmount < 4) {
this.finalTickAmt = tickAmount;
tickAmount = 5;
}
this.tickAmount = tickAmount;
},
/**
* When using multiple axes, adjust the number of ticks to match the highest
* number of ticks in that group
*/
adjustTickAmount: function () {
var tickInterval = this.tickInterval,
tickPositions = this.tickPositions,
tickAmount = this.tickAmount,
finalTickAmt = this.finalTickAmt,
currentTickAmount = tickPositions && tickPositions.length,
i,
len;
if (currentTickAmount < tickAmount) { // TODO: Check #3411
while (tickPositions.length < tickAmount) {
tickPositions.push(correctFloat(
tickPositions[tickPositions.length - 1] + tickInterval
));
}
this.transA *= (currentTickAmount - 1) / (tickAmount - 1);
this.max = tickPositions[tickPositions.length - 1];
// We have too many ticks, run second pass to try to reduce ticks
} else if (currentTickAmount > tickAmount) {
this.tickInterval *= 2;
this.setTickPositions();
}
// The finalTickAmt property is set in getTickAmount
if (defined(finalTickAmt)) {
i = len = tickPositions.length;
while (i--) {
if (
(finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick
(finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last
) {
tickPositions.splice(i, 1);
}
}
this.finalTickAmt = UNDEFINED;
}
},
/**
* Set the scale based on data min and max, user set min and max or options
*
*/
setScale: function () {
var axis = this,
stacks = axis.stacks,
type,
i,
isDirtyData,
isDirtyAxisLength;
axis.oldMin = axis.min;
axis.oldMax = axis.max;
axis.oldAxisLength = axis.len;
// set the new axisLength
axis.setAxisSize();
//axisLength = horiz ? axisWidth : axisHeight;
isDirtyAxisLength = axis.len !== axis.oldAxisLength;
// is there new data?
each(axis.series, function (series) {
if (series.isDirtyData || series.isDirty ||
series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
isDirtyData = true;
}
});
// do we really need to go through all this?
if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
// reset stacks
if (!axis.isXAxis) {
for (type in stacks) {
for (i in stacks[type]) {
stacks[type][i].total = null;
stacks[type][i].cum = 0;
}
}
}
axis.forceRedraw = false;
// get data extremes if needed
axis.getSeriesExtremes();
// get fixed positions based on tickInterval
axis.setTickInterval();
// record old values to decide whether a rescale is necessary later on (#540)
axis.oldUserMin = axis.userMin;
axis.oldUserMax = axis.userMax;
// Mark as dirty if it is not already set to dirty and extremes have changed. #595.
if (!axis.isDirty) {
axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
}
} else if (!axis.isXAxis) {
if (axis.oldStacks) {
stacks = axis.stacks = axis.oldStacks;
}
// reset stacks
for (type in stacks) {
for (i in stacks[type]) {
stacks[type][i].cum = stacks[type][i].total;
}
}
}
},
/**
* Set the extremes and optionally redraw
* @param {Number} newMin
* @param {Number} newMax
* @param {Boolean} redraw
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
* @param {Object} eventArguments
*
*/
setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
var axis = this,
chart = axis.chart;
redraw = pick(redraw, true); // defaults to true
each(axis.series, function (serie) {
delete serie.kdTree;
});
// Extend the arguments with min and max
eventArguments = extend(eventArguments, {
min: newMin,
max: newMax
});
// Fire the event
fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
axis.userMin = newMin;
axis.userMax = newMax;
axis.eventArgs = eventArguments;
// Mark for running afterSetExtremes
axis.isDirtyExtremes = true;
// redraw
if (redraw) {
chart.redraw(animation);
}
});
},
/**
* Overridable method for zooming chart. Pulled out in a separate method to allow overriding
* in stock charts.
*/
zoom: function (newMin, newMax) {
var dataMin = this.dataMin,
dataMax = this.dataMax,
options = this.options;
// Prevent pinch zooming out of range. Check for defined is for #1946. #1734.
if (!this.allowZoomOutside) {
if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) {
newMin = UNDEFINED;
}
if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, dataMax))) {
newMax = UNDEFINED;
}
}
// In full view, displaying the reset zoom button is not required
this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
// Do it
this.setExtremes(
newMin,
newMax,
false,
UNDEFINED,
{ trigger: 'zoom' }
);
return true;
},
/**
* Update the axis metrics
*/
setAxisSize: function () {
var chart = this.chart,
options = this.options,
offsetLeft = options.offsetLeft || 0,
offsetRight = options.offsetRight || 0,
horiz = this.horiz,
width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight),
height = pick(options.height, chart.plotHeight),
top = pick(options.top, chart.plotTop),
left = pick(options.left, chart.plotLeft + offsetLeft),
percentRegex = /%$/;
// Check for percentage based input values
if (percentRegex.test(height)) {
height = parseFloat(height) / 100 * chart.plotHeight;
}
if (percentRegex.test(top)) {
top = parseFloat(top) / 100 * chart.plotHeight + chart.plotTop;
}
// Expose basic values to use in Series object and navigator
this.left = left;
this.top = top;
this.width = width;
this.height = height;
this.bottom = chart.chartHeight - height - top;
this.right = chart.chartWidth - width - left;
// Direction agnostic properties
this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
this.pos = horiz ? left : top; // distance from SVG origin
},
/**
* Get the actual axis extremes
*/
getExtremes: function () {
var axis = this,
isLog = axis.isLog;
return {
min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
dataMin: axis.dataMin,
dataMax: axis.dataMax,
userMin: axis.userMin,
userMax: axis.userMax
};
},
/**
* Get the zero plane either based on zero or on the min or max value.
* Used in bar and area plots
*/
getThreshold: function (threshold) {
var axis = this,
isLog = axis.isLog;
var realMin = isLog ? lin2log(axis.min) : axis.min,
realMax = isLog ? lin2log(axis.max) : axis.max;
if (realMin > threshold || threshold === null) {
threshold = realMin;
} else if (realMax < threshold) {
threshold = realMax;
}
return axis.translate(threshold, 0, 1, 0, 1);
},
/**
* Compute auto alignment for the axis label based on which side the axis is on
* and the given rotation for the label
*/
autoLabelAlign: function (rotation) {
var ret,
angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
if (angle > 15 && angle < 165) {
ret = 'right';
} else if (angle > 195 && angle < 345) {
ret = 'left';
} else {
ret = 'center';
}
return ret;
},
/**
* Prevent the ticks from getting so close we can't draw the labels. On a horizontal
* axis, this is handled by rotating the labels, removing ticks and adding ellipsis.
* On a vertical axis remove ticks and add ellipsis.
*/
unsquish: function () {
var chart = this.chart,
ticks = this.ticks,
labelOptions = this.options.labels,
horiz = this.horiz,
tickInterval = this.tickInterval,
newTickInterval = tickInterval,
slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval),
rotation,
rotationOption = labelOptions.rotation,
labelMetrics = chart.renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label),
step,
bestScore = Number.MAX_VALUE,
autoRotation,
// Return the multiple of tickInterval that is needed to avoid collision
getStep = function (spaceNeeded) {
var step = spaceNeeded / (slotSize || 1);
step = step > 1 ? mathCeil(step) : 1;
return step * tickInterval;
};
if (horiz) {
autoRotation = defined(rotationOption) ?
[rotationOption] :
slotSize < 80 && !labelOptions.staggerLines && !labelOptions.step && labelOptions.autoRotation;
if (autoRotation) {
// Loop over the given autoRotation options, and determine which gives the best score. The
// best score is that with the lowest number of steps and a rotation closest to horizontal.
each(autoRotation, function (rot) {
var score;
if (rot && rot >= -90 && rot <= 90) {
step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot)));
score = step + mathAbs(rot / 360);
if (score < bestScore) {
bestScore = score;
rotation = rot;
newTickInterval = step;
}
}
});
}
} else {
newTickInterval = getStep(labelMetrics.h);
}
this.autoRotation = autoRotation;
this.labelRotation = rotation;
return newTickInterval;
},
renderUnsquish: function () {
var chart = this.chart,
renderer = chart.renderer,
tickPositions = this.tickPositions,
ticks = this.ticks,
labelOptions = this.options.labels,
horiz = this.horiz,
margin = chart.margin,
slotWidth = this.slotWidth = (horiz && !labelOptions.step && !labelOptions.rotation &&
((this.staggerLines || 1) * chart.plotWidth) / tickPositions.length) ||
(!horiz && ((margin[3] && (margin[3] - chart.spacing[3])) || chart.chartWidth * 0.33)), // #1580, #1931,
innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))),
attr = {},
labelMetrics = renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label),
css,
labelLength = 0,
label,
i,
pos;
// Set rotation option unless it is "auto", like in gauges
if (!isString(labelOptions.rotation)) {
attr.rotation = labelOptions.rotation;
}
// Handle auto rotation on horizontal axis
if (this.autoRotation) {
// Get the longest label length
each(tickPositions, function (tick) {
tick = ticks[tick];
if (tick && tick.labelLength > labelLength) {
labelLength = tick.labelLength;
}
});
// Apply rotation only if the label is too wide for the slot, and
// the label is wider than its height.
if (labelLength > innerWidth && labelLength > labelMetrics.h) {
attr.rotation = this.labelRotation;
} else {
this.labelRotation = 0;
}
// Handle word-wrap or ellipsis on vertical axis
} else if (slotWidth) {
// For word-wrap or ellipsis
css = { width: innerWidth + PX, textOverflow: 'clip' };
// On vertical axis, only allow word wrap if there is room for more lines.
i = tickPositions.length;
while (!horiz && i--) {
pos = tickPositions[i];
label = ticks[pos].label;
if (label) {
if (this.len / tickPositions.length - 4 < label.getBBox().height) {
label.specCss = { textOverflow: 'ellipsis' };
}
}
}
}
// Add ellipsis if the label length is significantly longer than ideal
if (attr.rotation) {
css = {
width: (labelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX,
textOverflow: 'ellipsis'
};
}
// Set the explicit or automatic label alignment
this.labelAlign = attr.align = labelOptions.align || this.autoLabelAlign(this.labelRotation);
// Apply general and specific CSS
each(tickPositions, function (pos) {
var tick = ticks[pos],
label = tick && tick.label;
if (label) {
if (css) {
label.css(merge(css, label.specCss));
}
delete label.specCss;
label.attr(attr);
tick.rotation = attr.rotation;
}
});
// TODO: Why not part of getLabelPosition?
this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side === 2);
},
/**
* Render the tick labels to a preliminary position to get their sizes
*/
getOffset: function () {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
tickPositions = axis.tickPositions,
ticks = axis.ticks,
horiz = axis.horiz,
side = axis.side,
invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
hasData,
showAxis,
titleOffset = 0,
titleOffsetOption,
titleMargin = 0,
axisTitleOptions = options.title,
labelOptions = options.labels,
labelOffset = 0, // reset
labelOffsetPadded,
axisOffset = chart.axisOffset,
clipOffset = chart.clipOffset,
directionFactor = [-1, 1, 1, -1][side],
n,
lineHeightCorrection;
// For reuse in Axis.render
axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions));
axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
// Set/reset staggerLines
axis.staggerLines = axis.horiz && labelOptions.staggerLines;
// Create the axisGroup and gridGroup elements on first iteration
if (!axis.axisGroup) {
axis.gridGroup = renderer.g('grid')
.attr({ zIndex: options.gridZIndex || 1 })
.add();
axis.axisGroup = renderer.g('axis')
.attr({ zIndex: options.zIndex || 2 })
.add();
axis.labelGroup = renderer.g('axis-labels')
.attr({ zIndex: labelOptions.zIndex || 7 })
.addClass(PREFIX + axis.coll.toLowerCase() + '-labels')
.add();
}
if (hasData || axis.isLinked) {
// Generate ticks
each(tickPositions, function (pos) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
} else {
ticks[pos].addLabel(); // update labels depending on tick interval
}
});
axis.renderUnsquish();
each(tickPositions, function (pos) {
// left side must be align: right and right side must have align: left for labels
if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) {
// get the highest offset
labelOffset = mathMax(
ticks[pos].getLabelSize(),
labelOffset
);
}
});
if (axis.staggerLines) {
labelOffset *= axis.staggerLines;
axis.labelOffset = labelOffset;
}
} else { // doesn't have data
for (n in ticks) {
ticks[n].destroy();
delete ticks[n];
}
}
if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
if (!axis.axisTitle) {
axis.axisTitle = renderer.text(
axisTitleOptions.text,
0,
0,
axisTitleOptions.useHTML
)
.attr({
zIndex: 7,
rotation: axisTitleOptions.rotation || 0,
align:
axisTitleOptions.textAlign ||
{ low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
})
.addClass(PREFIX + this.coll.toLowerCase() + '-title')
.css(axisTitleOptions.style)
.add(axis.axisGroup);
axis.axisTitle.isNew = true;
}
if (showAxis) {
titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
titleOffsetOption = axisTitleOptions.offset;
titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10);
}
// hide or show the title depending on whether showEmpty is set
axis.axisTitle[showAxis ? 'show' : 'hide']();
}
// handle automatic or user set offset
axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar
lineHeightCorrection = side === 2 ? axis.tickRotCorr.y : 0;
labelOffsetPadded = labelOffset + titleMargin +
(labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + 8) : labelOptions.x) - lineHeightCorrection));
axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded);
axisOffset[side] = mathMax(
axisOffset[side],
axis.axisTitleMargin + titleOffset + directionFactor * axis.offset,
labelOffsetPadded // #3027
);
clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2);
},
/**
* Get the path for the axis line
*/
getLinePath: function (lineWidth) {
var chart = this.chart,
opposite = this.opposite,
offset = this.offset,
horiz = this.horiz,
lineLeft = this.left + (opposite ? this.width : 0) + offset,
lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
if (opposite) {
lineWidth *= -1; // crispify the other way - #1480, #1687
}
return chart.renderer.crispLine([
M,
horiz ?
this.left :
lineLeft,
horiz ?
lineTop :
this.top,
L,
horiz ?
chart.chartWidth - this.right :
lineLeft,
horiz ?
lineTop :
chart.chartHeight - this.bottom
], lineWidth);
},
/**
* Position the title
*/
getTitlePosition: function () {
// compute anchor points for each of the title align options
var horiz = this.horiz,
axisLeft = this.left,
axisTop = this.top,
axisLength = this.len,
axisTitleOptions = this.options.title,
margin = horiz ? axisLeft : axisTop,
opposite = this.opposite,
offset = this.offset,
fontSize = pInt(axisTitleOptions.style.fontSize || 12),
// the position in the length direction of the axis
alongAxis = {
low: margin + (horiz ? 0 : axisLength),
middle: margin + axisLength / 2,
high: margin + (horiz ? axisLength : 0)
}[axisTitleOptions.align],
// the position in the perpendicular direction of the axis
offAxis = (horiz ? axisTop + this.height : axisLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
this.axisTitleMargin +
(this.side === 2 ? fontSize : 0);
return {
x: horiz ?
alongAxis :
offAxis + (opposite ? this.width : 0) + offset +
(axisTitleOptions.x || 0), // x
y: horiz ?
offAxis - (opposite ? this.height : 0) + offset :
alongAxis + (axisTitleOptions.y || 0) // y
};
},
/**
* Render the axis
*/
render: function () {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
isLog = axis.isLog,
isLinked = axis.isLinked,
tickPositions = axis.tickPositions,
axisTitle = axis.axisTitle,
ticks = axis.ticks,
minorTicks = axis.minorTicks,
alternateBands = axis.alternateBands,
stackLabelOptions = options.stackLabels,
alternateGridColor = options.alternateGridColor,
tickmarkOffset = axis.tickmarkOffset,
lineWidth = options.lineWidth,
linePath,
hasRendered = chart.hasRendered,
slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
hasData = axis.hasData,
showAxis = axis.showAxis,
from,
to;
// Reset
axis.labelEdge.length = 0;
//axis.justifyToPlot = overflow === 'justify';
axis.overlap = false;
// Mark all elements inActive before we go over and mark the active ones
each([ticks, minorTicks, alternateBands], function (coll) {
var pos;
for (pos in coll) {
coll[pos].isActive = false;
}
});
// If the series has data draw the ticks. Else only the line and title
if (hasData || isLinked) {
// minor ticks
if (axis.minorTickInterval && !axis.categories) {
each(axis.getMinorTickPositions(), function (pos) {
if (!minorTicks[pos]) {
minorTicks[pos] = new Tick(axis, pos, 'minor');
}
// render new ticks in old position
if (slideInTicks && minorTicks[pos].isNew) {
minorTicks[pos].render(null, true);
}
minorTicks[pos].render(null, false, 1);
});
}
// Major ticks. Pull out the first item and render it last so that
// we can get the position of the neighbour label. #808.
if (tickPositions.length) { // #1300
each(tickPositions, function (pos, i) {
// linked axes need an extra check to find out if
if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
}
// render new ticks in old position
if (slideInTicks && ticks[pos].isNew) {
ticks[pos].render(i, true, 0.1);
}
ticks[pos].render(i);
}
});
// In a categorized axis, the tick marks are displayed between labels. So
// we need to add a tick mark and grid line at the left edge of the X axis.
if (tickmarkOffset && (axis.min === 0 || axis.single)) {
if (!ticks[-1]) {
ticks[-1] = new Tick(axis, -1, null, true);
}
ticks[-1].render(-1);
}
}
// alternate grid color
if (alternateGridColor) {
each(tickPositions, function (pos, i) {
if (i % 2 === 0 && pos < axis.max) {
if (!alternateBands[pos]) {
alternateBands[pos] = new Highcharts.PlotLineOrBand(axis);
}
from = pos + tickmarkOffset; // #949
to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max;
alternateBands[pos].options = {
from: isLog ? lin2log(from) : from,
to: isLog ? lin2log(to) : to,
color: alternateGridColor
};
alternateBands[pos].render();
alternateBands[pos].isActive = true;
}
});
}
// custom plot lines and bands
if (!axis._addedPlotLB) { // only first time
each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
axis.addPlotBandOrLine(plotLineOptions);
});
axis._addedPlotLB = true;
}
} // end if hasData
// Remove inactive ticks
each([ticks, minorTicks, alternateBands], function (coll) {
var pos,
i,
forDestruction = [],
delay = globalAnimation ? globalAnimation.duration || 500 : 0,
destroyInactiveItems = function () {
i = forDestruction.length;
while (i--) {
// When resizing rapidly, the same items may be destroyed in different timeouts,
// or the may be reactivated
if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
coll[forDestruction[i]].destroy();
delete coll[forDestruction[i]];
}
}
};
for (pos in coll) {
if (!coll[pos].isActive) {
// Render to zero opacity
coll[pos].render(pos, false, 0);
coll[pos].isActive = false;
forDestruction.push(pos);
}
}
// When the objects are finished fading out, destroy them
if (coll === alternateBands || !chart.hasRendered || !delay) {
destroyInactiveItems();
} else if (delay) {
setTimeout(destroyInactiveItems, delay);
}
});
// Static items. As the axis group is cleared on subsequent calls
// to render, these items are added outside the group.
// axis line
if (lineWidth) {
linePath = axis.getLinePath(lineWidth);
if (!axis.axisLine) {
axis.axisLine = renderer.path(linePath)
.attr({
stroke: options.lineColor,
'stroke-width': lineWidth,
zIndex: 7
})
.add(axis.axisGroup);
} else {
axis.axisLine.animate({ d: linePath });
}
// show or hide the line depending on options.showEmpty
axis.axisLine[showAxis ? 'show' : 'hide']();
}
if (axisTitle && showAxis) {
axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
axis.getTitlePosition()
);
axisTitle.isNew = false;
}
// Stacked totals:
if (stackLabelOptions && stackLabelOptions.enabled) {
axis.renderStackTotals();
}
// End stacked totals
axis.isDirty = false;
},
/**
* Redraw the axis to reflect changes in the data or axis extremes
*/
redraw: function () {
// render the axis
this.render();
// move plot lines and bands
each(this.plotLinesAndBands, function (plotLine) {
plotLine.render();
});
// mark associated series as dirty and ready for redraw
each(this.series, function (series) {
series.isDirty = true;
});
},
/**
* Destroys an Axis instance.
*/
destroy: function (keepEvents) {
var axis = this,
stacks = axis.stacks,
stackKey,
plotLinesAndBands = axis.plotLinesAndBands,
i;
// Remove the events
if (!keepEvents) {
removeEvent(axis);
}
// Destroy each stack total
for (stackKey in stacks) {
destroyObjectProperties(stacks[stackKey]);
stacks[stackKey] = null;
}
// Destroy collections
each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
destroyObjectProperties(coll);
});
i = plotLinesAndBands.length;
while (i--) { // #1975
plotLinesAndBands[i].destroy();
}
// Destroy local variables
each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) {
if (axis[prop]) {
axis[prop] = axis[prop].destroy();
}
});
// Destroy crosshair
if (this.cross) {
this.cross.destroy();
}
},
/**
* Draw the crosshair
*/
drawCrosshair: function (e, point) { // docs: Missing docs for Axis.crosshair. Also for properties.
var path,
options = this.crosshair,
animation = options.animation,
pos,
attribs,
categorized;
if (
// Disabled in options
!this.crosshair ||
// snap
((defined(point) || !pick(this.crosshair.snap, true)) === false) ||
// Do not draw the crosshair if this axis is not part of the point
(defined(point) && pick(this.crosshair.snap, true) && (!point.series || point.series[this.isXAxis ? 'xAxis' : 'yAxis'] !== this))
) {
this.hideCrosshair();
} else {
// Get the path
if (!pick(options.snap, true)) {
pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
} else if (defined(point)) {
/*jslint eqeq: true*/
pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY;
/*jslint eqeq: false*/
}
if (this.isRadial) {
path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189
} else {
path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189
}
if (path === null) {
this.hideCrosshair();
return;
}
// Draw the cross
if (this.cross) {
this.cross
.attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation);
} else {
categorized = this.categories && !this.isRadial;
attribs = {
'stroke-width': options.width || (categorized ? this.transA : 1),
stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'),
zIndex: options.zIndex || 2
};
if (options.dashStyle) {
attribs.dashstyle = options.dashStyle;
}
this.cross = this.chart.renderer.path(path).attr(attribs).add();
}
}
},
/**
* Hide the crosshair.
*/
hideCrosshair: function () {
if (this.cross) {
this.cross.hide();
}
}
}; // end Axis
extend(Axis.prototype, AxisPlotLineOrBandExtension);
/**
* Set the tick positions to a time unit that makes sense, for example
* on the first of each month or on every Monday. Return an array
* with the time positions. Used in datetime axes as well as for grouping
* data on a datetime axis.
*
* @param {Object} normalizedInterval The interval in axis values (ms) and the count
* @param {Number} min The minimum in axis values
* @param {Number} max The maximum in axis values
* @param {Number} startOfWeek
*/
Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) {
var tickPositions = [],
i,
higherRanks = {},
useUTC = defaultOptions.global.useUTC,
minYear, // used in months and years as a basis for Date.UTC()
minDate = new Date(min - getTZOffset(min)),
interval = normalizedInterval.unitRange,
count = normalizedInterval.count;
if (defined(min)) { // #1300
minDate.setMilliseconds(interval >= timeUnits.second ? 0 :
count * mathFloor(minDate.getMilliseconds() / count)); // #3652, #3654
if (interval >= timeUnits.second) { // second
minDate.setSeconds(interval >= timeUnits.minute ? 0 :
count * mathFloor(minDate.getSeconds() / count));
}
if (interval >= timeUnits.minute) { // minute
minDate[setMinutes](interval >= timeUnits.hour ? 0 :
count * mathFloor(minDate[getMinutes]() / count));
}
if (interval >= timeUnits.hour) { // hour
minDate[setHours](interval >= timeUnits.day ? 0 :
count * mathFloor(minDate[getHours]() / count));
}
if (interval >= timeUnits.day) { // day
minDate[setDate](interval >= timeUnits.month ? 1 :
count * mathFloor(minDate[getDate]() / count));
}
if (interval >= timeUnits.month) { // month
minDate[setMonth](interval >= timeUnits.year ? 0 :
count * mathFloor(minDate[getMonth]() / count));
minYear = minDate[getFullYear]();
}
if (interval >= timeUnits.year) { // year
minYear -= minYear % count;
minDate[setFullYear](minYear);
}
// week is a special case that runs outside the hierarchy
if (interval === timeUnits.week) {
// get start of current week, independent of count
minDate[setDate](minDate[getDate]() - minDate[getDay]() +
pick(startOfWeek, 1));
}
// get tick positions
i = 1;
if (timezoneOffset || getTimezoneOffset) {
minDate = minDate.getTime();
minDate = new Date(minDate + getTZOffset(minDate));
}
minYear = minDate[getFullYear]();
var time = minDate.getTime(),
minMonth = minDate[getMonth](),
minDateDate = minDate[getDate](),
localTimezoneOffset = (timeUnits.day +
(useUTC ? getTZOffset(minDate) : minDate.getTimezoneOffset() * 60 * 1000)
) % timeUnits.day; // #950, #3359
// iterate and add tick positions at appropriate values
while (time < max) {
tickPositions.push(time);
// if the interval is years, use Date.UTC to increase years
if (interval === timeUnits.year) {
time = makeTime(minYear + i * count, 0);
// if the interval is months, use Date.UTC to increase months
} else if (interval === timeUnits.month) {
time = makeTime(minYear, minMonth + i * count);
// if we're using global time, the interval is not fixed as it jumps
// one hour at the DST crossover
} else if (!useUTC && (interval === timeUnits.day || interval === timeUnits.week)) {
time = makeTime(minYear, minMonth, minDateDate +
i * count * (interval === timeUnits.day ? 1 : 7));
// else, the interval is fixed and we use simple addition
} else {
time += interval * count;
}
i++;
}
// push the last time
tickPositions.push(time);
// mark new days if the time is dividible by day (#1649, #1760)
each(grep(tickPositions, function (time) {
return interval <= timeUnits.hour && time % timeUnits.day === localTimezoneOffset;
}), function (time) {
higherRanks[time] = 'day';
});
}
// record information on the chosen unit - for dynamic label formatter
tickPositions.info = extend(normalizedInterval, {
higherRanks: higherRanks,
totalRange: interval * count
});
return tickPositions;
};
/**
* Get a normalized tick interval for dates. Returns a configuration object with
* unit range (interval), count and name. Used to prepare data for getTimeTicks.
* Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
* of segments in stock charts, the normalizing logic was extracted in order to
* prevent it for running over again for each segment having the same interval.
* #662, #697.
*/
Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) {
var units = unitsOption || [[
'millisecond', // unit name
[1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
], [
'second',
[1, 2, 5, 10, 15, 30]
], [
'minute',
[1, 2, 5, 10, 15, 30]
], [
'hour',
[1, 2, 3, 4, 6, 8, 12]
], [
'day',
[1, 2]
], [
'week',
[1, 2]
], [
'month',
[1, 2, 3, 4, 6]
], [
'year',
null
]],
unit = units[units.length - 1], // default unit is years
interval = timeUnits[unit[0]],
multiples = unit[1],
count,
i;
// loop through the units to find the one that best fits the tickInterval
for (i = 0; i < units.length; i++) {
unit = units[i];
interval = timeUnits[unit[0]];
multiples = unit[1];
if (units[i + 1]) {
// lessThan is in the middle between the highest multiple and the next unit.
var lessThan = (interval * multiples[multiples.length - 1] +
timeUnits[units[i + 1][0]]) / 2;
// break and keep the current unit
if (tickInterval <= lessThan) {
break;
}
}
}
// prevent 2.5 years intervals, though 25, 250 etc. are allowed
if (interval === timeUnits.year && tickInterval < 5 * interval) {
multiples = [1, 2, 5];
}
// get the count
count = normalizeTickInterval(
tickInterval / interval,
multiples,
unit[0] === 'year' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360
);
return {
unitRange: interval,
count: count,
unitName: unit[0]
};
};/**
* Methods defined on the Axis prototype
*/
/**
* Set the tick positions of a logarithmic axis
*/
Axis.prototype.getLogTickPositions = function (interval, min, max, minor) {
var axis = this,
options = axis.options,
axisLength = axis.len,
// Since we use this method for both major and minor ticks,
// use a local variable and return the result
positions = [];
// Reset
if (!minor) {
axis._minorAutoInterval = null;
}
// First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
if (interval >= 0.5) {
interval = mathRound(interval);
positions = axis.getLinearTickPositions(interval, min, max);
// Second case: We need intermediary ticks. For example
// 1, 2, 4, 6, 8, 10, 20, 40 etc.
} else if (interval >= 0.08) {
var roundedMin = mathFloor(min),
intermediate,
i,
j,
len,
pos,
lastPos,
break2;
if (interval > 0.3) {
intermediate = [1, 2, 4];
} else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 4, 6, 8];
} else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
for (i = roundedMin; i < max + 1 && !break2; i++) {
len = intermediate.length;
for (j = 0; j < len && !break2; j++) {
pos = log2lin(lin2log(i) * intermediate[j]);
if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113
positions.push(lastPos);
}
if (lastPos > max) {
break2 = true;
}
lastPos = pos;
}
}
// Third case: We are so deep in between whole logarithmic values that
// we might as well handle the tick positions like a linear axis. For
// example 1.01, 1.02, 1.03, 1.04.
} else {
var realMin = lin2log(min),
realMax = lin2log(max),
tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
interval = pick(
filteredTickIntervalOption,
axis._minorAutoInterval,
(realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
);
interval = normalizeTickInterval(
interval,
null,
getMagnitude(interval)
);
positions = map(axis.getLinearTickPositions(
interval,
realMin,
realMax
), log2lin);
if (!minor) {
axis._minorAutoInterval = interval / 5;
}
}
// Set the axis-level tickInterval variable
if (!minor) {
axis.tickInterval = interval;
}
return positions;
};/**
* The tooltip object
* @param {Object} chart The chart instance
* @param {Object} options Tooltip options
*/
var Tooltip = Highcharts.Tooltip = function () {
this.init.apply(this, arguments);
};
Tooltip.prototype = {
init: function (chart, options) {
var borderWidth = options.borderWidth,
style = options.style,
padding = pInt(style.padding);
// Save the chart and options
this.chart = chart;
this.options = options;
// Keep track of the current series
//this.currentSeries = UNDEFINED;
// List of crosshairs
this.crosshairs = [];
// Current values of x and y when animating
this.now = { x: 0, y: 0 };
// The tooltip is initially hidden
this.isHidden = true;
// create the label
this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip')
.attr({
padding: padding,
fill: options.backgroundColor,
'stroke-width': borderWidth,
r: options.borderRadius,
zIndex: 8
})
.css(style)
.css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
.add()
.attr({ y: -9999 }); // #2301, #2657
// When using canVG the shadow shows up as a gray circle
// even if the tooltip is hidden.
if (!useCanVG) {
this.label.shadow(options.shadow);
}
// Public property for getting the shared state.
this.shared = options.shared;
},
/**
* Destroy the tooltip and its elements.
*/
destroy: function () {
// Destroy and clear local variables
if (this.label) {
this.label = this.label.destroy();
}
clearTimeout(this.hideTimer);
clearTimeout(this.tooltipTimeout);
},
/**
* Provide a soft movement for the tooltip
*
* @param {Number} x
* @param {Number} y
* @private
*/
move: function (x, y, anchorX, anchorY) {
var tooltip = this,
now = tooltip.now,
animate = tooltip.options.animation !== false && !tooltip.isHidden &&
// When we get close to the target position, abort animation and land on the right place (#3056)
(mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1),
skipAnchor = tooltip.followPointer || tooltip.len > 1;
// Get intermediate values for animation
extend(now, {
x: animate ? (2 * now.x + x) / 3 : x,
y: animate ? (now.y + y) / 2 : y,
anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY
});
// Move to the intermediate value
tooltip.label.attr(now);
// Run on next tick of the mouse tracker
if (animate) {
// Never allow two timeouts
clearTimeout(this.tooltipTimeout);
// Set the fixed interval ticking for the smooth tooltip
this.tooltipTimeout = setTimeout(function () {
// The interval function may still be running during destroy, so check that the chart is really there before calling.
if (tooltip) {
tooltip.move(x, y, anchorX, anchorY);
}
}, 32);
}
},
/**
* Hide the tooltip
*/
hide: function (delay) {
var tooltip = this,
hoverPoints;
clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
if (!this.isHidden) {
hoverPoints = this.chart.hoverPoints;
this.hideTimer = setTimeout(function () {
tooltip.label.fadeOut();
tooltip.isHidden = true;
}, pick(delay, this.options.hideDelay, 500));
// hide previous hoverPoints and set new
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
this.chart.hoverPoints = null;
this.chart.hoverSeries = null;
}
},
/**
* Extendable method to get the anchor position of the tooltip
* from a point or set of points
*/
getAnchor: function (points, mouseEvent) {
var ret,
chart = this.chart,
inverted = chart.inverted,
plotTop = chart.plotTop,
plotLeft = chart.plotLeft,
plotX = 0,
plotY = 0,
yAxis,
xAxis;
points = splat(points);
// Pie uses a special tooltipPos
ret = points[0].tooltipPos;
// When tooltip follows mouse, relate the position to the mouse
if (this.followPointer && mouseEvent) {
if (mouseEvent.chartX === UNDEFINED) {
mouseEvent = chart.pointer.normalize(mouseEvent);
}
ret = [
mouseEvent.chartX - chart.plotLeft,
mouseEvent.chartY - plotTop
];
}
// When shared, use the average position
if (!ret) {
each(points, function (point) {
yAxis = point.series.yAxis;
xAxis = point.series.xAxis;
plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0);
plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
(!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
});
plotX /= points.length;
plotY /= points.length;
ret = [
inverted ? chart.plotWidth - plotY : plotX,
this.shared && !inverted && points.length > 1 && mouseEvent ?
mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
inverted ? chart.plotHeight - plotX : plotY
];
}
return map(ret, mathRound);
},
/**
* Place the tooltip in a chart without spilling over
* and not covering the point it self.
*/
getPosition: function (boxWidth, boxHeight, point) {
var chart = this.chart,
distance = this.distance,
ret = {},
swapped,
first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop],
second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft],
// The far side is right or bottom
preferFarSide = pick(point.ttBelow, (chart.inverted && !point.negative) || (!chart.inverted && point.negative)),
/**
* Handle the preferred dimension. When the preferred dimension is tooltip
* on top or bottom of the point, it will look for space there.
*/
firstDimension = function (dim, outerSize, innerSize, point) {
var roomLeft = innerSize < point - distance,
roomRight = point + distance + innerSize < outerSize,
alignedLeft = point - distance - innerSize,
alignedRight = point + distance;
if (preferFarSide && roomRight) {
ret[dim] = alignedRight;
} else if (!preferFarSide && roomLeft) {
ret[dim] = alignedLeft;
} else if (roomLeft) {
ret[dim] = alignedLeft;
} else if (roomRight) {
ret[dim] = alignedRight;
} else {
return false;
}
},
/**
* Handle the secondary dimension. If the preferred dimension is tooltip
* on top or bottom of the point, the second dimension is to align the tooltip
* above the point, trying to align center but allowing left or right
* align within the chart box.
*/
secondDimension = function (dim, outerSize, innerSize, point) {
// Too close to the edge, return false and swap dimensions
if (point < distance || point > outerSize - distance) {
return false;
// Align left/top
} else if (point < innerSize / 2) {
ret[dim] = 1;
// Align right/bottom
} else if (point > outerSize - innerSize / 2) {
ret[dim] = outerSize - innerSize - 2;
// Align center
} else {
ret[dim] = point - innerSize / 2;
}
},
/**
* Swap the dimensions
*/
swap = function (count) {
var temp = first;
first = second;
second = temp;
swapped = count;
},
run = function () {
if (firstDimension.apply(0, first) !== false) {
if (secondDimension.apply(0, second) === false && !swapped) {
swap(true);
run();
}
} else if (!swapped) {
swap(true);
run();
} else {
ret.x = ret.y = 0;
}
};
// Under these conditions, prefer the tooltip on the side of the point
if (chart.inverted || this.len > 1) {
swap();
}
run();
return ret;
},
/**
* In case no user defined formatter is given, this will be used. Note that the context
* here is an object holding point, series, x, y etc.
*/
defaultFormatter: function (tooltip) {
var items = this.points || splat(this),
s;
// build the header
s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header
// build the values
s = s.concat(tooltip.bodyFormatter(items));
// footer
s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header
return s.join('');
},
/**
* Refresh the tooltip's text and position.
* @param {Object} point
*/
refresh: function (point, mouseEvent) {
var tooltip = this,
chart = tooltip.chart,
label = tooltip.label,
options = tooltip.options,
x,
y,
anchor,
textConfig = {},
text,
pointConfig = [],
formatter = options.formatter || tooltip.defaultFormatter,
hoverPoints = chart.hoverPoints,
borderColor,
shared = tooltip.shared,
currentSeries;
clearTimeout(this.hideTimer);
// get the reference point coordinates (pie charts use tooltipPos)
tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
anchor = tooltip.getAnchor(point, mouseEvent);
x = anchor[0];
y = anchor[1];
// shared tooltip, array is sent over
if (shared && !(point.series && point.series.noSharedTooltip)) {
// hide previous hoverPoints and set new
chart.hoverPoints = point;
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
each(point, function (item) {
item.setState(HOVER_STATE);
pointConfig.push(item.getLabelConfig());
});
textConfig = {
x: point[0].category,
y: point[0].y
};
textConfig.points = pointConfig;
this.len = pointConfig.length;
point = point[0];
// single point tooltip
} else {
textConfig = point.getLabelConfig();
}
text = formatter.call(textConfig, tooltip);
// register the current series
currentSeries = point.series;
this.distance = pick(currentSeries.tooltipOptions.distance, 16);
// update the inner HTML
if (text === false) {
this.hide();
} else {
// show it
if (tooltip.isHidden) {
stop(label);
label.attr('opacity', 1).show();
}
// update text
label.attr({
text: text
});
// set the stroke color of the box
borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
label.attr({
stroke: borderColor
});
tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow });
this.isHidden = false;
}
fireEvent(chart, 'tooltipRefresh', {
text: text,
x: x + chart.plotLeft,
y: y + chart.plotTop,
borderColor: borderColor
});
},
/**
* Find the new position and perform the move
*/
updatePosition: function (point) {
var chart = this.chart,
label = this.label,
pos = (this.options.positioner || this.getPosition).call(
this,
label.width,
label.height,
point
);
// do the move
this.move(
mathRound(pos.x),
mathRound(pos.y),
point.plotX + chart.plotLeft,
point.plotY + chart.plotTop
);
},
/**
* Get the best X date format based on the closest point range on the axis.
*/
getXDateFormat: function (point, options, xAxis) {
var xDateFormat,
dateTimeLabelFormats = options.dateTimeLabelFormats,
closestPointRange = xAxis && xAxis.closestPointRange,
n,
blank = '01-01 00:00:00.000',
strpos = {
millisecond: 15,
second: 12,
minute: 9,
hour: 6,
day: 3
},
date,
lastN;
if (closestPointRange) {
date = dateFormat('%m-%d %H:%M:%S.%L', point.x);
for (n in timeUnits) {
// If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format
if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek &&
date.substr(6) === blank.substr(6)) {
n = 'week';
break;
// The first format that is too great for the range
} else if (timeUnits[n] > closestPointRange) {
n = lastN;
break;
// If the point is placed every day at 23:59, we need to show
// the minutes as well. #2637.
} else if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) {
break;
}
// Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition
if (n !== 'week') {
lastN = n;
}
}
if (n) {
xDateFormat = dateTimeLabelFormats[n];
}
} else {
xDateFormat = dateTimeLabelFormats.day;
}
return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581
},
/**
* Format the footer/header of the tooltip
* #3397: abstraction to enable formatting of footer and header
*/
tooltipFooterHeaderFormatter: function (point, isFooter) {
var footOrHead = isFooter ? 'footer' : 'header',
series = point.series,
tooltipOptions = series.tooltipOptions,
xDateFormat = tooltipOptions.xDateFormat,
xAxis = series.xAxis,
isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key),
formatString = tooltipOptions[footOrHead+'Format'];
// Guess the best date format based on the closest point distance (#568, #3418)
if (isDateTime && !xDateFormat) {
xDateFormat = this.getXDateFormat(point, tooltipOptions, xAxis);
}
// Insert the footer date format if any
if (isDateTime && xDateFormat) {
formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}');
}
return format(formatString, {
point: point,
series: series
});
},
/**
* Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item,
* abstracting this functionality allows to easily overwrite and extend it.
*/
bodyFormatter: function (items) {
return map(items, function (item) {
var tooltipOptions = item.series.tooltipOptions;
return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat);
});
}
};
var hoverChartIndex;
// Global flag for touch support
hasTouch = doc.documentElement.ontouchstart !== UNDEFINED;
/**
* The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
* Subsequent methods should be named differently from what they are doing.
* @param {Object} chart The Chart instance
* @param {Object} options The root options object
*/
var Pointer = Highcharts.Pointer = function (chart, options) {
this.init(chart, options);
};
Pointer.prototype = {
/**
* Initialize Pointer
*/
init: function (chart, options) {
var chartOptions = options.chart,
chartEvents = chartOptions.events,
zoomType = useCanVG ? '' : chartOptions.zoomType,
inverted = chart.inverted,
zoomX,
zoomY;
// Store references
this.options = options;
this.chart = chart;
// Zoom status
this.zoomX = zoomX = /x/.test(zoomType);
this.zoomY = zoomY = /y/.test(zoomType);
this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
this.hasZoom = zoomX || zoomY;
// Do we need to handle click on a touch device?
this.runChartClick = chartEvents && !!chartEvents.click;
this.pinchDown = [];
this.lastValidTouch = {};
if (Highcharts.Tooltip && options.tooltip.enabled) {
chart.tooltip = new Tooltip(chart, options.tooltip);
this.followTouchMove = pick(options.tooltip.followTouchMove, true);
}
this.setDOMEvents();
},
/**
* Add crossbrowser support for chartX and chartY
* @param {Object} e The event object in standard browsers
*/
normalize: function (e, chartPosition) {
var chartX,
chartY,
ePos;
// common IE normalizing
e = e || window.event;
// Framework specific normalizing (#1165)
e = washMouseEvent(e);
// More IE normalizing, needs to go after washMouseEvent
if (!e.target) {
e.target = e.srcElement;
}
// iOS (#2757)
ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e;
// Get mouse position
if (!chartPosition) {
this.chartPosition = chartPosition = offset(this.chart.container);
}
// chartX and chartY
if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
// for IE10 quirks mode within framesets
chartY = e.y;
} else {
chartX = ePos.pageX - chartPosition.left;
chartY = ePos.pageY - chartPosition.top;
}
return extend(e, {
chartX: mathRound(chartX),
chartY: mathRound(chartY)
});
},
/**
* Get the click position in terms of axis values.
*
* @param {Object} e A pointer event
*/
getCoordinates: function (e) {
var coordinates = {
xAxis: [],
yAxis: []
};
each(this.chart.axes, function (axis) {
coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
axis: axis,
value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
});
});
return coordinates;
},
/**
* With line type charts with a single tracker, get the point closest to the mouse.
* Run Point.onMouseOver and display tooltip for the point or points.
*/
runPointActions: function (e) {
var pointer = this,
chart = pointer.chart,
series = chart.series,
tooltip = chart.tooltip,
shared = tooltip ? tooltip.shared : false,
followPointer,
//point,
//points,
hoverPoint = chart.hoverPoint,
hoverSeries = chart.hoverSeries,
i,
trueXkd,
trueX,
//j,
distance = chart.chartWidth,
rdistance = chart.chartWidth,
anchor,
noSharedTooltip,
kdpoints = [],
kdpoint;
// For hovering over the empty parts of the plot area (hoverSeries is undefined).
// If there is one series with point tracking (combo chart), don't go to nearest neighbour.
if (!shared && !hoverSeries) {
for (i = 0; i < series.length; i++) {
if (series[i].directTouch || !series[i].options.stickyTracking) {
series = [];
}
}
}
if (!(hoverSeries && hoverSeries.noSharedTooltip) && (shared || !hoverSeries)) { // #3821
// Find nearest points on all series
each(series, function (s) {
// Skip hidden series
noSharedTooltip = s.noSharedTooltip && shared;
if (s.visible && !noSharedTooltip && pick(s.options.enableMouseTracking, true)) { // #3821
kdpoints.push(s.searchPoint(e));
}
});
// Find absolute nearest point
each(kdpoints, function (p) {
if (p && defined(p.plotX) && defined(p.plotY)) {
if ((p.dist.distX < distance) || ((p.dist.distX === distance || p.series.kdDimensions > 1) && p.dist.distR < rdistance)) {
distance = p.dist.distX;
rdistance = p.dist.distR;
kdpoint = p;
}
}
//point = kdpoints[0];
});
} else {
kdpoint = hoverSeries ? hoverSeries.searchPoint(e) : UNDEFINED;
}
// Refresh tooltip for kdpoint
if (kdpoint && tooltip && kdpoint !== hoverPoint) {
// Draw tooltip if necessary
if (shared && !kdpoint.series.noSharedTooltip) {
i = kdpoints.length;
trueXkd = kdpoint.plotX + kdpoint.series.xAxis.left;
while (i--) {
trueX = kdpoints[i].plotX + kdpoints[i].series.xAxis.left;
if (kdpoints[i].x !== kdpoint.x || trueX !== trueXkd || !defined(kdpoints[i].y) || (kdpoints[i].series.noSharedTooltip || false)) {
kdpoints.splice(i, 1);
}
}
tooltip.refresh(kdpoints, e);
each(kdpoints, function (point) {
point.onMouseOver(e);
});
} else {
tooltip.refresh(kdpoint, e);
kdpoint.onMouseOver(e);
}
// Update positions (regardless of kdpoint or hoverPoint)
} else {
followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer;
if (tooltip && followPointer && !tooltip.isHidden) {
anchor = tooltip.getAnchor([{}], e);
tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
}
}
// Crosshair
each(chart.axes, function (axis) {
axis.drawCrosshair(e, pick(kdpoint, hoverPoint));
});
},
/**
* Reset the tracking by hiding the tooltip, the hover series state and the hover point
*
* @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
*/
reset: function (allowMove, delay) {
var pointer = this,
chart = pointer.chart,
hoverSeries = chart.hoverSeries,
hoverPoint = chart.hoverPoint,
tooltip = chart.tooltip,
tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint;
// Narrow in allowMove
allowMove = allowMove && tooltip && tooltipPoints;
// Check if the points have moved outside the plot area, #1003
if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
allowMove = false;
}
// Just move the tooltip, #349
if (allowMove) {
tooltip.refresh(tooltipPoints);
if (hoverPoint) { // #2500
hoverPoint.setState(hoverPoint.state, true);
each(chart.axes, function (axis) {
if (pick(axis.options.crosshair && axis.options.crosshair.snap, true)) {
axis.drawCrosshair(null, allowMove);
} else {
axis.hideCrosshair();
}
});
}
// Full reset
} else {
if (hoverPoint) {
hoverPoint.onMouseOut();
}
if (hoverSeries) {
hoverSeries.onMouseOut();
}
if (tooltip) {
tooltip.hide(delay);
}
if (pointer._onDocumentMouseMove) {
removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
pointer._onDocumentMouseMove = null;
}
// Remove crosshairs
each(chart.axes, function (axis) {
axis.hideCrosshair();
});
pointer.hoverX = null;
}
},
/**
* Scale series groups to a certain scale and translation
*/
scaleGroups: function (attribs, clip) {
var chart = this.chart,
seriesAttribs;
// Scale each series
each(chart.series, function (series) {
seriesAttribs = attribs || series.getPlotBox(); // #1701
if (series.xAxis && series.xAxis.zoomEnabled) {
series.group.attr(seriesAttribs);
if (series.markerGroup) {
series.markerGroup.attr(seriesAttribs);
series.markerGroup.clip(clip ? chart.clipRect : null);
}
if (series.dataLabelsGroup) {
series.dataLabelsGroup.attr(seriesAttribs);
}
}
});
// Clip
chart.clipRect.attr(clip || chart.clipBox);
},
/**
* Start a drag operation
*/
dragStart: function (e) {
var chart = this.chart;
// Record the start position
chart.mouseIsDown = e.type;
chart.cancelClick = false;
chart.mouseDownX = this.mouseDownX = e.chartX;
chart.mouseDownY = this.mouseDownY = e.chartY;
},
/**
* Perform a drag operation in response to a mousemove event while the mouse is down
*/
drag: function (e) {
var chart = this.chart,
chartOptions = chart.options.chart,
chartX = e.chartX,
chartY = e.chartY,
zoomHor = this.zoomHor,
zoomVert = this.zoomVert,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
clickedInside,
size,
mouseDownX = this.mouseDownX,
mouseDownY = this.mouseDownY,
panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key'];
// If the mouse is outside the plot area, adjust to cooordinates
// inside to prevent the selection marker from going outside
if (chartX < plotLeft) {
chartX = plotLeft;
} else if (chartX > plotLeft + plotWidth) {
chartX = plotLeft + plotWidth;
}
if (chartY < plotTop) {
chartY = plotTop;
} else if (chartY > plotTop + plotHeight) {
chartY = plotTop + plotHeight;
}
// determine if the mouse has moved more than 10px
this.hasDragged = Math.sqrt(
Math.pow(mouseDownX - chartX, 2) +
Math.pow(mouseDownY - chartY, 2)
);
if (this.hasDragged > 10) {
clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
// make a selection
if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) {
if (!this.selectionMarker) {
this.selectionMarker = chart.renderer.rect(
plotLeft,
plotTop,
zoomHor ? 1 : plotWidth,
zoomVert ? 1 : plotHeight,
0
)
.attr({
fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
zIndex: 7
})
.add();
}
}
// adjust the width of the selection marker
if (this.selectionMarker && zoomHor) {
size = chartX - mouseDownX;
this.selectionMarker.attr({
width: mathAbs(size),
x: (size > 0 ? 0 : size) + mouseDownX
});
}
// adjust the height of the selection marker
if (this.selectionMarker && zoomVert) {
size = chartY - mouseDownY;
this.selectionMarker.attr({
height: mathAbs(size),
y: (size > 0 ? 0 : size) + mouseDownY
});
}
// panning
if (clickedInside && !this.selectionMarker && chartOptions.panning) {
chart.pan(e, chartOptions.panning);
}
}
},
/**
* On mouse up or touch end across the entire document, drop the selection.
*/
drop: function (e) {
var pointer = this,
chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
xAxis: [],
yAxis: [],
originalEvent: e.originalEvent || e
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function (axis) {
if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569
var horiz = axis.horiz,
minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
selectionData[axis.coll].push({
axis: axis,
min: mathMin(selectionMin, selectionMax), // for reversed axes
max: mathMax(selectionMin, selectionMax)
});
runZoom = true;
}
});
if (runZoom) {
fireEvent(chart, 'selection', selectionData, function (args) {
chart.zoom(extend(args, hasPinched ? { animation: false } : null));
});
}
}
this.selectionMarker = this.selectionMarker.destroy();
// Reset scaling preview
if (hasPinched) {
this.scaleGroups();
}
}
// Reset all
if (chart) { // it may be destroyed on mouse up - #877
css(chart.container, { cursor: chart._cursor });
chart.cancelClick = this.hasDragged > 10; // #370
chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
this.pinchDown = [];
}
},
onContainerMouseDown: function (e) {
e = this.normalize(e);
// issue #295, dragging not always working in Firefox
if (e.preventDefault) {
e.preventDefault();
}
this.dragStart(e);
},
onDocumentMouseUp: function (e) {
if (charts[hoverChartIndex]) {
charts[hoverChartIndex].pointer.drop(e);
}
},
/**
* Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
* Issue #149 workaround. The mouseleave event does not always fire.
*/
onDocumentMouseMove: function (e) {
var chart = this.chart,
chartPosition = this.chartPosition,
hoverSeries = chart.hoverSeries;
e = this.normalize(e, chartPosition);
// If we're outside, hide the tooltip
if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') &&
!chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
this.reset();
}
},
/**
* When mouse leaves the container, hide the tooltip.
*/
onContainerMouseLeave: function () {
var chart = charts[hoverChartIndex];
if (chart) {
chart.pointer.reset();
chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
}
},
// The mousemove, touchmove and touchstart event handler
onContainerMouseMove: function (e) {
var chart = this.chart;
hoverChartIndex = chart.index;
e = this.normalize(e);
e.returnValue = false; // #2251, #3224
if (chart.mouseIsDown === 'mousedown') {
this.drag(e);
}
// Show the tooltip and run mouse over events (#977)
if ((this.inClass(e.target, 'highcharts-tracker') ||
chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
this.runPointActions(e);
}
},
/**
* Utility to detect whether an element has, or has a parent with, a specific
* class name. Used on detection of tracker objects and on deciding whether
* hovering the tooltip should cause the active series to mouse out.
*/
inClass: function (element, className) {
var elemClassName;
while (element) {
elemClassName = attr(element, 'class');
if (elemClassName) {
if (elemClassName.indexOf(className) !== -1) {
return true;
} else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
return false;
}
}
element = element.parentNode;
}
},
onTrackerMouseOut: function (e) {
var series = this.chart.hoverSeries,
relatedTarget = e.relatedTarget || e.toElement,
relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499
if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') &&
relatedSeries !== series) {
series.onMouseOut();
}
},
onContainerClick: function (e) {
var chart = this.chart,
hoverPoint = chart.hoverPoint,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop;
e = this.normalize(e);
e.cancelBubble = true; // IE specific
if (!chart.cancelClick) {
// On tracker click, fire the series and point events. #783, #1583
if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
// the series click event
fireEvent(hoverPoint.series, 'click', extend(e, {
point: hoverPoint
}));
// the point click event
if (chart.hoverPoint) { // it may be destroyed (#1844)
hoverPoint.firePointEvent('click', e);
}
// When clicking outside a tracker, fire a chart event
} else {
extend(e, this.getCoordinates(e));
// fire a click event in the chart
if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
fireEvent(chart, 'click', e);
}
}
}
},
/**
* Set the JS DOM events on the container and document. This method should contain
* a one-to-one assignment between methods and their handlers. Any advanced logic should
* be moved to the handler reflecting the event's name.
*/
setDOMEvents: function () {
var pointer = this,
container = pointer.chart.container;
container.onmousedown = function (e) {
pointer.onContainerMouseDown(e);
};
container.onmousemove = function (e) {
pointer.onContainerMouseMove(e);
};
container.onclick = function (e) {
pointer.onContainerClick(e);
};
addEvent(container, 'mouseleave', pointer.onContainerMouseLeave);
if (chartCount === 1) {
addEvent(doc, 'mouseup', pointer.onDocumentMouseUp);
}
if (hasTouch) {
container.ontouchstart = function (e) {
pointer.onContainerTouchStart(e);
};
container.ontouchmove = function (e) {
pointer.onContainerTouchMove(e);
};
if (chartCount === 1) {
addEvent(doc, 'touchend', pointer.onDocumentTouchEnd);
}
}
},
/**
* Destroys the Pointer object and disconnects DOM events.
*/
destroy: function () {
var prop;
removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave);
if (!chartCount) {
removeEvent(doc, 'mouseup', this.onDocumentMouseUp);
removeEvent(doc, 'touchend', this.onDocumentTouchEnd);
}
// memory and CPU leak
clearInterval(this.tooltipTimeout);
for (prop in this) {
this[prop] = null;
}
}
};
/* Support for touch devices */
extend(Highcharts.Pointer.prototype, {
/**
* Run translation operations
*/
pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (this.zoomHor || this.pinchHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (this.zoomVert || this.pinchVert) {
this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
},
/**
* Run translation operations for each direction (horizontal and vertical) independently
*/
pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) {
var chart = this.chart,
xy = horiz ? 'x' : 'y',
XY = horiz ? 'X' : 'Y',
sChartXY = 'chart' + XY,
wh = horiz ? 'width' : 'height',
plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
selectionWH,
selectionXY,
clipXY,
scale = forcedScale || 1,
inverted = chart.inverted,
bounds = chart.bounds[horiz ? 'h' : 'v'],
singleTouch = pinchDown.length === 1,
touch0Start = pinchDown[0][sChartXY],
touch0Now = touches[0][sChartXY],
touch1Start = !singleTouch && pinchDown[1][sChartXY],
touch1Now = !singleTouch && touches[1][sChartXY],
outOfBounds,
transformScale,
scaleKey,
setScale = function () {
if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
}
clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
};
// Set the scale, first pass
setScale();
selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
// Out of bounds
if (selectionXY < bounds.min) {
selectionXY = bounds.min;
outOfBounds = true;
} else if (selectionXY + selectionWH > bounds.max) {
selectionXY = bounds.max - selectionWH;
outOfBounds = true;
}
// Is the chart dragged off its bounds, determined by dataMin and dataMax?
if (outOfBounds) {
// Modify the touchNow position in order to create an elastic drag movement. This indicates
// to the user that the chart is responsive but can't be dragged further.
touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
if (!singleTouch) {
touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
}
// Set the scale, second pass to adapt to the modified touchNow positions
setScale();
} else {
lastValidTouch[xy] = [touch0Now, touch1Now];
}
// Set geometry for clipping, selection and transformation
if (!inverted) { // TODO: implement clipping for inverted charts
clip[xy] = clipXY - plotLeftTop;
clip[wh] = selectionWH;
}
scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
transformScale = inverted ? 1 / scale : scale;
selectionMarker[wh] = selectionWH;
selectionMarker[xy] = selectionXY;
transform[scaleKey] = scale;
transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
},
/**
* Handle touch events with two touches
*/
pinch: function (e) {
var self = this,
chart = self.chart,
pinchDown = self.pinchDown,
touches = e.touches,
touchesLength = touches.length,
lastValidTouch = self.lastValidTouch,
hasZoom = self.hasZoom,
selectionMarker = self.selectionMarker,
transform = {},
fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
chart.runTrackerClick) || self.runChartClick),
clip = {};
// On touch devices, only proceed to trigger click if a handler is defined
if (hasZoom && !fireClickEvent) {
e.preventDefault();
}
// Normalize each touch
map(touches, function (e) {
return self.normalize(e);
});
// Register the touch start position
if (e.type === 'touchstart') {
each(touches, function (e, i) {
pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
});
lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
// Identify the data bounds in pixels
each(chart.axes, function (axis) {
if (axis.zoomEnabled) {
var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
minPixelPadding = axis.minPixelPadding,
min = axis.toPixels(pick(axis.options.min, axis.dataMin)),
max = axis.toPixels(pick(axis.options.max, axis.dataMax)),
absMin = mathMin(min, max),
absMax = mathMax(min, max);
// Store the bounds for use in the touchmove handler
bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
}
});
self.res = true; // reset on next move
// Event type is touchmove, handle panning and pinching
} else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
// Set the marker
if (!selectionMarker) {
self.selectionMarker = selectionMarker = extend({
destroy: noop
}, chart.plotBox);
}
self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
self.hasPinched = hasZoom;
// Scale and translate the groups to provide visual feedback during pinching
self.scaleGroups(transform, clip);
// Optionally move the tooltip on touchmove
if (!hasZoom && self.followTouchMove && touchesLength === 1) {
this.runPointActions(self.normalize(e));
} else if (self.res) {
self.res = false;
this.reset(false, 0);
}
}
},
onContainerTouchStart: function (e) {
var chart = this.chart;
hoverChartIndex = chart.index;
if (e.touches.length === 1) {
e = this.normalize(e);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) {
// Run mouse events and display tooltip etc
this.runPointActions(e);
this.pinch(e);
} else {
// Hide the tooltip on touching outside the plot area (#1203)
this.reset();
}
} else if (e.touches.length === 2) {
this.pinch(e);
}
},
onContainerTouchMove: function (e) {
if (e.touches.length === 1 || e.touches.length === 2) {
this.pinch(e);
}
},
onDocumentTouchEnd: function (e) {
if (charts[hoverChartIndex]) {
charts[hoverChartIndex].pointer.drop(e);
}
}
});
if (win.PointerEvent || win.MSPointerEvent) {
// The touches object keeps track of the points being touched at all times
var touches = {},
hasPointerEvent = !!win.PointerEvent,
getWebkitTouches = function () {
var key, fake = [];
fake.item = function (i) { return this[i]; };
for (key in touches) {
if (touches.hasOwnProperty(key)) {
fake.push({
pageX: touches[key].pageX,
pageY: touches[key].pageY,
target: touches[key].target
});
}
}
return fake;
},
translateMSPointer = function (e, method, wktype, callback) {
var p;
e = e.originalEvent || e;
if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) {
callback(e);
p = charts[hoverChartIndex].pointer;
p[method]({
type: wktype,
target: e.currentTarget,
preventDefault: noop,
touches: getWebkitTouches()
});
}
};
/**
* Extend the Pointer prototype with methods for each event handler and more
*/
extend(Pointer.prototype, {
onContainerPointerDown: function (e) {
translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) {
touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget };
});
},
onContainerPointerMove: function (e) {
translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) {
touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY };
if (!touches[e.pointerId].target) {
touches[e.pointerId].target = e.currentTarget;
}
});
},
onDocumentPointerUp: function (e) {
translateMSPointer(e, 'onContainerTouchEnd', 'touchend', function (e) {
delete touches[e.pointerId];
});
},
/**
* Add or remove the MS Pointer specific events
*/
batchMSEvents: function (fn) {
fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
}
});
// Disable default IE actions for pinch and such on chart element
wrap(Pointer.prototype, 'init', function (proceed, chart, options) {
proceed.call(this, chart, options);
if (this.hasZoom || this.followTouchMove) {
css(chart.container, {
'-ms-touch-action': NONE,
'touch-action': NONE
});
}
});
// Add IE specific touch events to chart
wrap(Pointer.prototype, 'setDOMEvents', function (proceed) {
proceed.apply(this);
if (this.hasZoom || this.followTouchMove) {
this.batchMSEvents(addEvent);
}
});
// Destroy MS events also
wrap(Pointer.prototype, 'destroy', function (proceed) {
this.batchMSEvents(removeEvent);
proceed.call(this);
});
}
/**
* The overview of the chart's series
*/
var Legend = Highcharts.Legend = function (chart, options) {
this.init(chart, options);
};
Legend.prototype = {
/**
* Initialize the legend
*/
init: function (chart, options) {
var legend = this,
itemStyle = options.itemStyle,
padding,
itemMarginTop = options.itemMarginTop || 0;
this.options = options;
if (!options.enabled) {
return;
}
legend.itemStyle = itemStyle;
legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
legend.itemMarginTop = itemMarginTop;
legend.padding = padding = pick(options.padding, 8);
legend.initialItemX = padding;
legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
legend.maxItemWidth = 0;
legend.chart = chart;
legend.itemHeight = 0;
legend.symbolWidth = pick(options.symbolWidth, 16);
legend.pages = [];
// Render it
legend.render();
// move checkboxes
addEvent(legend.chart, 'endResize', function () {
legend.positionCheckboxes();
});
},
/**
* Set the colors for the legend item
* @param {Object} item A Series or Point instance
* @param {Object} visible Dimmed or colored
*/
colorizeItem: function (item, visible) {
var legend = this,
options = legend.options,
legendItem = item.legendItem,
legendLine = item.legendLine,
legendSymbol = item.legendSymbol,
hiddenColor = legend.itemHiddenStyle.color,
textColor = visible ? options.itemStyle.color : hiddenColor,
symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor,
markerOptions = item.options && item.options.marker,
symbolAttr = { fill: symbolColor },
key,
val;
if (legendItem) {
legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
}
if (legendLine) {
legendLine.attr({ stroke: symbolColor });
}
if (legendSymbol) {
// Apply marker options
if (markerOptions && legendSymbol.isMarker) { // #585
symbolAttr.stroke = symbolColor;
markerOptions = item.convertAttribs(markerOptions);
for (key in markerOptions) {
val = markerOptions[key];
if (val !== UNDEFINED) {
symbolAttr[key] = val;
}
}
}
legendSymbol.attr(symbolAttr);
}
},
/**
* Position the legend item
* @param {Object} item A Series or Point instance
*/
positionItem: function (item) {
var legend = this,
options = legend.options,
symbolPadding = options.symbolPadding,
ltr = !options.rtl,
legendItemPos = item._legendItemPos,
itemX = legendItemPos[0],
itemY = legendItemPos[1],
checkbox = item.checkbox;
if (item.legendGroup) {
item.legendGroup.translate(
ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
itemY
);
}
if (checkbox) {
checkbox.x = itemX;
checkbox.y = itemY;
}
},
/**
* Destroy a single legend item
* @param {Object} item The series or point
*/
destroyItem: function (item) {
var checkbox = item.checkbox;
// destroy SVG elements
each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
if (checkbox) {
discardElement(item.checkbox);
}
},
/**
* Destroys the legend.
*/
destroy: function () {
var legend = this,
legendGroup = legend.group,
box = legend.box;
if (box) {
legend.box = box.destroy();
}
if (legendGroup) {
legend.group = legendGroup.destroy();
}
},
/**
* Position the checkboxes after the width is determined
*/
positionCheckboxes: function (scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function (item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
css(checkbox, {
left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX,
top: top + PX,
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
});
}
});
}
},
/**
* Render the legend title on top of the legend
*/
renderTitle: function () {
var options = this.options,
padding = this.padding,
titleOptions = options.title,
titleHeight = 0,
bBox;
if (titleOptions.text) {
if (!this.title) {
this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
.attr({ zIndex: 1 })
.css(titleOptions.style)
.add(this.group);
}
bBox = this.title.getBBox();
titleHeight = bBox.height;
this.offsetWidth = bBox.width; // #1717
this.contentGroup.attr({ translateY: titleHeight });
}
this.titleHeight = titleHeight;
},
/**
* Render a single specific legend item
* @param {Object} item A series or point
*/
renderItem: function (item) {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
options = legend.options,
horizontal = options.layout === 'horizontal',
symbolWidth = legend.symbolWidth,
symbolPadding = options.symbolPadding,
itemStyle = legend.itemStyle,
itemHiddenStyle = legend.itemHiddenStyle,
padding = legend.padding,
itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
ltr = !options.rtl,
itemHeight,
widthOption = options.width,
itemMarginBottom = options.itemMarginBottom || 0,
itemMarginTop = legend.itemMarginTop,
initialItemX = legend.initialItemX,
bBox,
itemWidth,
li = item.legendItem,
series = item.series && item.series.drawLegendSymbol ? item.series : item,
seriesOptions = series.options,
showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
useHTML = options.useHTML;
if (!li) { // generate it once, later move it
// Generate the group box
// A group to hold the symbol and text. Text is to be appended in Legend class.
item.legendGroup = renderer.g('legend-item')
.attr({ zIndex: 1 })
.add(legend.scrollGroup);
// Generate the list item text and add it to the group
item.legendItem = li = renderer.text(
options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
ltr ? symbolWidth + symbolPadding : -symbolPadding,
legend.baseline || 0,
useHTML
)
.css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
.attr({
align: ltr ? 'left' : 'right',
zIndex: 2
})
.add(item.legendGroup);
// Get the baseline for the first item - the font size is equal for all
if (!legend.baseline) {
legend.baseline = renderer.fontMetrics(itemStyle.fontSize, li).f + 3 + itemMarginTop;
li.attr('y', legend.baseline);
}
// Draw the legend symbol inside the group box
series.drawLegendSymbol(legend, item);
if (legend.setItemEvents) {
legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle);
}
// Colorize the items
legend.colorizeItem(item, item.visible);
// add the HTML checkbox on top
if (showCheckbox) {
legend.createCheckboxForItem(item);
}
}
// calculate the positions for the next line
bBox = li.getBBox();
itemWidth = item.checkboxOffset =
options.itemWidth ||
item.legendItemWidth ||
symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height);
// if the item exceeds the width, start a new line
if (horizontal && legend.itemX - initialItemX + itemWidth >
(widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
legend.itemX = initialItemX;
legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
}
// If the item exceeds the height, start a new column
/*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
legend.itemY = legend.initialItemY;
legend.itemX += legend.maxItemWidth;
legend.maxItemWidth = 0;
}*/
// Set the edge positions
legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
// cache the position of the newly generated or reordered items
item._legendItemPos = [legend.itemX, legend.itemY];
// advance
if (horizontal) {
legend.itemX += itemWidth;
} else {
legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
legend.lastLineHeight = itemHeight;
}
// the width of the widest item
legend.offsetWidth = widthOption || mathMax(
(horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
legend.offsetWidth
);
},
/**
* Get all items, which is one item per series for normal series and one item per point
* for pie series.
*/
getAllItems: function () {
var allItems = [];
each(this.chart.series, function (series) {
var seriesOptions = series.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
return;
}
// use points or series for the legend item depending on legendType
allItems = allItems.concat(
series.legendItems ||
(seriesOptions.legendType === 'point' ?
series.data :
series)
);
});
return allItems;
},
/**
* Adjust the chart margins by reserving space for the legend on only one side
* of the chart. If the position is set to a corner, top or bottom is reserved
* for horizontal legends and left or right for vertical ones.
*/
adjustMargins: function (margin, spacing) {
var chart = this.chart,
options = this.options,
// Use the first letter of each alignment option in order to detect the side
alignment = options.align[0] + options.verticalAlign[0] + options.layout[0];
if (this.display && !options.floating) {
each([
/(lth|ct|rth)/,
/(rtv|rm|rbv)/,
/(rbh|cb|lbh)/,
/(lbv|lm|ltv)/
], function (alignments, side) {
if (alignments.test(alignment) && !defined(margin[side])) {
// Now we have detected on which side of the chart we should reserve space for the legend
chart[marginNames[side]] = mathMax(
chart[marginNames[side]],
chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] +
[1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
pick(options.margin, 12) +
spacing[side]
);
}
});
}
},
/**
* Render the legend. This method can be called both before and after
* chart.render. If called after, it will only rearrange items instead
* of creating new ones.
*/
render: function () {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
legendGroup = legend.group,
allItems,
display,
legendWidth,
legendHeight,
box = legend.box,
options = legend.options,
padding = legend.padding,
legendBorderWidth = options.borderWidth,
legendBackgroundColor = options.backgroundColor;
legend.itemX = legend.initialItemX;
legend.itemY = legend.initialItemY;
legend.offsetWidth = 0;
legend.lastItemY = 0;
if (!legendGroup) {
legend.group = legendGroup = renderer.g('legend')
.attr({ zIndex: 7 })
.add();
legend.contentGroup = renderer.g()
.attr({ zIndex: 1 }) // above background
.add(legendGroup);
legend.scrollGroup = renderer.g()
.add(legend.contentGroup);
}
legend.renderTitle();
// add each series or point
allItems = legend.getAllItems();
// sort by legendIndex
stableSort(allItems, function (a, b) {
return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
});
// reversed legend
if (options.reversed) {
allItems.reverse();
}
legend.allItems = allItems;
legend.display = display = !!allItems.length;
// render the items
legend.lastLineHeight = 0;
each(allItems, function (item) {
legend.renderItem(item);
});
// Get the box
legendWidth = (options.width || legend.offsetWidth) + padding;
legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
legendHeight = legend.handleOverflow(legendHeight);
legendHeight += padding;
// Draw the border and/or background
if (legendBorderWidth || legendBackgroundColor) {
if (!box) {
legend.box = box = renderer.rect(
0,
0,
legendWidth,
legendHeight,
options.borderRadius,
legendBorderWidth || 0
).attr({
stroke: options.borderColor,
'stroke-width': legendBorderWidth || 0,
fill: legendBackgroundColor || NONE
})
.add(legendGroup)
.shadow(options.shadow);
box.isNew = true;
} else if (legendWidth > 0 && legendHeight > 0) {
box[box.isNew ? 'attr' : 'animate'](
box.crisp({ width: legendWidth, height: legendHeight })
);
box.isNew = false;
}
// hide the border if no items
box[display ? 'show' : 'hide']();
}
legend.legendWidth = legendWidth;
legend.legendHeight = legendHeight;
// Now that the legend width and height are established, put the items in the
// final position
each(allItems, function (item) {
legend.positionItem(item);
});
// 1.x compatibility: positioning based on style
/*var props = ['left', 'right', 'top', 'bottom'],
prop,
i = 4;
while (i--) {
prop = props[i];
if (options.style[prop] && options.style[prop] !== 'auto') {
options[i < 2 ? 'align' : 'verticalAlign'] = prop;
options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
}
}*/
if (display) {
legendGroup.align(extend({
width: legendWidth,
height: legendHeight
}, options), true, 'spacingBox');
}
if (!chart.isResizing) {
this.positionCheckboxes();
}
},
/**
* Set up the overflow handling by adding navigation with up and down arrows below the
* legend.
*/
handleOverflow: function (legendHeight) {
var legend = this,
chart = this.chart,
renderer = chart.renderer,
options = this.options,
optionsY = options.y,
alignTop = options.verticalAlign === 'top',
spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
maxHeight = options.maxHeight,
clipHeight,
clipRect = this.clipRect,
navOptions = options.navigation,
animation = pick(navOptions.animation, true),
arrowSize = navOptions.arrowSize || 12,
nav = this.nav,
pages = this.pages,
lastY,
allItems = this.allItems;
// Adjust the height
if (options.layout === 'horizontal') {
spaceHeight /= 2;
}
if (maxHeight) {
spaceHeight = mathMin(spaceHeight, maxHeight);
}
// Reset the legend height and adjust the clipping rectangle
pages.length = 0;
if (legendHeight > spaceHeight && !options.useHTML) {
this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - this.padding, 0);
this.currentPage = pick(this.currentPage, 1);
this.fullHeight = legendHeight;
// Fill pages with Y positions so that the top of each a legend item defines
// the scroll top for each page (#2098)
each(allItems, function (item, i) {
var y = item._legendItemPos[1],
h = mathRound(item.legendItem.getBBox().height),
len = pages.length;
if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
pages.push(lastY || y);
len++;
}
if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
pages.push(y);
}
if (y !== lastY) {
lastY = y;
}
});
// Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
if (!clipRect) {
clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 9999, 0);
legend.contentGroup.clip(clipRect);
}
clipRect.attr({
height: clipHeight
});
// Add navigation elements
if (!nav) {
this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(-1, animation);
})
.add(nav);
this.pager = renderer.text('', 15, 10)
.css(navOptions.style)
.add(nav);
this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(1, animation);
})
.add(nav);
}
// Set initial position
legend.scroll(0);
legendHeight = spaceHeight;
} else if (nav) {
clipRect.attr({
height: chart.chartHeight
});
nav.hide();
this.scrollGroup.attr({
translateY: 1
});
this.clipHeight = 0; // #1379
}
return legendHeight;
},
/**
* Scroll the legend by a number of pages
* @param {Object} scrollBy
* @param {Object} animation
*/
scroll: function (scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
activeColor = navOptions.activeColor,
inactiveColor = navOptions.inactiveColor,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== UNDEFINED) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: VISIBLE
});
this.up.attr({
fill: currentPage === 1 ? inactiveColor : activeColor
})
.css({
cursor: currentPage === 1 ? 'default' : 'pointer'
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.down.attr({
x: 18 + this.pager.getBBox().width, // adjust to text width
fill: currentPage === pageCount ? inactiveColor : activeColor
})
.css({
cursor: currentPage === pageCount ? 'default' : 'pointer'
});
scrollOffset = -pages[currentPage - 1] + this.initialItemY;
this.scrollGroup.animate({
translateY: scrollOffset
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
}
};
/*
* LegendSymbolMixin
*/
var LegendSymbolMixin = Highcharts.LegendSymbolMixin = {
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawRectangle: function (legend, item) {
var symbolHeight = legend.options.symbolHeight || 12;
item.legendSymbol = this.chart.renderer.rect(
0,
legend.baseline - 5 - (symbolHeight / 2),
legend.symbolWidth,
symbolHeight,
legend.options.symbolRadius || 0
).attr({
zIndex: 3
}).add(item.legendGroup);
},
/**
* Get the series' symbol in the legend. This method should be overridable to create custom
* symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
*
* @param {Object} legend The legend object
*/
drawLineMarker: function (legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendOptions = legend.options,
legendSymbol,
symbolWidth = legend.symbolWidth,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize, this.legendItem).b * 0.3),
attr;
// Draw the line
if (options.lineWidth) {
attr = {
'stroke-width': options.lineWidth
};
if (options.dashStyle) {
attr.dashstyle = options.dashStyle;
}
this.legendLine = renderer.path([
M,
0,
verticalCenter,
L,
symbolWidth,
verticalCenter
])
.attr(attr)
.add(legendItemGroup);
}
// Draw the marker
if (markerOptions && markerOptions.enabled !== false) {
radius = markerOptions.radius;
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius
)
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
}
};
// Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
// and for #2580, a similar drawing flaw in Firefox 26.
// TODO: Explore if there's a general cause for this. The problem may be related
// to nested group elements, as the legend item texts are within 4 group elements.
if (/Trident\/7\.0/.test(userAgent) || isFirefox) {
wrap(Legend.prototype, 'positionItem', function (proceed, item) {
var legend = this,
runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030)
if (item._legendItemPos) {
proceed.call(legend, item);
}
};
// Do it now, for export and to get checkbox placement
runPositionItem();
// Do it after to work around the core issue
setTimeout(runPositionItem);
});
}
/**
* The chart class
* @param {Object} options
* @param {Function} callback Function to run when the chart has loaded
*/
var Chart = Highcharts.Chart = function () {
this.init.apply(this, arguments);
};
Chart.prototype = {
/**
* Hook for modules
*/
callbacks: [],
/**
* Initialize the chart
*/
init: function (userOptions, callback) {
// Handle regular options
var options,
seriesOptions = userOptions.series; // skip merging data points to increase performance
userOptions.series = null;
options = merge(defaultOptions, userOptions); // do the merge
options.series = userOptions.series = seriesOptions; // set back the series data
this.userOptions = userOptions;
var optionsChart = options.chart;
// Create margin & spacing array
this.margin = this.splashArray('margin', optionsChart);
this.spacing = this.splashArray('spacing', optionsChart);
var chartEvents = optionsChart.events;
//this.runChartClick = chartEvents && !!chartEvents.click;
this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
this.callback = callback;
this.isResizing = 0;
this.options = options;
//chartTitleOptions = UNDEFINED;
//chartSubtitleOptions = UNDEFINED;
this.axes = [];
this.series = [];
this.hasCartesianSeries = optionsChart.showAxes;
//this.axisOffset = UNDEFINED;
//this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
//this.inverted = UNDEFINED;
//this.loadingShown = UNDEFINED;
//this.container = UNDEFINED;
//this.chartWidth = UNDEFINED;
//this.chartHeight = UNDEFINED;
//this.marginRight = UNDEFINED;
//this.marginBottom = UNDEFINED;
//this.containerWidth = UNDEFINED;
//this.containerHeight = UNDEFINED;
//this.oldChartWidth = UNDEFINED;
//this.oldChartHeight = UNDEFINED;
//this.renderTo = UNDEFINED;
//this.renderToClone = UNDEFINED;
//this.spacingBox = UNDEFINED
//this.legend = UNDEFINED;
// Elements
//this.chartBackground = UNDEFINED;
//this.plotBackground = UNDEFINED;
//this.plotBGImage = UNDEFINED;
//this.plotBorder = UNDEFINED;
//this.loadingDiv = UNDEFINED;
//this.loadingSpan = UNDEFINED;
var chart = this,
eventType;
// Add the chart to the global lookup
chart.index = charts.length;
charts.push(chart);
chartCount++;
// Set up auto resize
if (optionsChart.reflow !== false) {
addEvent(chart, 'load', function () {
chart.initReflow();
});
}
// Chart event handlers
if (chartEvents) {
for (eventType in chartEvents) {
addEvent(chart, eventType, chartEvents[eventType]);
}
}
chart.xAxis = [];
chart.yAxis = [];
// Expose methods and variables
chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
chart.pointCount = chart.colorCounter = chart.symbolCounter = 0;
chart.firstRender();
},
/**
* Initialize an individual series, called internally before render time
*/
initSeries: function (options) {
var chart = this,
optionsChart = chart.options.chart,
type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
series,
constr = seriesTypes[type];
// No such series type
if (!constr) {
error(17, true);
}
series = new constr();
series.init(this, options);
return series;
},
/**
* Check whether a given point is within the plot area
*
* @param {Number} plotX Pixel x relative to the plot area
* @param {Number} plotY Pixel y relative to the plot area
* @param {Boolean} inverted Whether the chart is inverted
*/
isInsidePlot: function (plotX, plotY, inverted) {
var x = inverted ? plotY : plotX,
y = inverted ? plotX : plotY;
return x >= 0 &&
x <= this.plotWidth &&
y >= 0 &&
y <= this.plotHeight;
},
/**
* Redraw legend, axes or series based on updated data
*
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
redraw: function (animation) {
var chart = this,
axes = chart.axes,
series = chart.series,
pointer = chart.pointer,
legend = chart.legend,
redrawLegend = chart.isDirtyLegend,
hasStackedSeries,
hasDirtyStacks,
hasCartesianSeries = chart.hasCartesianSeries,
isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
seriesLength = series.length,
i = seriesLength,
serie,
renderer = chart.renderer,
isHiddenChart = renderer.isHidden(),
afterRedraw = [];
setAnimation(animation, chart);
if (isHiddenChart) {
chart.cloneRenderTo();
}
// Adjust title layout (reflow multiline text)
chart.layOutTitles();
// link stacked series
while (i--) {
serie = series[i];
if (serie.options.stacking) {
hasStackedSeries = true;
if (serie.isDirty) {
hasDirtyStacks = true;
break;
}
}
}
if (hasDirtyStacks) { // mark others as dirty
i = seriesLength;
while (i--) {
serie = series[i];
if (serie.options.stacking) {
serie.isDirty = true;
}
}
}
// handle updated data in the series
each(series, function (serie) {
if (serie.isDirty) { // prepare the data so axis can read it
if (serie.options.legendType === 'point') {
redrawLegend = true;
}
}
});
// handle added or removed series
if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
// draw legend graphics
legend.render();
chart.isDirtyLegend = false;
}
// reset stacks
if (hasStackedSeries) {
chart.getStacks();
}
if (hasCartesianSeries) {
if (!chart.isResizing) {
// reset maxTicks
chart.maxTicks = null;
// set axes scales
each(axes, function (axis) {
axis.setScale();
});
}
}
chart.getMargins(); // #3098
if (hasCartesianSeries) {
// If one axis is dirty, all axes must be redrawn (#792, #2169)
each(axes, function (axis) {
if (axis.isDirty) {
isDirtyBox = true;
}
});
// redraw axes
each(axes, function (axis) {
// Fire 'afterSetExtremes' only if extremes are set
if (axis.isDirtyExtremes) { // #821
axis.isDirtyExtremes = false;
afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
delete axis.eventArgs;
});
}
if (isDirtyBox || hasStackedSeries) {
axis.redraw();
}
});
}
// the plot areas size has changed
if (isDirtyBox) {
chart.drawChartBox();
}
// redraw affected series
each(series, function (serie) {
if (serie.isDirty && serie.visible &&
(!serie.isCartesian || serie.xAxis)) { // issue #153
serie.redraw();
}
});
// move tooltip or reset
if (pointer) {
pointer.reset(true);
}
// redraw if canvas
renderer.draw();
// fire the event
fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
if (isHiddenChart) {
chart.cloneRenderTo(true);
}
// Fire callbacks that are put on hold until after the redraw
each(afterRedraw, function (callback) {
callback.call();
});
},
/**
* Get an axis, series or point object by id.
* @param id {String} The id as given in the configuration options
*/
get: function (id) {
var chart = this,
axes = chart.axes,
series = chart.series;
var i,
j,
points;
// search axes
for (i = 0; i < axes.length; i++) {
if (axes[i].options.id === id) {
return axes[i];
}
}
// search series
for (i = 0; i < series.length; i++) {
if (series[i].options.id === id) {
return series[i];
}
}
// search points
for (i = 0; i < series.length; i++) {
points = series[i].points || [];
for (j = 0; j < points.length; j++) {
if (points[j].id === id) {
return points[j];
}
}
}
return null;
},
/**
* Create the Axis instances based on the config options
*/
getAxes: function () {
var chart = this,
options = this.options,
xAxisOptions = options.xAxis = splat(options.xAxis || {}),
yAxisOptions = options.yAxis = splat(options.yAxis || {}),
optionsArray,
axis;
// make sure the options are arrays and add some members
each(xAxisOptions, function (axis, i) {
axis.index = i;
axis.isX = true;
});
each(yAxisOptions, function (axis, i) {
axis.index = i;
});
// concatenate all axis options into one array
optionsArray = xAxisOptions.concat(yAxisOptions);
each(optionsArray, function (axisOptions) {
axis = new Axis(chart, axisOptions);
});
},
/**
* Get the currently selected points from all series
*/
getSelectedPoints: function () {
var points = [];
each(this.series, function (serie) {
points = points.concat(grep(serie.points || [], function (point) {
return point.selected;
}));
});
return points;
},
/**
* Get the currently selected series
*/
getSelectedSeries: function () {
return grep(this.series, function (serie) {
return serie.selected;
});
},
/**
* Generate stacks for each series and calculate stacks total values
*/
getStacks: function () {
var chart = this;
// reset stacks for each yAxis
each(chart.yAxis, function (axis) {
if (axis.stacks && axis.hasVisibleSeries) {
axis.oldStacks = axis.stacks;
}
});
each(chart.series, function (series) {
if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
series.stackKey = series.type + pick(series.options.stack, '');
}
});
},
/**
* Show the title and subtitle of the chart
*
* @param titleOptions {Object} New title options
* @param subtitleOptions {Object} New subtitle options
*
*/
setTitle: function (titleOptions, subtitleOptions, redraw) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function (arr) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
chart[name] = chart.renderer.text(
chartTitleOptions.text,
0,
0,
chartTitleOptions.useHTML
)
.attr({
align: chartTitleOptions.align,
'class': PREFIX + name,
zIndex: chartTitleOptions.zIndex || 4
})
.css(chartTitleOptions.style)
.add();
}
});
chart.layOutTitles(redraw);
},
/**
* Lay out the chart titles and cache the full offset height for use in getMargins
*/
layOutTitles: function (redraw) {
var titleOffset = 0,
title = this.title,
subtitle = this.subtitle,
options = this.options,
titleOptions = options.title,
subtitleOptions = options.subtitle,
requiresDirtyBox,
renderer = this.renderer,
autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button
if (title) {
title
.css({ width: (titleOptions.width || autoWidth) + PX })
.align(extend({
y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3
}, titleOptions), false, 'spacingBox');
if (!titleOptions.floating && !titleOptions.verticalAlign) {
titleOffset = title.getBBox().height;
}
}
if (subtitle) {
subtitle
.css({ width: (subtitleOptions.width || autoWidth) + PX })
.align(extend({
y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(titleOptions.style.fontSize, subtitle).b
}, subtitleOptions), false, 'spacingBox');
if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
}
}
requiresDirtyBox = this.titleOffset !== titleOffset;
this.titleOffset = titleOffset; // used in getMargins
if (!this.isDirtyBox && requiresDirtyBox) {
this.isDirtyBox = requiresDirtyBox;
// Redraw if necessary (#2719, #2744)
if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
this.redraw();
}
}
},
/**
* Get chart width and height according to options and container size
*/
getChartSize: function () {
var chart = this,
optionsChart = chart.options.chart,
widthOption = optionsChart.width,
heightOption = optionsChart.height,
renderTo = chart.renderToClone || chart.renderTo;
// get inner width and height from jQuery (#824)
if (!defined(widthOption)) {
chart.containerWidth = adapterRun(renderTo, 'width');
}
if (!defined(heightOption)) {
chart.containerHeight = adapterRun(renderTo, 'height');
}
chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460
chart.chartHeight = mathMax(0, pick(heightOption,
// the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
chart.containerHeight > 19 ? chart.containerHeight : 400));
},
/**
* Create a clone of the chart's renderTo div and place it outside the viewport to allow
* size computation on chart.render and chart.redraw
*/
cloneRenderTo: function (revert) {
var clone = this.renderToClone,
container = this.container;
// Destroy the clone and bring the container back to the real renderTo div
if (revert) {
if (clone) {
this.renderTo.appendChild(container);
discardElement(clone);
delete this.renderToClone;
}
// Set up the clone
} else {
if (container && container.parentNode === this.renderTo) {
this.renderTo.removeChild(container); // do not clone this
}
this.renderToClone = clone = this.renderTo.cloneNode(0);
css(clone, {
position: ABSOLUTE,
top: '-9999px',
display: 'block' // #833
});
if (clone.style.setProperty) { // #2631
clone.style.setProperty('display', 'block', 'important');
}
doc.body.appendChild(clone);
if (container) {
clone.appendChild(container);
}
}
},
/**
* Get the containing element, determine the size and create the inner container
* div to hold the chart
*/
getContainer: function () {
var chart = this,
container,
optionsChart = chart.options.chart,
chartWidth,
chartHeight,
renderTo,
indexAttrName = 'data-highcharts-chart',
oldChartIndex,
containerId;
chart.renderTo = renderTo = optionsChart.renderTo;
containerId = PREFIX + idCounter++;
if (isString(renderTo)) {
chart.renderTo = renderTo = doc.getElementById(renderTo);
}
// Display an error if the renderTo is wrong
if (!renderTo) {
error(13, true);
}
// If the container already holds a chart, destroy it. The check for hasRendered is there
// because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart
// attribute and the SVG contents, but not an interactive chart. So in this case,
// charts[oldChartIndex] will point to the wrong chart if any (#2609).
oldChartIndex = pInt(attr(renderTo, indexAttrName));
if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) {
charts[oldChartIndex].destroy();
}
// Make a reference to the chart from the div
attr(renderTo, indexAttrName, chart.index);
// remove previous chart
renderTo.innerHTML = '';
// If the container doesn't have an offsetWidth, it has or is a child of a node
// that has display:none. We need to temporarily move it out to a visible
// state to determine the size, else the legend and tooltips won't render
// properly. The allowClone option is used in sparklines as a micro optimization,
// saving about 1-2 ms each chart.
if (!optionsChart.skipClone && !renderTo.offsetWidth) {
chart.cloneRenderTo();
}
// get the width and height
chart.getChartSize();
chartWidth = chart.chartWidth;
chartHeight = chart.chartHeight;
// create the inner container
chart.container = container = createElement(DIV, {
className: PREFIX + 'container' +
(optionsChart.className ? ' ' + optionsChart.className : ''),
id: containerId
}, extend({
position: RELATIVE,
overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
// content overflow in IE
width: chartWidth + PX,
height: chartHeight + PX,
textAlign: 'left',
lineHeight: 'normal', // #427
zIndex: 0, // #1072
'-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
}, optionsChart.style),
chart.renderToClone || renderTo
);
// cache the cursor (#1650)
chart._cursor = container.style.cursor;
// Initialize the renderer
chart.renderer =
optionsChart.forExport ? // force SVG, used for SVG export
new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) :
new Renderer(container, chartWidth, chartHeight, optionsChart.style);
if (useCanVG) {
// If we need canvg library, extend and configure the renderer
// to get the tracker for translating mouse events
chart.renderer.create(chart, container, chartWidth, chartHeight);
}
// Add a reference to the charts index
chart.renderer.chartIndex = chart.index;
},
/**
* Calculate margins by rendering axis labels in a preliminary position. Title,
* subtitle and legend have already been rendered at this stage, but will be
* moved into their final positions
*/
getMargins: function (skipAxes) {
var chart = this,
spacing = chart.spacing,
margin = chart.margin,
titleOffset = chart.titleOffset;
chart.resetMargins();
// Adjust for title and subtitle
if (titleOffset && !defined(margin[0])) {
chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
}
// Adjust for legend
chart.legend.adjustMargins(margin, spacing);
// adjust for scroller
if (chart.extraBottomMargin) {
chart.marginBottom += chart.extraBottomMargin;
}
if (chart.extraTopMargin) {
chart.plotTop += chart.extraTopMargin;
}
if (!skipAxes) {
this.getAxisMargins();
}
},
getAxisMargins: function () {
var chart = this,
axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left
margin = chart.margin;
// pre-render axes to get labels offset width
if (chart.hasCartesianSeries) {
each(chart.axes, function (axis) {
axis.getOffset();
});
}
// Add the axis offsets
each(marginNames, function (m, side) {
if (!defined(margin[side])) {
chart[m] += axisOffset[side];
}
});
chart.setChartSize();
},
/**
* Resize the chart to its container if size is not explicitly set
*/
reflow: function (e) {
var chart = this,
optionsChart = chart.options.chart,
renderTo = chart.renderTo,
width = optionsChart.width || adapterRun(renderTo, 'width'),
height = optionsChart.height || adapterRun(renderTo, 'height'),
target = e ? e.target : win, // #805 - MooTools doesn't supply e
doReflow = function () {
if (chart.container) { // It may have been destroyed in the meantime (#1257)
chart.setSize(width, height, false);
chart.hasUserSize = null;
}
};
// Width and height checks for display:none. Target is doc in IE8 and Opera,
// win in Firefox, Chrome and IE9.
if (!chart.hasUserSize && width && height && (target === win || target === doc)) {
if (width !== chart.containerWidth || height !== chart.containerHeight) {
clearTimeout(chart.reflowTimeout);
if (e) { // Called from window.resize
chart.reflowTimeout = setTimeout(doReflow, 100);
} else { // Called directly (#2224)
doReflow();
}
}
chart.containerWidth = width;
chart.containerHeight = height;
}
},
/**
* Add the event handlers necessary for auto resizing
*/
initReflow: function () {
var chart = this,
reflow = function (e) {
chart.reflow(e);
};
addEvent(win, 'resize', reflow);
addEvent(chart, 'destroy', function () {
removeEvent(win, 'resize', reflow);
});
},
/**
* Resize the chart to a given width and height
* @param {Number} width
* @param {Number} height
* @param {Object|Boolean} animation
*/
setSize: function (width, height, animation) {
var chart = this,
chartWidth,
chartHeight,
fireEndResize;
// Handle the isResizing counter
chart.isResizing += 1;
fireEndResize = function () {
if (chart) {
fireEvent(chart, 'endResize', null, function () {
chart.isResizing -= 1;
});
}
};
// set the animation for the current process
setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (defined(width)) {
chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
chart.hasUserSize = !!chartWidth;
}
if (defined(height)) {
chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
}
// Resize the container with the global animation applied if enabled (#2503)
(globalAnimation ? animate : css)(chart.container, {
width: chartWidth + PX,
height: chartHeight + PX
}, globalAnimation);
chart.setChartSize(true);
chart.renderer.setSize(chartWidth, chartHeight, animation);
// handle axes
chart.maxTicks = null;
each(chart.axes, function (axis) {
axis.isDirty = true;
axis.setScale();
});
// make sure non-cartesian series are also handled
each(chart.series, function (serie) {
serie.isDirty = true;
});
chart.isDirtyLegend = true; // force legend redraw
chart.isDirtyBox = true; // force redraw of plot and chart border
chart.layOutTitles(); // #2857
chart.getMargins();
chart.redraw(animation);
chart.oldChartHeight = null;
fireEvent(chart, 'resize');
// fire endResize and set isResizing back
// If animation is disabled, fire without delay
if (globalAnimation === false) {
fireEndResize();
} else { // else set a timeout with the animation duration
setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
}
},
/**
* Set the public chart properties. This is done before and after the pre-render
* to determine margin sizes
*/
setChartSize: function (skipAxes) {
var chart = this,
inverted = chart.inverted,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
optionsChart = chart.options.chart,
spacing = chart.spacing,
clipOffset = chart.clipOffset,
clipX,
clipY,
plotLeft,
plotTop,
plotWidth,
plotHeight,
plotBorderWidth;
chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
chart.plotTop = plotTop = mathRound(chart.plotTop);
chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
chart.plotSizeX = inverted ? plotHeight : plotWidth;
chart.plotSizeY = inverted ? plotWidth : plotHeight;
chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
// Set boxes used for alignment
chart.spacingBox = renderer.spacingBox = {
x: spacing[3],
y: spacing[0],
width: chartWidth - spacing[3] - spacing[1],
height: chartHeight - spacing[0] - spacing[2]
};
chart.plotBox = renderer.plotBox = {
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
};
plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
chart.clipBox = {
x: clipX,
y: clipY,
width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY))
};
if (!skipAxes) {
each(chart.axes, function (axis) {
axis.setAxisSize();
axis.setAxisTranslation();
});
}
},
/**
* Initial margins before auto size margins are applied
*/
resetMargins: function () {
var chart = this;
each(marginNames, function (m, side) {
chart[m] = pick(chart.margin[side], chart.spacing[side]);
});
chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
chart.clipOffset = [0, 0, 0, 0];
},
/**
* Draw the borders and backgrounds for chart and plot area
*/
drawChartBox: function () {
var chart = this,
optionsChart = chart.options.chart,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
chartBackground = chart.chartBackground,
plotBackground = chart.plotBackground,
plotBorder = chart.plotBorder,
plotBGImage = chart.plotBGImage,
chartBorderWidth = optionsChart.borderWidth || 0,
chartBackgroundColor = optionsChart.backgroundColor,
plotBackgroundColor = optionsChart.plotBackgroundColor,
plotBackgroundImage = optionsChart.plotBackgroundImage,
plotBorderWidth = optionsChart.plotBorderWidth || 0,
mgn,
bgAttr,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
plotBox = chart.plotBox,
clipRect = chart.clipRect,
clipBox = chart.clipBox;
// Chart area
mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
if (chartBorderWidth || chartBackgroundColor) {
if (!chartBackground) {
bgAttr = {
fill: chartBackgroundColor || NONE
};
if (chartBorderWidth) { // #980
bgAttr.stroke = optionsChart.borderColor;
bgAttr['stroke-width'] = chartBorderWidth;
}
chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
optionsChart.borderRadius, chartBorderWidth)
.attr(bgAttr)
.addClass(PREFIX + 'background')
.add()
.shadow(optionsChart.shadow);
} else { // resize
chartBackground.animate(
chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn })
);
}
}
// Plot background
if (plotBackgroundColor) {
if (!plotBackground) {
chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
.attr({
fill: plotBackgroundColor
})
.add()
.shadow(optionsChart.plotShadow);
} else {
plotBackground.animate(plotBox);
}
}
if (plotBackgroundImage) {
if (!plotBGImage) {
chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
.add();
} else {
plotBGImage.animate(plotBox);
}
}
// Plot clip
if (!clipRect) {
chart.clipRect = renderer.clipRect(clipBox);
} else {
clipRect.animate({
width: clipBox.width,
height: clipBox.height
});
}
// Plot area border
if (plotBorderWidth) {
if (!plotBorder) {
chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
.attr({
stroke: optionsChart.plotBorderColor,
'stroke-width': plotBorderWidth,
fill: NONE,
zIndex: 1
})
.add();
} else {
plotBorder.animate(
plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative
);
}
}
// reset
chart.isDirtyBox = false;
},
/**
* Detect whether a certain chart property is needed based on inspecting its options
* and series. This mainly applies to the chart.invert property, and in extensions to
* the chart.angular and chart.polar properties.
*/
propFromSeries: function () {
var chart = this,
optionsChart = chart.options.chart,
klass,
seriesOptions = chart.options.series,
i,
value;
each(['inverted', 'angular', 'polar'], function (key) {
// The default series type's class
klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
// Get the value from available chart-wide properties
value = (
chart[key] || // 1. it is set before
optionsChart[key] || // 2. it is set in the options
(klass && klass.prototype[key]) // 3. it's default series class requires it
);
// 4. Check if any the chart's series require it
i = seriesOptions && seriesOptions.length;
while (!value && i--) {
klass = seriesTypes[seriesOptions[i].type];
if (klass && klass.prototype[key]) {
value = true;
}
}
// Set the chart property
chart[key] = value;
});
},
/**
* Link two or more series together. This is done initially from Chart.render,
* and after Chart.addSeries and Series.remove.
*/
linkSeries: function () {
var chart = this,
chartSeries = chart.series;
// Reset links
each(chartSeries, function (series) {
series.linkedSeries.length = 0;
});
// Apply new links
each(chartSeries, function (series) {
var linkedTo = series.options.linkedTo;
if (isString(linkedTo)) {
if (linkedTo === ':previous') {
linkedTo = chart.series[series.index - 1];
} else {
linkedTo = chart.get(linkedTo);
}
if (linkedTo) {
linkedTo.linkedSeries.push(series);
series.linkedParent = linkedTo;
}
}
});
},
/**
* Render series for the chart
*/
renderSeries: function () {
each(this.series, function (serie) {
serie.translate();
serie.render();
});
},
/**
* Render labels for the chart
*/
renderLabels: function () {
var chart = this,
labels = chart.options.labels;
if (labels.items) {
each(labels.items, function (label) {
var style = extend(labels.style, label.style),
x = pInt(style.left) + chart.plotLeft,
y = pInt(style.top) + chart.plotTop + 12;
// delete to prevent rewriting in IE
delete style.left;
delete style.top;
chart.renderer.text(
label.html,
x,
y
)
.attr({ zIndex: 2 })
.css(style)
.add();
});
}
},
/**
* Render all graphics for the chart
*/
render: function () {
var chart = this,
axes = chart.axes,
renderer = chart.renderer,
options = chart.options,
tempWidth,
tempHeight,
redoHorizontal,
redoVertical;
// Title
chart.setTitle();
// Legend
chart.legend = new Legend(chart, options.legend);
chart.getStacks(); // render stacks
// Get chart margins
chart.getMargins(true);
chart.setChartSize();
// Record preliminary dimensions for later comparison
tempWidth = chart.plotWidth;
tempHeight = chart.plotHeight = chart.plotHeight - 13; // 13 is the most common height of X axis labels
// Get margins by pre-rendering axes
each(axes, function (axis) {
axis.setScale();
});
chart.getAxisMargins();
// If the plot area size has changed significantly, calculate tick positions again
redoHorizontal = tempWidth / chart.plotWidth > 1.2;
redoVertical = tempHeight / chart.plotHeight > 1.1;
if (redoHorizontal || redoVertical) {
chart.maxTicks = null; // reset for second pass
each(axes, function (axis) {
if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) {
axis.setTickInterval(true); // update to reflect the new margins
}
});
chart.getMargins(); // second pass to check for new labels
}
// Draw the borders and backgrounds
chart.drawChartBox();
// Axes
if (chart.hasCartesianSeries) {
each(axes, function (axis) {
axis.render();
});
}
// The series
if (!chart.seriesGroup) {
chart.seriesGroup = renderer.g('series-group')
.attr({ zIndex: 3 })
.add();
}
chart.renderSeries();
// Labels
chart.renderLabels();
// Credits
chart.showCredits(options.credits);
// Set flag
chart.hasRendered = true;
},
/**
* Show chart credits based on config options
*/
showCredits: function (credits) {
if (credits.enabled && !this.credits) {
this.credits = this.renderer.text(
credits.text,
0,
0
)
.on('click', function () {
if (credits.href) {
location.href = credits.href;
}
})
.attr({
align: credits.position.align,
zIndex: 8
})
.css(credits.style)
.add()
.align(credits.position);
}
},
/**
* Clean up memory usage
*/
destroy: function () {
var chart = this,
axes = chart.axes,
series = chart.series,
container = chart.container,
i,
parentNode = container && container.parentNode;
// fire the chart.destoy event
fireEvent(chart, 'destroy');
// Delete the chart from charts lookup array
charts[chart.index] = UNDEFINED;
chartCount--;
chart.renderTo.removeAttribute('data-highcharts-chart');
// remove events
removeEvent(chart);
// ==== Destroy collections:
// Destroy axes
i = axes.length;
while (i--) {
axes[i] = axes[i].destroy();
}
// Destroy each series
i = series.length;
while (i--) {
series[i] = series[i].destroy();
}
// ==== Destroy chart properties:
each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
var prop = chart[name];
if (prop && prop.destroy) {
chart[name] = prop.destroy();
}
});
// remove container and all SVG
if (container) { // can break in IE when destroyed before finished loading
container.innerHTML = '';
removeEvent(container);
if (parentNode) {
discardElement(container);
}
}
// clean it all up
for (i in chart) {
delete chart[i];
}
},
/**
* VML namespaces can't be added until after complete. Listening
* for Perini's doScroll hack is not enough.
*/
isReadyToRender: function () {
var chart = this;
// Note: in spite of JSLint's complaints, win == win.top is required
/*jslint eqeq: true*/
if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
/*jslint eqeq: false*/
if (useCanVG) {
// Delay rendering until canvg library is downloaded and ready
CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
} else {
doc.attachEvent('onreadystatechange', function () {
doc.detachEvent('onreadystatechange', chart.firstRender);
if (doc.readyState === 'complete') {
chart.firstRender();
}
});
}
return false;
}
return true;
},
/**
* Prepare for first rendering after all data are loaded
*/
firstRender: function () {
var chart = this,
options = chart.options,
callback = chart.callback;
// Check whether the chart is ready to render
if (!chart.isReadyToRender()) {
return;
}
// Create the container
chart.getContainer();
// Run an early event after the container and renderer are established
fireEvent(chart, 'init');
chart.resetMargins();
chart.setChartSize();
// Set the common chart properties (mainly invert) from the given series
chart.propFromSeries();
// get axes
chart.getAxes();
// Initialize the series
each(options.series || [], function (serieOptions) {
chart.initSeries(serieOptions);
});
chart.linkSeries();
// Run an event after axes and series are initialized, but before render. At this stage,
// the series data is indexed and cached in the xData and yData arrays, so we can access
// those before rendering. Used in Highstock.
fireEvent(chart, 'beforeRender');
// depends on inverted and on margins being set
if (Highcharts.Pointer) {
chart.pointer = new Pointer(chart, options);
}
chart.render();
// add canvas
chart.renderer.draw();
// run callbacks
if (callback) {
callback.apply(chart, [chart]);
}
each(chart.callbacks, function (fn) {
if (chart.index !== UNDEFINED) { // Chart destroyed in its own callback (#3600)
fn.apply(chart, [chart]);
}
});
// Fire the load event
fireEvent(chart, 'load');
// If the chart was rendered outside the top container, put it back in (#3679)
chart.cloneRenderTo(true);
},
/**
* Creates arrays for spacing and margin from given options.
*/
splashArray: function (target, options) {
var oVar = options[target],
tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
return [pick(options[target + 'Top'], tArray[0]),
pick(options[target + 'Right'], tArray[1]),
pick(options[target + 'Bottom'], tArray[2]),
pick(options[target + 'Left'], tArray[3])];
}
}; // end Chart
var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = {
/**
* Get the center of the pie based on the size and center options relative to the
* plot area. Borrowed by the polar and gauge series types.
*/
getCenter: function () {
var options = this.options,
chart = this.chart,
slicingRoom = 2 * (options.slicedOffset || 0),
handleSlicingRoom,
plotWidth = chart.plotWidth - 2 * slicingRoom,
plotHeight = chart.plotHeight - 2 * slicingRoom,
centerOption = options.center,
positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
smallestSize = mathMin(plotWidth, plotHeight),
isPercent;
return map(positions, function (length, i) {
isPercent = /%$/.test(length);
handleSlicingRoom = i < 2 || (i === 2 && isPercent);
return (isPercent ?
// i == 0: centerX, relative to width
// i == 1: centerY, relative to height
// i == 2: size, relative to smallestSize
// i == 4: innerSize, relative to smallestSize
[plotWidth, plotHeight, smallestSize, smallestSize][i] *
pInt(length) / 100 :
length) + (handleSlicingRoom ? slicingRoom : 0);
});
}
};
/**
* The Point object and prototype. Inheritable and used as base for PiePoint
*/
var Point = function () {};
Point.prototype = {
/**
* Initialize the point
* @param {Object} series The series object containing this point
* @param {Object} options The data in either number, array or object format
*/
init: function (series, options, x) {
var point = this,
colors;
point.series = series;
point.color = series.color; // #3445
point.applyOptions(options, x);
point.pointAttr = {};
if (series.options.colorByPoint) {
colors = series.options.colors || series.chart.options.colors;
point.color = point.color || colors[series.colorCounter++];
// loop back to zero
if (series.colorCounter === colors.length) {
series.colorCounter = 0;
}
}
series.chart.pointCount++;
return point;
},
/**
* Apply the options containing the x and y data and possible some extra properties.
* This is called on point init or from point.update.
*
* @param {Object} options
*/
applyOptions: function (options, x) {
var point = this,
series = point.series,
pointValKey = series.options.pointValKey || series.pointValKey;
options = Point.prototype.optionsToObject.call(this, options);
// copy options directly to point
extend(point, options);
point.options = point.options ? extend(point.options, options) : options;
// For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
if (pointValKey) {
point.y = point[pointValKey];
}
// If no x is set by now, get auto incremented value. All points must have an
// x value, however the y value can be null to create a gap in the series
if (point.x === UNDEFINED && series) {
point.x = x === UNDEFINED ? series.autoIncrement() : x;
}
return point;
},
/**
* Transform number or array configs into objects
*/
optionsToObject: function (options) {
var ret = {},
series = this.series,
pointArrayMap = series.pointArrayMap || ['y'],
valueCount = pointArrayMap.length,
firstItemType,
i = 0,
j = 0;
if (typeof options === 'number' || options === null) {
ret[pointArrayMap[0]] = options;
} else if (isArray(options)) {
// with leading x value
if (options.length > valueCount) {
firstItemType = typeof options[0];
if (firstItemType === 'string') {
ret.name = options[0];
} else if (firstItemType === 'number') {
ret.x = options[0];
}
i++;
}
while (j < valueCount) {
ret[pointArrayMap[j++]] = options[i++];
}
} else if (typeof options === 'object') {
ret = options;
// This is the fastest way to detect if there are individual point dataLabels that need
// to be considered in drawDataLabels. These can only occur in object configs.
if (options.dataLabels) {
series._hasPointLabels = true;
}
// Same approach as above for markers
if (options.marker) {
series._hasPointMarkers = true;
}
}
return ret;
},
/**
* Destroy a point to clear memory. Its reference still stays in series.data.
*/
destroy: function () {
var point = this,
series = point.series,
chart = series.chart,
hoverPoints = chart.hoverPoints,
prop;
chart.pointCount--;
if (hoverPoints) {
point.setState();
erase(hoverPoints, point);
if (!hoverPoints.length) {
chart.hoverPoints = null;
}
}
if (point === chart.hoverPoint) {
point.onMouseOut();
}
// remove all events
if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
removeEvent(point);
point.destroyElements();
}
if (point.legendItem) { // pies have legend items
chart.legend.destroyItem(point);
}
for (prop in point) {
point[prop] = null;
}
},
/**
* Destroy SVG elements associated with the point
*/
destroyElements: function () {
var point = this,
props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'],
prop,
i = 6;
while (i--) {
prop = props[i];
if (point[prop]) {
point[prop] = point[prop].destroy();
}
}
},
/**
* Return the configuration hash needed for the data label and tooltip formatters
*/
getLabelConfig: function () {
var point = this;
return {
x: point.category,
y: point.y,
key: point.name || point.category,
series: point.series,
point: point,
percentage: point.percentage,
total: point.total || point.stackTotal
};
},
/**
* Extendable method for formatting each point's tooltip line
*
* @return {String} A string to be concatenated in to the common tooltip text
*/
tooltipFormatter: function (pointFormat) {
// Insert options for valueDecimals, valuePrefix, and valueSuffix
var series = this.series,
seriesTooltipOptions = series.tooltipOptions,
valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
valuePrefix = seriesTooltipOptions.valuePrefix || '',
valueSuffix = seriesTooltipOptions.valueSuffix || '';
// Loop over the point array map and replace unformatted values with sprintf formatting markup
each(series.pointArrayMap || ['y'], function (key) {
key = '{point.' + key; // without the closing bracket
if (valuePrefix || valueSuffix) {
pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
}
pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
});
return format(pointFormat, {
point: this,
series: this.series
});
},
/**
* Fire an event on the Point object. Must not be renamed to fireEvent, as this
* causes a name clash in MooTools
* @param {String} eventType
* @param {Object} eventArgs Additional event arguments
* @param {Function} defaultFunction Default event handler
*/
firePointEvent: function (eventType, eventArgs, defaultFunction) {
var point = this,
series = this.series,
seriesOptions = series.options;
// load event handlers on demand to save time on mouseover/out
if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
this.importEvents();
}
// add default handler if in selection mode
if (eventType === 'click' && seriesOptions.allowPointSelect) {
defaultFunction = function (event) {
// Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
};
}
fireEvent(this, eventType, eventArgs, defaultFunction);
}
};/**
* @classDescription The base function which all other series types inherit from. The data in the series is stored
* in various arrays.
*
* - First, series.options.data contains all the original config options for
* each point whether added by options or methods like series.addPoint.
* - Next, series.data contains those values converted to points, but in case the series data length
* exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
* only contains the points that have been created on demand.
* - Then there's series.points that contains all currently visible point objects. In case of cropping,
* the cropped-away points are not part of this array. The series.points array starts at series.cropStart
* compared to series.data and series.options.data. If however the series data is grouped, these can't
* be correlated one to one.
* - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
* - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
*
* @param {Object} chart
* @param {Object} options
*/
var Series = Highcharts.Series = function () {};
Series.prototype = {
isCartesian: true,
type: 'line',
pointClass: Point,
sorted: true, // requires the data to be sorted
requireSorting: true,
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'lineColor',
'stroke-width': 'lineWidth',
fill: 'fillColor',
r: 'radius'
},
axisTypes: ['xAxis', 'yAxis'],
colorCounter: 0,
parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
init: function (chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series,
sortByIndex = function (a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, b._i);
};
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: NORMAL_STATE,
pointAttr: {},
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// special
if (useCanVG) {
options.animation = false;
}
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// Set the data
each(series.parallelArrays, function (key) {
series[key + 'Data'] = [];
});
series.setData(options.data, false);
// Mark cartesian
if (series.isCartesian) {
chart.hasCartesianSeries = true;
}
// Register it in the chart
chartSeries.push(series);
series._i = chartSeries.length - 1;
// Sort series according to index option (#248, #1123, #2456)
stableSort(chartSeries, sortByIndex);
if (this.yAxis) {
stableSort(this.yAxis.series, sortByIndex);
}
each(chartSeries, function (series, i) {
series.index = i;
series.name = series.name || 'Series ' + (i + 1);
});
},
/**
* Set the xAxis and yAxis properties of cartesian series, and register the series
* in the axis.series array
*/
bindAxes: function () {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function (axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
// set this series.xAxis or series.yAxis reference
series[AXIS] = axis;
// mark dirty for redraw
axis.isDirty = true;
}
});
// The series needs an X and an Y axis
if (!series[AXIS] && series.optionalAxis !== AXIS) {
error(18, true);
}
});
},
/**
* For simple series types like line and column, the data values are held in arrays like
* xData and yData for quick lookup to find extremes and more. For multidimensional series
* like bubble and map, this can be extended with arrays like zData and valueData by
* adding to the series.parallelArrays array.
*/
updateParallelArrays: function (point, i) {
var series = point.series,
args = arguments,
fn = typeof i === 'number' ?
// Insert the value in the given position
function (key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} :
// Apply the method specified in i with the following arguments as arguments
function (key) {
Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
};
each(series.parallelArrays, fn);
},
/**
* Return an auto incremented x value based on the pointStart and pointInterval options.
* This is only used if an x value is not given for the point that calls autoIncrement.
*/
autoIncrement: function () {
var options = this.options,
xIncrement = this.xIncrement,
date,
pointInterval,
pointIntervalUnit = options.pointIntervalUnit;
xIncrement = pick(xIncrement, options.pointStart, 0);
this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1);
// Added code for pointInterval strings
if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') {
date = new Date(xIncrement);
date = (pointIntervalUnit === 'month') ?
+date[setMonth](date[getMonth]() + pointInterval) :
+date[setFullYear](date[getFullYear]() + pointInterval);
pointInterval = date - xIncrement;
}
this.xIncrement = xIncrement + pointInterval;
return xIncrement;
},
/**
* Divide the series data into segments divided by null values.
*/
getSegments: function () {
var series = this,
lastNull = -1,
segments = [],
i,
points = series.points,
pointsLength = points.length;
if (pointsLength) { // no action required for []
// if connect nulls, just remove null points
if (series.options.connectNulls) {
i = pointsLength;
while (i--) {
if (points[i].y === null) {
points.splice(i, 1);
}
}
if (points.length) {
segments = [points];
}
// else, split on null points
} else {
each(points, function (point, i) {
if (point.y === null) {
if (i > lastNull + 1) {
segments.push(points.slice(lastNull + 1, i));
}
lastNull = i;
} else if (i === pointsLength - 1) { // last value
segments.push(points.slice(lastNull + 1, i + 1));
}
});
}
}
// register it
series.segments = segments;
},
/**
* Set the series options by merging from the options tree
* @param {Object} itemOptions
*/
setOptions: function (itemOptions) {
var chart = this.chart,
chartOptions = chart.options,
plotOptions = chartOptions.plotOptions,
userOptions = chart.userOptions || {},
userPlotOptions = userOptions.plotOptions || {},
typeOptions = plotOptions[this.type],
options,
zones;
this.userOptions = itemOptions;
options = merge(
typeOptions,
plotOptions.series,
itemOptions
);
// The tooltip options are merged between global and series specific options
this.tooltipOptions = merge(
defaultOptions.tooltip,
defaultOptions.plotOptions[this.type].tooltip,
userOptions.tooltip,
userPlotOptions.series && userPlotOptions.series.tooltip,
userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
itemOptions.tooltip
);
// Delete marker object if not allowed (#1125)
if (typeOptions.marker === null) {
delete options.marker;
}
// Handle color zones
this.zoneAxis = options.zoneAxis;
zones = this.zones = (options.zones || []).slice();
if ((options.negativeColor || options.negativeFillColor) && !options.zones) {
zones.push({
value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0,
color: options.negativeColor,
fillColor: options.negativeFillColor
});
}
if (zones.length) { // Push one extra zone for the rest
if (defined(zones[zones.length - 1].value)) {
zones.push({
color: this.color,
fillColor: this.fillColor
});
}
}
return options;
},
getCyclic: function (prop, value, defaults) {
var i,
userOptions = this.userOptions,
indexName = '_' + prop + 'Index',
counterName = prop + 'Counter';
if (!value) {
if (defined(userOptions[indexName])) { // after Series.update()
i = userOptions[indexName];
} else {
userOptions[indexName] = i = this.chart[counterName] % defaults.length;
this.chart[counterName] += 1;
}
value = defaults[i];
}
this[prop] = value;
},
/**
* Get the series' color
*/
getColor: function () {
if (!this.options.colorByPoint) {
this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors);
}
},
/**
* Get the series' symbol
*/
getSymbol: function () {
var seriesMarkerOption = this.options.marker;
this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols);
// don't substract radius in image symbols (#604)
if (/^url/.test(this.symbol)) {
seriesMarkerOption.radius = 0;
}
},
drawLegendSymbol: LegendSymbolMixin.drawLineMarker,
/**
* Replace the series data with a new set of data
* @param {Object} data
* @param {Object} redraw
*/
setData: function (data, redraw, animation, updatePoints) {
var series = this,
oldData = series.points,
oldDataLength = (oldData && oldData.length) || 0,
dataLength,
options = series.options,
chart = series.chart,
firstPoint = null,
xAxis = series.xAxis,
hasCategories = xAxis && !!xAxis.categories,
i,
turboThreshold = options.turboThreshold,
pt,
xData = this.xData,
yData = this.yData,
pointArrayMap = series.pointArrayMap,
valueCount = pointArrayMap && pointArrayMap.length;
data = data || [];
dataLength = data.length;
redraw = pick(redraw, true);
// If the point count is the same as is was, just run Point.update which is
// cheaper, allows animation, and keeps references to points.
if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) {
each(data, function (point, i) {
oldData[i].update(point, false, null, false);
});
} else {
// Reset properties
series.xIncrement = null;
series.pointRange = hasCategories ? 1 : options.pointRange;
series.colorCounter = 0; // for series with colorByPoint (#1547)
// Update parallel arrays
each(this.parallelArrays, function (key) {
series[key + 'Data'].length = 0;
});
// In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
// first value is tested, and we assume that all the rest are defined the same
// way. Although the 'for' loops are similar, they are repeated inside each
// if-else conditional for max performance.
if (turboThreshold && dataLength > turboThreshold) {
// find the first non-null point
i = 0;
while (firstPoint === null && i < dataLength) {
firstPoint = data[i];
i++;
}
if (isNumber(firstPoint)) { // assume all points are numbers
var x = pick(options.pointStart, 0),
pointInterval = pick(options.pointInterval, 1);
for (i = 0; i < dataLength; i++) {
xData[i] = x;
yData[i] = data[i];
x += pointInterval;
}
series.xIncrement = x;
} else if (isArray(firstPoint)) { // assume all points are arrays
if (valueCount) { // [x, low, high] or [x, o, h, l, c]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt.slice(1, valueCount + 1);
}
} else { // [x, y]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt[1];
}
}
} else {
error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
}
} else {
for (i = 0; i < dataLength; i++) {
if (data[i] !== UNDEFINED) { // stray commas in oldIE
pt = { series: series };
series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
series.updateParallelArrays(pt, i);
if (hasCategories && pt.name) {
xAxis.names[pt.x] = pt.name; // #2046
}
}
}
}
// Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
if (isString(yData[0])) {
error(14, true);
}
series.data = [];
series.options.data = data;
//series.zData = zData;
// destroy old points
i = oldDataLength;
while (i--) {
if (oldData[i] && oldData[i].destroy) {
oldData[i].destroy();
}
}
// reset minRange (#878)
if (xAxis) {
xAxis.minRange = xAxis.userMinRange;
}
// redraw
series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
animation = false;
}
if (redraw) {
chart.redraw(animation);
}
},
/**
* Process the data by cropping away unused data points if the series is longer
* than the crop threshold. This saves computing time for lage series.
*/
processData: function (force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
isCartesian = series.isCartesian,
xExtremes,
min,
max;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
if (xAxis) {
xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
min = xExtremes.min;
max = xExtremes.max;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
}
}
// Find the closest distance between processed points
for (i = processedXData.length - 1; i >= 0; i--) {
distance = processedXData[i] - processedXData[i - 1];
if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
closestPointRange = distance;
// Unsorted data is not supported by the line tooltip, as well as data grouping and
// navigation in Stock charts (#725) and width calculation of columns (#1900)
} else if (distance < 0 && series.requireSorting) {
error(15);
}
}
// Record the properties
series.cropped = cropped; // undefined or true
series.cropStart = cropStart;
series.processedXData = processedXData;
series.processedYData = processedYData;
if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
series.pointRange = closestPointRange || 1;
}
series.closestPointRange = closestPointRange;
},
/**
* Iterate over xData and crop values between min and max. Returns object containing crop start/end
* cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
*/
cropData: function (xData, yData, min, max) {
var dataLength = xData.length,
cropStart = 0,
cropEnd = dataLength,
cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
i;
// iterate up to find slice start
for (i = 0; i < dataLength; i++) {
if (xData[i] >= min) {
cropStart = mathMax(0, i - cropShoulder);
break;
}
}
// proceed to find slice end
for (; i < dataLength; i++) {
if (xData[i] > max) {
cropEnd = i + cropShoulder;
break;
}
}
return {
xData: xData.slice(cropStart, cropEnd),
yData: yData.slice(cropStart, cropEnd),
start: cropStart,
end: cropEnd
};
},
/**
* Generate the data point after the data has been processed by cropping away
* unused points and optionally grouped in Highcharts Stock.
*/
generatePoints: function () {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
pointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
point = data[cursor];
} else if (dataOptions[cursor] !== UNDEFINED) { // #970
data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
}
points[i] = point;
} else {
// splat the y data in case of ohlc data array
points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
}
points[i].index = cursor; // For faster access in Point.update
}
// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
// swithching view from non-grouped data to grouped data (#637)
if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
for (i = 0; i < dataLength; i++) {
if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
i += processedDataLength;
}
if (data[i]) {
data[i].destroyElements();
data[i].plotX = UNDEFINED; // #1003
}
}
}
series.data = data;
series.points = points;
},
/**
* Calculate Y extremes for visible data
*/
getExtremes: function (yData) {
var xAxis = this.xAxis,
yAxis = this.yAxis,
xData = this.processedXData,
yDataLength,
activeYData = [],
activeCounter = 0,
xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
xMin = xExtremes.min,
xMax = xExtremes.max,
validValue,
withinRange,
dataMin,
dataMax,
x,
y,
i,
j;
yData = yData || this.stackedYData || this.processedYData;
yDataLength = yData.length;
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
// For points within the visible range, including the first point outside the
// visible range, consider y extremes
validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin &&
(xData[i - 1] || x) <= xMax);
if (validValue && withinRange) {
j = y.length;
if (j) { // array, like ohlc or range data
while (j--) {
if (y[j] !== null) {
activeYData[activeCounter++] = y[j];
}
}
} else {
activeYData[activeCounter++] = y;
}
}
}
this.dataMin = pick(dataMin, arrayMin(activeYData));
this.dataMax = pick(dataMax, arrayMax(activeYData));
},
/**
* Translate data points from raw data values to chart specific positioning data
* needed later in drawPoints, drawGraph and drawTracker.
*/
translate: function () {
if (!this.processedXData) { // hidden series
this.processData();
}
this.generatePoints();
var series = this,
options = series.options,
stacking = options.stacking,
xAxis = series.xAxis,
categories = xAxis.categories,
yAxis = series.yAxis,
points = series.points,
dataLength = points.length,
hasModifyValue = !!series.modifyValue,
i,
pointPlacement = options.pointPlacement,
dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
threshold = options.threshold,
plotX,
plotY,
lastPlotX,
closestPointRangePx = Number.MAX_VALUE;
// Translate each point
for (i = 0; i < dataLength; i++) {
var point = points[i],
xValue = point.x,
yValue = point.y,
yBottom = point.low,
stack = stacking && yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey],
pointStack,
stackValues;
// Discard disallowed y values for log axes (#3434)
if (yAxis.isLog && yValue !== null && yValue <= 0) {
point.y = yValue = null;
error(10);
}
// Get the plotX translation
point.plotX = plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591
// Calculate the bottom y value for stacked series
if (stacking && series.visible && stack && stack[xValue]) {
pointStack = stack[xValue];
stackValues = pointStack.points[series.index + ',' + i];
yBottom = stackValues[0];
yValue = stackValues[1];
if (yBottom === 0) {
yBottom = pick(threshold, yAxis.min);
}
if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
yBottom = null;
}
point.total = point.stackTotal = pointStack.total;
point.percentage = pointStack.total && (point.y / pointStack.total * 100);
point.stackY = yValue;
// Place the stack label
pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
}
// Set translated yBottom or remove it
point.yBottom = defined(yBottom) ?
yAxis.translate(yBottom, 0, 1, 0, 1) :
null;
// general hook, used for Highstock compare mode
if (hasModifyValue) {
yValue = series.modifyValue(yValue, point);
}
// Set the the plotY value, reset it for redraws
point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201
UNDEFINED;
point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519
plotX >= 0 && plotX <= xAxis.len;
// Set client related positions for mouse tracking
point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514
point.negative = point.y < (threshold || 0);
// some API data
point.category = categories && categories[point.x] !== UNDEFINED ?
categories[point.x] : point.x;
// Determine auto enabling of markers (#3635)
if (i) {
closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX));
}
lastPlotX = plotX;
}
series.closestPointRangePx = closestPointRangePx;
// now that we have the cropped data, build the segments
series.getSegments();
},
/**
* Set the clipping for the series. For animated series it is called twice, first to initiate
* animating the clip then the second time without the animation to set the final clip.
*/
setClip: function (animation) {
var chart = this.chart,
renderer = chart.renderer,
inverted = chart.inverted,
seriesClipBox = this.clipBox,
clipBox = seriesClipBox || chart.clipBox,
sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height].join(','),
clipRect = chart[sharedClipKey],
markerClipRect = chart[sharedClipKey + 'm'];
// If a clipping rectangle with the same properties is currently present in the chart, use that.
if (!clipRect) {
// When animation is set, prepare the initial positions
if (animation) {
clipBox.width = 0;
chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
-99, // include the width of the first marker
inverted ? -chart.plotLeft : -chart.plotTop,
99,
inverted ? chart.chartWidth : chart.chartHeight
);
}
chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox);
}
if (animation) {
clipRect.count += 1;
}
if (this.options.clip !== false) {
this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect);
this.markerGroup.clip(markerClipRect);
this.sharedClipKey = sharedClipKey;
}
// Remove the shared clipping rectancgle when all series are shown
if (!animation) {
clipRect.count -= 1;
if (clipRect.count <= 0 && sharedClipKey && chart[sharedClipKey]) {
if (!seriesClipBox) {
chart[sharedClipKey] = chart[sharedClipKey].destroy();
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
}
}
}
},
/**
* Animate in the series
*/
animate: function (init) {
var series = this,
chart = series.chart,
clipRect,
animation = series.options.animation,
sharedClipKey;
// Animation option is set to true
if (animation && !isObject(animation)) {
animation = defaultPlotOptions[series.type].animation;
}
// Initialize the animation. Set up the clipping rectangle.
if (init) {
series.setClip(animation);
// Run the animation
} else {
sharedClipKey = this.sharedClipKey;
clipRect = chart[sharedClipKey];
if (clipRect) {
clipRect.animate({
width: chart.plotSizeX
}, animation);
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'].animate({
width: chart.plotSizeX + 99
}, animation);
}
// Delete this function to allow it only once
series.animate = null;
}
},
/**
* This runs after animation to land on the final plot clipping
*/
afterAnimate: function () {
this.setClip();
fireEvent(this, 'afterAnimate');
},
/**
* Draw the markers
*/
drawPoints: function () {
var series = this,
pointAttr,
points = series.points,
chart = series.chart,
plotX,
plotY,
i,
point,
radius,
symbol,
isImage,
graphic,
options = series.options,
seriesMarkerOptions = options.marker,
seriesPointAttr = series.pointAttr[''],
pointMarkerOptions,
hasPointMarker,
enabled,
isInside,
markerGroup = series.markerGroup,
xAxis = series.xAxis,
globallyEnabled = pick(
seriesMarkerOptions.enabled,
xAxis.isRadial,
series.closestPointRangePx > 2 * seriesMarkerOptions.radius
);
if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {
i = points.length;
while (i--) {
point = points[i];
plotX = mathFloor(point.plotX); // #1843
plotY = point.plotY;
graphic = point.graphic;
pointMarkerOptions = point.marker || {};
hasPointMarker = !!point.marker;
enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
isInside = point.isInside;
// only draw the point if y is defined
if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
// shortcuts
pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr;
radius = pointAttr.r;
symbol = pick(pointMarkerOptions.symbol, series.symbol);
isImage = symbol.indexOf('url') === 0;
if (graphic) { // update
graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
.animate(extend({
x: plotX - radius,
y: plotY - radius
}, graphic.symbolName ? { // don't apply to image symbols #507
width: 2 * radius,
height: 2 * radius
} : {}));
} else if (isInside && (radius > 0 || isImage)) {
point.graphic = graphic = chart.renderer.symbol(
symbol,
plotX - radius,
plotY - radius,
2 * radius,
2 * radius,
hasPointMarker ? pointMarkerOptions : seriesMarkerOptions
)
.attr(pointAttr)
.add(markerGroup);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
}
}
},
/**
* Convert state properties from API naming conventions to SVG attributes
*
* @param {Object} options API options object
* @param {Object} base1 SVG attribute object to inherit from
* @param {Object} base2 Second level SVG attribute object to inherit from
*/
convertAttribs: function (options, base1, base2, base3) {
var conversion = this.pointAttrToOptions,
attr,
option,
obj = {};
options = options || {};
base1 = base1 || {};
base2 = base2 || {};
base3 = base3 || {};
for (attr in conversion) {
option = conversion[attr];
obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
}
return obj;
},
/**
* Get the state attributes. Each series type has its own set of attributes
* that are allowed to change on a point's state change. Series wide attributes are stored for
* all series, and additionally point specific attributes are stored for all
* points with individual marker options. If such options are not defined for the point,
* a reference to the series wide attributes is stored in point.pointAttr.
*/
getAttribs: function () {
var series = this,
seriesOptions = series.options,
normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
stateOptions = normalOptions.states,
stateOptionsHover = stateOptions[HOVER_STATE],
pointStateOptionsHover,
seriesColor = series.color,
seriesNegativeColor = series.options.negativeColor,
normalDefaults = {
stroke: seriesColor,
fill: seriesColor
},
points = series.points || [], // #927
i,
point,
seriesPointAttr = [],
pointAttr,
pointAttrToOptions = series.pointAttrToOptions,
hasPointSpecificOptions = series.hasPointSpecificOptions,
defaultLineColor = normalOptions.lineColor,
defaultFillColor = normalOptions.fillColor,
turboThreshold = seriesOptions.turboThreshold,
zones = series.zones,
zoneAxis = series.zoneAxis || 'y',
attr,
key;
// series type specific modifications
if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
// if no hover radius is given, default to normal radius + 2
stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus;
stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus;
} else { // column, bar, pie
// if no hover color is given, brighten the normal color
stateOptionsHover.color = stateOptionsHover.color ||
Color(stateOptionsHover.color || seriesColor)
.brighten(stateOptionsHover.brightness).get();
// if no hover negativeColor is given, brighten the normal negativeColor
stateOptionsHover.negativeColor = stateOptionsHover.negativeColor ||
Color(stateOptionsHover.negativeColor || seriesNegativeColor)
.brighten(stateOptionsHover.brightness).get();
}
// general point attributes for the series normal state
seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
// HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
each([HOVER_STATE, SELECT_STATE], function (state) {
seriesPointAttr[state] =
series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
});
// set it
series.pointAttr = seriesPointAttr;
// Generate the point-specific attribute collections if specific point
// options are given. If not, create a referance to the series wide point
// attributes
i = points.length;
if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) {
while (i--) {
point = points[i];
normalOptions = (point.options && point.options.marker) || point.options;
if (normalOptions && normalOptions.enabled === false) {
normalOptions.radius = 0;
}
if (zones.length) {
var j = 0,
threshold = zones[j];
while (point[zoneAxis] >= threshold.value) {
threshold = zones[++j];
}
point.color = point.fillColor = threshold.color;
}
hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
// check if the point has specific visual options
if (point.options) {
for (key in pointAttrToOptions) {
if (defined(normalOptions[pointAttrToOptions[key]])) {
hasPointSpecificOptions = true;
}
}
}
// a specific marker config object is defined for the individual point:
// create it's own attribute collection
if (hasPointSpecificOptions) {
normalOptions = normalOptions || {};
pointAttr = [];
stateOptions = normalOptions.states || {}; // reassign for individual point
pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
// Handle colors for column and pies
if (!seriesOptions.marker) { // column, bar, point
// If no hover color is given, brighten the normal color. #1619, #2579
pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) ||
Color(point.color)
.brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness)
.get();
}
// normal point state inherits series wide normal state
attr = { color: point.color }; // #868
if (!defaultFillColor) { // Individual point color or negative color markers (#2219)
attr.fillColor = point.color;
}
if (!defaultLineColor) {
attr.lineColor = point.color; // Bubbles take point color, line markers use white
}
pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]);
// inherit from point normal and series hover
pointAttr[HOVER_STATE] = series.convertAttribs(
stateOptions[HOVER_STATE],
seriesPointAttr[HOVER_STATE],
pointAttr[NORMAL_STATE]
);
// inherit from point normal and series hover
pointAttr[SELECT_STATE] = series.convertAttribs(
stateOptions[SELECT_STATE],
seriesPointAttr[SELECT_STATE],
pointAttr[NORMAL_STATE]
);
// no marker config object is created: copy a reference to the series-wide
// attribute collection
} else {
pointAttr = seriesPointAttr;
}
point.pointAttr = pointAttr;
}
}
},
/**
* Clear DOM objects and free up memory
*/
destroy: function () {
var series = this,
chart = series.chart,
issue134 = /AppleWebKit\/533/.test(userAgent),
destroy,
i,
data = series.data || [],
point,
prop,
axis;
// add event hook
fireEvent(series, 'destroy');
// remove all events
removeEvent(series);
// erase from axes
each(series.axisTypes || [], function (AXIS) {
axis = series[AXIS];
if (axis) {
erase(axis.series, series);
axis.isDirty = axis.forceRedraw = true;
}
});
// remove legend items
if (series.legendItem) {
series.chart.legend.destroyItem(series);
}
// destroy all points with their elements
i = data.length;
while (i--) {
point = data[i];
if (point && point.destroy) {
point.destroy();
}
}
series.points = null;
// Clear the animation timeout if we are destroying the series during initial animation
clearTimeout(series.animationTimeout);
// destroy all SVGElements associated to the series
each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker',
'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) {
if (series[prop]) {
// issue 134 workaround
destroy = issue134 && prop === 'group' ?
'hide' :
'destroy';
series[prop][destroy]();
}
});
// remove from hoverSeries
if (chart.hoverSeries === series) {
chart.hoverSeries = null;
}
erase(chart.series, series);
// clear all members
for (prop in series) {
delete series[prop];
}
},
/**
* Return the graph path of a segment
*/
getSegmentPath: function (segment) {
var series = this,
segmentPath = [],
step = series.options.step;
// build the segment line
each(segment, function (point, i) {
var plotX = point.plotX,
plotY = point.plotY,
lastPoint;
if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
} else {
// moveTo or lineTo
segmentPath.push(i ? L : M);
// step line?
if (step && i) {
lastPoint = segment[i - 1];
if (step === 'right') {
segmentPath.push(
lastPoint.plotX,
plotY
);
} else if (step === 'center') {
segmentPath.push(
(lastPoint.plotX + plotX) / 2,
lastPoint.plotY,
(lastPoint.plotX + plotX) / 2,
plotY
);
} else {
segmentPath.push(
plotX,
lastPoint.plotY
);
}
}
// normal line to next point
segmentPath.push(
point.plotX,
point.plotY
);
}
});
return segmentPath;
},
/**
* Get the graph path
*/
getGraphPath: function () {
var series = this,
graphPath = [],
segmentPath,
singlePoints = []; // used in drawTracker
// Divide into segments and build graph and area paths
each(series.segments, function (segment) {
segmentPath = series.getSegmentPath(segment);
// add the segment to the graph, or a single point for tracking
if (segment.length > 1) {
graphPath = graphPath.concat(segmentPath);
} else {
singlePoints.push(segment[0]);
}
});
// Record it for use in drawGraph and drawTracker, and return graphPath
series.singlePoints = singlePoints;
series.graphPath = graphPath;
return graphPath;
},
/**
* Draw the actual graph
*/
drawGraph: function () {
var series = this,
options = this.options,
props = [['graph', options.lineColor || this.color, options.dashStyle]],
lineWidth = options.lineWidth,
roundCap = options.linecap !== 'square',
graphPath = this.getGraphPath(),
fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph
zones = this.zones;
each(zones, function (threshold, i) {
props.push(['colorGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]);
});
// Draw the graph
each(props, function (prop, i) {
var graphKey = prop[0],
graph = series[graphKey],
attribs;
if (graph) {
stop(graph); // cancel running animations, #459
graph.animate({ d: graphPath });
} else if ((lineWidth || fillColor) && graphPath.length) { // #1487
attribs = {
stroke: prop[1],
'stroke-width': lineWidth,
fill: fillColor,
zIndex: 1 // #1069
};
if (prop[2]) {
attribs.dashstyle = prop[2];
} else if (roundCap) {
attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
}
series[graphKey] = series.chart.renderer.path(graphPath)
.attr(attribs)
.add(series.group)
.shadow(!i && options.shadow);
}
});
},
/**
* Clip the graphs into the positive and negative coloured graphs
*/
applyZones: function () {
var series = this,
chart = this.chart,
renderer = chart.renderer,
zones = this.zones,
translatedFrom,
translatedTo,
clips = this.clips || [],
clipAttr,
graph = this.graph,
area = this.area,
chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight),
zoneAxis = this.zoneAxis || 'y',
axis = this[zoneAxis + 'Axis'],
reversed = axis.reversed,
horiz = axis.horiz;
if (zones.length && (graph || area)) {
// The use of the Color Threshold assumes there are no gaps
// so it is safe to hide the original graph and area
graph.hide();
if (area) { area.hide(); }
// Create the clips
each(zones, function (threshold, i) {
translatedFrom = pick(translatedTo, (reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(axis.min))));
translatedTo = mathRound(axis.toPixels(pick(threshold.value, axis.max), true));
if (axis.isXAxis) {
clipAttr = {
x: reversed ? translatedTo : translatedFrom,
y: 0,
width: Math.abs(translatedFrom - translatedTo),
height: chartSizeMax
};
if (!horiz) {
clipAttr.x = chart.plotHeight - clipAttr.x;
}
} else {
clipAttr = {
x: 0,
y: reversed ? translatedFrom : translatedTo,
width: chartSizeMax,
height: Math.abs(translatedFrom - translatedTo)
};
if (horiz) {
clipAttr.y = chart.plotWidth - clipAttr.y;
}
}
/// VML SUPPPORT
if (chart.inverted && renderer.isVML) {
if (axis.isXAxis) {
clipAttr = {
x: 0,
y: reversed ? translatedFrom : translatedTo,
height: clipAttr.width,
width: chart.chartWidth
};
} else {
clipAttr = {
x: clipAttr.y - chart.plotLeft - chart.spacingBox.x,
y: 0,
width: clipAttr.height,
height: chart.chartHeight
};
}
}
/// END OF VML SUPPORT
if (clips[i]) {
clips[i].animate(clipAttr);
} else {
clips[i] = renderer.clipRect(clipAttr);
series['colorGraph' + i].clip(clips[i]);
if (area) {
series['colorArea' + i].clip(clips[i]);
}
}
});
this.clips = clips;
}
},
/**
* Initialize and perform group inversion on series.group and series.markerGroup
*/
invertGroups: function () {
var series = this,
chart = series.chart;
// Pie, go away (#1736)
if (!series.xAxis) {
return;
}
// A fixed size is needed for inversion to work
function setInvert() {
var size = {
width: series.yAxis.len,
height: series.xAxis.len
};
each(['group', 'markerGroup'], function (groupName) {
if (series[groupName]) {
series[groupName].attr(size).invert();
}
});
}
addEvent(chart, 'resize', setInvert); // do it on resize
addEvent(series, 'destroy', function () {
removeEvent(chart, 'resize', setInvert);
});
// Do it now
setInvert(); // do it now
// On subsequent render and redraw, just do setInvert without setting up events again
series.invertGroups = setInvert;
},
/**
* General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
* series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
*/
plotGroup: function (prop, name, visibility, zIndex, parent) {
var group = this[prop],
isNew = !group;
// Generate it on first call
if (isNew) {
this[prop] = group = this.chart.renderer.g(name)
.attr({
visibility: visibility,
zIndex: zIndex || 0.1 // IE8 needs this
})
.add(parent);
}
// Place it on first and subsequent (redraw) calls
group[isNew ? 'attr' : 'animate'](this.getPlotBox());
return group;
},
/**
* Get the translation and scale for the plot area of this series
*/
getPlotBox: function () {
var chart = this.chart,
xAxis = this.xAxis,
yAxis = this.yAxis;
// Swap axes for inverted (#2339)
if (chart.inverted) {
xAxis = yAxis;
yAxis = this.xAxis;
}
return {
translateX: xAxis ? xAxis.left : chart.plotLeft,
translateY: yAxis ? yAxis.top : chart.plotTop,
scaleX: 1, // #1623
scaleY: 1
};
},
/**
* Render the graph and markers
*/
render: function () {
var series = this,
chart = series.chart,
group,
options = series.options,
animation = options.animation,
// Animation doesn't work in IE8 quirks when the group div is hidden,
// and looks bad in other oldIE
animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0,
visibility = series.visible ? VISIBLE : HIDDEN,
zIndex = options.zIndex,
hasRendered = series.hasRendered,
chartSeriesGroup = chart.seriesGroup;
// the group
group = series.plotGroup(
'group',
'series',
visibility,
zIndex,
chartSeriesGroup
);
series.markerGroup = series.plotGroup(
'markerGroup',
'markers',
visibility,
zIndex,
chartSeriesGroup
);
// initiate the animation
if (animDuration) {
series.animate(true);
}
// cache attributes for shapes
series.getAttribs();
// SVGRenderer needs to know this before drawing elements (#1089, #1795)
group.inverted = series.isCartesian ? chart.inverted : false;
// draw the graph if any
if (series.drawGraph) {
series.drawGraph();
series.applyZones();
}
each(series.points, function (point) {
if (point.redraw) {
point.redraw();
}
});
// draw the data labels (inn pies they go before the points)
if (series.drawDataLabels) {
series.drawDataLabels();
}
// draw the points
if (series.visible) {
series.drawPoints();
}
// draw the mouse tracking area
if (series.drawTracker && series.options.enableMouseTracking !== false) {
series.drawTracker();
}
// Handle inverted series and tracker groups
if (chart.inverted) {
series.invertGroups();
}
// Run the animation
if (animDuration) {
series.animate();
}
// Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
// which should be available to the user).
if (!hasRendered) {
if (animDuration) {
series.animationTimeout = setTimeout(function () {
series.afterAnimate();
}, animDuration);
} else {
series.afterAnimate();
}
}
series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
// (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
series.hasRendered = true;
},
/**
* Redraw the series after an update in the axes.
*/
redraw: function () {
var series = this,
chart = series.chart,
wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
group = series.group,
xAxis = series.xAxis,
yAxis = series.yAxis;
// reposition on resize
if (group) {
if (chart.inverted) {
group.attr({
width: chart.plotWidth,
height: chart.plotHeight
});
}
group.animate({
translateX: pick(xAxis && xAxis.left, chart.plotLeft),
translateY: pick(yAxis && yAxis.top, chart.plotTop)
});
}
series.translate();
series.render();
if (wasDirtyData) {
fireEvent(series, 'updatedData');
}
},
/**
* KD Tree && PointSearching Implementation
*/
kdDimensions: 1,
kdTree: null,
kdAxisArray: ['plotX', 'plotY'],
kdComparer: 'distX',
searchPoint: function (e) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
inverted = series.chart.inverted;
e.plotX = inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos;
e.plotY = inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos;
return this.searchKDTree(e);
},
buildKDTree: function () {
var series = this,
dimensions = series.kdDimensions;
// Internal function
function _kdtree(points, depth, dimensions) {
var axis, median, length = points && points.length;
if (length) {
// alternate between the axis
axis = series.kdAxisArray[depth % dimensions];
// sort point array
points.sort(function(a, b) {
return a[axis] - b[axis];
});
median = Math.floor(length / 2);
// build and return node
return {
point: points[median],
left: _kdtree(points.slice(0, median), depth + 1, dimensions),
right: _kdtree(points.slice(median + 1), depth + 1, dimensions)
};
}
}
function startRecursive() {
series.kdTree = _kdtree(series.points, dimensions, dimensions);
}
delete series.kdTree;
if (series.options.kdSync) { // For testing tooltips, don't build async
startRecursive();
} else {
setTimeout(startRecursive);
}
},
searchKDTree: function (point) {
var series = this,
kdComparer = this.kdComparer,
kdX = this.kdAxisArray[0],
kdY = this.kdAxisArray[1];
// Internal function
function _distance(p1, p2) {
var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null,
y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null,
r = (x || 0) + (y || 0);
return {
distX: defined(x) ? Math.sqrt(x) : Number.MAX_VALUE,
distY: defined(y) ? Math.sqrt(y) : Number.MAX_VALUE,
distR: defined(r) ? Math.sqrt(r) : Number.MAX_VALUE
};
}
function _search(search, tree, depth, dimensions) {
var point = tree.point,
axis = series.kdAxisArray[depth % dimensions],
tdist,
sideA,
sideB,
ret = point,
nPoint1,
nPoint2;
point.dist = _distance(search, point);
// Pick side based on distance to splitting point
tdist = search[axis] - point[axis];
sideA = tdist < 0 ? 'left' : 'right';
// End of tree
if (tree[sideA]) {
nPoint1 =_search(search, tree[sideA], depth + 1, dimensions);
ret = (nPoint1.dist[kdComparer] < ret.dist[kdComparer] ? nPoint1 : point);
sideB = tdist < 0 ? 'right' : 'left';
if (tree[sideB]) {
// compare distance to current best to splitting point to decide wether to check side B or not
if (Math.sqrt(tdist*tdist) < ret.dist[kdComparer]) {
nPoint2 = _search(search, tree[sideB], depth + 1, dimensions);
ret = (nPoint2.dist[kdComparer] < ret.dist[kdComparer] ? nPoint2 : ret);
}
}
}
return ret;
}
if (!this.kdTree) {
this.buildKDTree();
}
if (this.kdTree) {
return _search(point,
this.kdTree, this.kdDimensions, this.kdDimensions);
} else {
return UNDEFINED;
}
}
}; // end Series prototype
/**
* The class for stack items
*/
function StackItem(axis, options, isNegative, x, stackOption) {
var inverted = axis.chart.inverted;
this.axis = axis;
// Tells if the stack is negative
this.isNegative = isNegative;
// Save the options to be able to style the label
this.options = options;
// Save the x value to be able to position the label later
this.x = x;
// Initialize total value
this.total = null;
// This will keep each points' extremes stored by series.index and point index
this.points = {};
// Save the stack option on the series configuration object, and whether to treat it as percent
this.stack = stackOption;
// The align options and text align varies on whether the stack is negative and
// if the chart is inverted or not.
// First test the user supplied value, then use the dynamic.
this.alignOptions = {
align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
};
this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
}
StackItem.prototype = {
destroy: function () {
destroyObjectProperties(this, this.axis);
},
/**
* Renders the stack total label and adds it to the stack label group.
*/
render: function (group) {
var options = this.options,
formatOption = options.format,
str = formatOption ?
format(formatOption, this) :
options.formatter.call(this); // format the text in the label
// Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
if (this.label) {
this.label.attr({text: str, visibility: HIDDEN});
// Create new label
} else {
this.label =
this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
.css(options.style) // apply style
.attr({
align: this.textAlign, // fix the text-anchor
rotation: options.rotation, // rotation
visibility: HIDDEN // hidden until setOffset is called
})
.add(group); // add to the labels-group
}
},
/**
* Sets the offset that the stack has from the x value and repositions the label.
*/
setOffset: function (xOffset, xWidth) {
var stackItem = this,
axis = stackItem.axis,
chart = axis.chart,
inverted = chart.inverted,
neg = this.isNegative, // special treatment is needed for negative stacks
y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
yZero = axis.translate(0), // stack origin
h = mathAbs(y - yZero), // stack height
x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
plotHeight = chart.plotHeight,
stackBox = { // this is the box for the complete stack
x: inverted ? (neg ? y : y - h) : x,
y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
width: inverted ? h : xWidth,
height: inverted ? xWidth : h
},
label = this.label,
alignAttr;
if (label) {
label.align(this.alignOptions, null, stackBox); // align the label to the box
// Set visibility (#678)
alignAttr = label.alignAttr;
label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true);
}
}
};
// Stacking methods defined on the Axis prototype
/**
* Build the stacks from top down
*/
Axis.prototype.buildStacks = function () {
var series = this.series,
reversedStacks = pick(this.options.reversedStacks, true),
i = series.length;
if (!this.isXAxis) {
this.usePercentage = false;
while (i--) {
series[reversedStacks ? i : series.length - i - 1].setStackedPoints();
}
// Loop up again to compute percent stack
if (this.usePercentage) {
for (i = 0; i < series.length; i++) {
series[i].setPercentStacks();
}
}
}
};
Axis.prototype.renderStackTotals = function () {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
stacks = axis.stacks,
stackKey,
oneStack,
stackCategory,
stackTotalGroup = axis.stackTotalGroup;
// Create a separate group for the stack total labels
if (!stackTotalGroup) {
axis.stackTotalGroup = stackTotalGroup =
renderer.g('stack-labels')
.attr({
visibility: VISIBLE,
zIndex: 6
})
.add();
}
// plotLeft/Top will change when y axis gets wider so we need to translate the
// stackTotalGroup at every render call. See bug #506 and #516
stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
// Render each stack total
for (stackKey in stacks) {
oneStack = stacks[stackKey];
for (stackCategory in oneStack) {
oneStack[stackCategory].render(stackTotalGroup);
}
}
};
// Stacking methods defnied for Series prototype
/**
* Adds series' points value to corresponding stack
*/
Series.prototype.setStackedPoints = function () {
if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) {
return;
}
var series = this,
xData = series.processedXData,
yData = series.processedYData,
stackedYData = [],
yDataLength = yData.length,
seriesOptions = series.options,
threshold = seriesOptions.threshold,
stackOption = seriesOptions.stack,
stacking = seriesOptions.stacking,
stackKey = series.stackKey,
negKey = '-' + stackKey,
negStacks = series.negStacks,
yAxis = series.yAxis,
stacks = yAxis.stacks,
oldStacks = yAxis.oldStacks,
isNegative,
stack,
other,
key,
pointKey,
i,
x,
y;
// loop over the non-null y values and read them into a local array
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
pointKey = series.index + ',' + i;
// Read stacked values into a stack based on the x value,
// the sign of y and the stack key. Stacking is also handled for null values (#739)
isNegative = negStacks && y < threshold;
key = isNegative ? negKey : stackKey;
// Create empty object for this stack if it doesn't exist yet
if (!stacks[key]) {
stacks[key] = {};
}
// Initialize StackItem for this x
if (!stacks[key][x]) {
if (oldStacks[key] && oldStacks[key][x]) {
stacks[key][x] = oldStacks[key][x];
stacks[key][x].total = null;
} else {
stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption);
}
}
// If the StackItem doesn't exist, create it first
stack = stacks[key][x];
stack.points[pointKey] = [stack.cum || 0];
// Add value to the stack total
if (stacking === 'percent') {
// Percent stacked column, totals are the same for the positive and negative stacks
other = isNegative ? stackKey : negKey;
if (negStacks && stacks[other] && stacks[other][x]) {
other = stacks[other][x];
stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0;
// Percent stacked areas
} else {
stack.total = correctFloat(stack.total + (mathAbs(y) || 0));
}
} else {
stack.total = correctFloat(stack.total + (y || 0));
}
stack.cum = (stack.cum || 0) + (y || 0);
stack.points[pointKey].push(stack.cum);
stackedYData[i] = stack.cum;
}
if (stacking === 'percent') {
yAxis.usePercentage = true;
}
this.stackedYData = stackedYData; // To be used in getExtremes
// Reset old stacks
yAxis.oldStacks = {};
};
/**
* Iterate over all stacks and compute the absolute values to percent
*/
Series.prototype.setPercentStacks = function () {
var series = this,
stackKey = series.stackKey,
stacks = series.yAxis.stacks,
processedXData = series.processedXData;
each([stackKey, '-' + stackKey], function (key) {
var i = processedXData.length,
x,
stack,
pointExtremes,
totalFactor;
while (i--) {
x = processedXData[i];
stack = stacks[key] && stacks[key][x];
pointExtremes = stack && stack.points[series.index + ',' + i];
if (pointExtremes) {
totalFactor = stack.total ? 100 / stack.total : 0;
pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value
pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value
series.stackedYData[i] = pointExtremes[1];
}
}
});
};
// Extend the Chart prototype for dynamic methods
extend(Chart.prototype, {
/**
* Add a series dynamically after time
*
* @param {Object} options The config options
* @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
* @return {Object} series The newly created series object
*/
addSeries: function (options, redraw, animation) {
var series,
chart = this;
if (options) {
redraw = pick(redraw, true); // defaults to true
fireEvent(chart, 'addSeries', { options: options }, function () {
series = chart.initSeries(options);
chart.isDirtyLegend = true; // the series array is out of sync with the display
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
return series;
},
/**
* Add an axis to the chart
* @param {Object} options The axis option
* @param {Boolean} isX Whether it is an X axis or a value axis
*/
addAxis: function (options, isX, redraw, animation) {
var key = isX ? 'xAxis' : 'yAxis',
chartOptions = this.options,
axis;
/*jslint unused: false*/
axis = new Axis(this, merge(options, {
index: this[key].length,
isX: isX
}));
/*jslint unused: true*/
// Push the new axis options to the chart options
chartOptions[key] = splat(chartOptions[key] || {});
chartOptions[key].push(options);
if (pick(redraw, true)) {
this.redraw(animation);
}
},
/**
* Dim the chart and show a loading text or symbol
* @param {String} str An optional text to show in the loading label instead of the default one
*/
showLoading: function (str) {
var chart = this,
options = chart.options,
loadingDiv = chart.loadingDiv,
loadingOptions = options.loading,
setLoadingSize = function () {
if (loadingDiv) {
css(loadingDiv, {
left: chart.plotLeft + PX,
top: chart.plotTop + PX,
width: chart.plotWidth + PX,
height: chart.plotHeight + PX
});
}
};
// create the layer at the first call
if (!loadingDiv) {
chart.loadingDiv = loadingDiv = createElement(DIV, {
className: PREFIX + 'loading'
}, extend(loadingOptions.style, {
zIndex: 10,
display: NONE
}), chart.container);
chart.loadingSpan = createElement(
'span',
null,
loadingOptions.labelStyle,
loadingDiv
);
addEvent(chart, 'redraw', setLoadingSize); // #1080
}
// update text
chart.loadingSpan.innerHTML = str || options.lang.loading;
// show it
if (!chart.loadingShown) {
css(loadingDiv, {
opacity: 0,
display: ''
});
animate(loadingDiv, {
opacity: loadingOptions.style.opacity
}, {
duration: loadingOptions.showDuration || 0
});
chart.loadingShown = true;
}
setLoadingSize();
},
/**
* Hide the loading layer
*/
hideLoading: function () {
var options = this.options,
loadingDiv = this.loadingDiv;
if (loadingDiv) {
animate(loadingDiv, {
opacity: 0
}, {
duration: options.loading.hideDuration || 100,
complete: function () {
css(loadingDiv, { display: NONE });
}
});
}
this.loadingShown = false;
}
});
// extend the Point prototype for dynamic methods
extend(Point.prototype, {
/**
* Update the point with new options (typically x/y data) and optionally redraw the series.
*
* @param {Object} options Point options as defined in the series.data array
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
*/
update: function (options, redraw, animation, runEvent) {
var point = this,
series = point.series,
graphic = point.graphic,
i,
chart = series.chart,
seriesOptions = series.options,
names = series.xAxis && series.xAxis.names;
redraw = pick(redraw, true);
function update() {
point.applyOptions(options);
// Update visuals
if (isObject(options) && !isArray(options)) {
// Defer the actual redraw until getAttribs has been called (#3260)
point.redraw = function () {
if (graphic) {
if (options && options.marker && options.marker.symbol) {
point.graphic = graphic.destroy();
} else {
graphic.attr(point.pointAttr[point.state || '']);
}
}
if (options && options.dataLabels && point.dataLabel) { // #2468
point.dataLabel = point.dataLabel.destroy();
}
point.redraw = null;
};
}
// record changes in the parallel arrays
i = point.index;
series.updateParallelArrays(point, i);
if (names && point.name) {
names[point.x] = point.name;
}
seriesOptions.data[i] = point.options;
// redraw
series.isDirty = series.isDirtyData = true;
if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
chart.isDirtyBox = true;
}
if (seriesOptions.legendType === 'point') { // #1831, #1885
chart.legend.destroyItem(point);
}
if (redraw) {
chart.redraw(animation);
}
}
// Fire the event with a default handler of doing the update
if (runEvent === false) { // When called from setData
update();
} else {
point.firePointEvent('update', { options: options }, update);
}
},
/**
* Remove a point and optionally redraw the series and if necessary the axes
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function (redraw, animation) {
this.series.removePoint(inArray(this, this.series.data), redraw, animation);
}
});
// Extend the series prototype for dynamic methods
extend(Series.prototype, {
/**
* Add a point dynamically after chart load time
* @param {Object} options Point options as given in series.data
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean} shift If shift is true, a point is shifted off the start
* of the series as one is appended to the end.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
addPoint: function (options, redraw, shift, animation) {
var series = this,
seriesOptions = series.options,
data = series.data,
graph = series.graph,
area = series.area,
chart = series.chart,
names = series.xAxis && series.xAxis.names,
currentShift = (graph && graph.shift) || 0,
dataOptions = seriesOptions.data,
point,
isInTheMiddle,
xData = series.xData,
x,
i;
setAnimation(animation, chart);
// Make graph animate sideways
if (shift) {
each([graph, area, series.graphNeg, series.areaNeg], function (shape) {
if (shape) {
shape.shift = currentShift + 1;
}
});
}
if (area) {
area.isArea = true; // needed in animation, both with and without shift
}
// Optional redraw, defaults to true
redraw = pick(redraw, true);
// Get options and push the point to xData, yData and series.options. In series.generatePoints
// the Point instance will be created on demand and pushed to the series.data array.
point = { series: series };
series.pointClass.prototype.applyOptions.apply(point, [options]);
x = point.x;
// Get the insertion point
i = xData.length;
if (series.requireSorting && x < xData[i - 1]) {
isInTheMiddle = true;
while (i && xData[i - 1] > x) {
i--;
}
}
series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item
series.updateParallelArrays(point, i); // update it
if (names && point.name) {
names[x] = point.name;
}
dataOptions.splice(i, 0, options);
if (isInTheMiddle) {
series.data.splice(i, 0, null);
series.processData();
}
// Generate points to be added to the legend (#1329)
if (seriesOptions.legendType === 'point') {
series.generatePoints();
}
// Shift the first point off the parallel arrays
// todo: consider series.removePoint(i) method
if (shift) {
if (data[0] && data[0].remove) {
data[0].remove(false);
} else {
data.shift();
series.updateParallelArrays(point, 'shift');
dataOptions.shift();
}
}
// redraw
delete series.kdTree; // #3816 kdTree has to be rebuild.
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
series.getAttribs(); // #1937
chart.redraw();
}
},
/**
* Remove a point (rendered or not), by index
*/
removePoint: function (i, redraw, animation) {
var series = this,
data = series.data,
point = data[i],
points = series.points,
chart = series.chart,
remove = function () {
if (data.length === points.length) {
points.splice(i, 1);
}
data.splice(i, 1);
series.options.data.splice(i, 1);
series.updateParallelArrays(point || { series: series }, 'splice', i, 1);
if (point) {
point.destroy();
}
// redraw
delete series.kdTree; // #3816 kdTree has to be rebuild.
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw();
}
};
setAnimation(animation, chart);
redraw = pick(redraw, true);
// Fire the event with a default handler of removing the point
if (point) {
point.firePointEvent('remove', null, remove);
} else {
remove();
}
},
/**
* Remove a series and optionally redraw the chart
*
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function (redraw, animation) {
var series = this,
chart = series.chart;
redraw = pick(redraw, true);
if (!series.isRemoving) { /* prevent triggering native event in jQuery
(calling the remove function from the remove event) */
series.isRemoving = true;
// fire the event with a default handler of removing the point
fireEvent(series, 'remove', null, function () {
// destroy elements
series.destroy();
// redraw
chart.isDirtyLegend = chart.isDirtyBox = true;
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
series.isRemoving = false;
},
/**
* Update the series with a new set of options
*/
update: function (newOptions, redraw) {
var series = this,
chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
proto = seriesTypes[oldType].prototype,
preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
n;
// If we're changing type or zIndex, create new groups (#3380, #3404)
if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) {
preserve.length = 0;
}
// Make sure groups are not destroyed (#3094)
each(preserve, function (prop) {
preserve[prop] = series[prop];
delete series[prop];
});
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, { data: this.options.data }, newOptions);
// Destroy the series and delete all properties. Reinsert all methods
// and properties from the new type prototype (#2270, #3719)
this.remove(false);
for (n in proto) {
this[n] = UNDEFINED;
}
extend(this, seriesTypes[newOptions.type || oldType].prototype);
// Re-register groups (#3094)
each(preserve, function (prop) {
series[prop] = preserve[prop];
});
this.init(chart, newOptions);
chart.linkSeries(); // Links are lost in this.remove (#3028)
if (pick(redraw, true)) {
chart.redraw(false);
}
}
});
// Extend the Axis.prototype for dynamic methods
extend(Axis.prototype, {
/**
* Update the axis with a new options structure
*/
update: function (newOptions, redraw) {
var chart = this.chart;
newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions);
this.destroy(true);
this._addedPlotLB = UNDEFINED; // #1611, #2887
this.init(chart, extend(newOptions, { events: UNDEFINED }));
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Remove the axis from the chart
*/
remove: function (redraw) {
var chart = this.chart,
key = this.coll, // xAxis or yAxis
axisSeries = this.series,
i = axisSeries.length;
// Remove associated series (#2687)
while (i--) {
if (axisSeries[i]) {
axisSeries[i].remove(false);
}
}
// Remove the axis
erase(chart.axes, this);
erase(chart[key], this);
chart.options[key].splice(this.options.index, 1);
each(chart[key], function (axis, i) { // Re-index, #1706
axis.options.index = i;
});
this.destroy();
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Update the axis title by options
*/
setTitle: function (newTitleOptions, redraw) {
this.update({ title: newTitleOptions }, redraw);
},
/**
* Set new axis categories and optionally redraw
* @param {Array} categories
* @param {Boolean} redraw
*/
setCategories: function (categories, redraw) {
this.update({ categories: categories }, redraw);
}
});
/**
* LineSeries object
*/
var LineSeries = extendClass(Series);
seriesTypes.line = LineSeries;
/**
* Set the default options for area
*/
defaultPlotOptions.area = merge(defaultSeriesOptions, {
threshold: 0
// trackByArea: false,
// lineColor: null, // overrides color, but lets fillColor be unaltered
// fillOpacity: 0.75,
// fillColor: null
});
/**
* AreaSeries object
*/
var AreaSeries = extendClass(Series, {
type: 'area',
/**
* For stacks, don't split segments on null values. Instead, draw null values with
* no marker. Also insert dummy points for any X position that exists in other series
* in the stack.
*/
getSegments: function () {
var series = this,
segments = [],
segment = [],
keys = [],
xAxis = this.xAxis,
yAxis = this.yAxis,
stack = yAxis.stacks[this.stackKey],
pointMap = {},
plotX,
plotY,
points = this.points,
connectNulls = this.options.connectNulls,
i,
x;
if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
// Create a map where we can quickly look up the points by their X value.
for (i = 0; i < points.length; i++) {
pointMap[points[i].x] = points[i];
}
// Sort the keys (#1651)
for (x in stack) {
if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
keys.push(+x);
}
}
keys.sort(function (a, b) {
return a - b;
});
each(keys, function (x) {
var y = 0,
stackPoint;
if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
return;
// The point exists, push it to the segment
} else if (pointMap[x]) {
segment.push(pointMap[x]);
// There is no point for this X value in this series, so we
// insert a dummy point in order for the areas to be drawn
// correctly.
} else {
// Loop down the stack to find the series below this one that has
// a value (#1991)
for (i = series.index; i <= yAxis.series.length; i++) {
stackPoint = stack[x].points[i + ',' + x];
if (stackPoint) {
y = stackPoint[1];
break;
}
}
plotX = xAxis.translate(x);
plotY = yAxis.toPixels(y, true);
segment.push({
y: null,
plotX: plotX,
clientX: plotX,
plotY: plotY,
yBottom: plotY,
onMouseOver: noop
});
}
});
if (segment.length) {
segments.push(segment);
}
} else {
Series.prototype.getSegments.call(this);
segments = this.segments;
}
this.segments = segments;
},
/**
* Extend the base Series getSegmentPath method by adding the path for the area.
* This path is pushed to the series.areaPath property.
*/
getSegmentPath: function (segment) {
var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
i,
options = this.options,
segLength = segmentPath.length,
translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
yBottom;
if (segLength === 3) { // for animation from 1 to two points
areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
}
if (options.stacking && !this.closedStacks) {
// Follow stack back. Todo: implement areaspline. A general solution could be to
// reverse the entire graphPath of the previous series, though may be hard with
// splines and with series with different extremes
for (i = segment.length - 1; i >= 0; i--) {
yBottom = pick(segment[i].yBottom, translatedThreshold);
// step line?
if (i < segment.length - 1 && options.step) {
areaSegmentPath.push(segment[i + 1].plotX, yBottom);
}
areaSegmentPath.push(segment[i].plotX, yBottom);
}
} else { // follow zero line back
this.closeSegment(areaSegmentPath, segment, translatedThreshold);
}
this.areaPath = this.areaPath.concat(areaSegmentPath);
return segmentPath;
},
/**
* Extendable method to close the segment path of an area. This is overridden in polar
* charts.
*/
closeSegment: function (path, segment, translatedThreshold) {
path.push(
L,
segment[segment.length - 1].plotX,
translatedThreshold,
L,
segment[0].plotX,
translatedThreshold
);
},
/**
* Draw the graph and the underlying area. This method calls the Series base
* function and adds the area. The areaPath is calculated in the getSegmentPath
* method called from Series.prototype.drawGraph.
*/
drawGraph: function () {
// Define or reset areaPath
this.areaPath = [];
// Call the base method
Series.prototype.drawGraph.apply(this);
// Define local variables
var series = this,
areaPath = this.areaPath,
options = this.options,
zones = this.zones,
props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
each(zones, function (threshold, i) {
props.push(['colorArea' + i, threshold.color || series.color, threshold.fillColor || options.fillColor]);
});
each(props, function (prop) {
var areaKey = prop[0],
area = series[areaKey];
// Create or update the area
if (area) { // update
area.animate({ d: areaPath });
} else { // create
series[areaKey] = series.chart.renderer.path(areaPath)
.attr({
fill: pick(
prop[2],
Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get()
),
zIndex: 0 // #1069
}).add(series.group);
}
});
},
drawLegendSymbol: LegendSymbolMixin.drawRectangle
});
seriesTypes.area = AreaSeries;
/**
* Set the default options for spline
*/
defaultPlotOptions.spline = merge(defaultSeriesOptions);
/**
* SplineSeries object
*/
var SplineSeries = extendClass(Series, {
type: 'spline',
/**
* Get the spline segment from a given point's previous neighbour to the given point
*/
getPointSpline: function (segment, point, i) {
var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
denom = smoothing + 1,
plotX = point.plotX,
plotY = point.plotY,
lastPoint = segment[i - 1],
nextPoint = segment[i + 1],
leftContX,
leftContY,
rightContX,
rightContY,
ret;
// find control points
if (lastPoint && nextPoint) {
var lastX = lastPoint.plotX,
lastY = lastPoint.plotY,
nextX = nextPoint.plotX,
nextY = nextPoint.plotY,
correction;
leftContX = (smoothing * plotX + lastX) / denom;
leftContY = (smoothing * plotY + lastY) / denom;
rightContX = (smoothing * plotX + nextX) / denom;
rightContY = (smoothing * plotY + nextY) / denom;
// have the two control points make a straight line through main point
correction = ((rightContY - leftContY) * (rightContX - plotX)) /
(rightContX - leftContX) + plotY - rightContY;
leftContY += correction;
rightContY += correction;
// to prevent false extremes, check that control points are between
// neighbouring points' y values
if (leftContY > lastY && leftContY > plotY) {
leftContY = mathMax(lastY, plotY);
rightContY = 2 * plotY - leftContY; // mirror of left control point
} else if (leftContY < lastY && leftContY < plotY) {
leftContY = mathMin(lastY, plotY);
rightContY = 2 * plotY - leftContY;
}
if (rightContY > nextY && rightContY > plotY) {
rightContY = mathMax(nextY, plotY);
leftContY = 2 * plotY - rightContY;
} else if (rightContY < nextY && rightContY < plotY) {
rightContY = mathMin(nextY, plotY);
leftContY = 2 * plotY - rightContY;
}
// record for drawing in next point
point.rightContX = rightContX;
point.rightContY = rightContY;
}
// Visualize control points for debugging
/*
if (leftContX) {
this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
.attr({
stroke: 'red',
'stroke-width': 1,
fill: 'none'
})
.add();
this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'red',
'stroke-width': 1
})
.add();
this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
.attr({
stroke: 'green',
'stroke-width': 1,
fill: 'none'
})
.add();
this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'green',
'stroke-width': 1
})
.add();
}
*/
// moveTo or lineTo
if (!i) {
ret = [M, plotX, plotY];
} else { // curve from last point to this
ret = [
'C',
lastPoint.rightContX || lastPoint.plotX,
lastPoint.rightContY || lastPoint.plotY,
leftContX || plotX,
leftContY || plotY,
plotX,
plotY
];
lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
}
return ret;
}
});
seriesTypes.spline = SplineSeries;
/**
* Set the default options for areaspline
*/
defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
/**
* AreaSplineSeries object
*/
var areaProto = AreaSeries.prototype,
AreaSplineSeries = extendClass(SplineSeries, {
type: 'areaspline',
closedStacks: true, // instead of following the previous graph back, follow the threshold back
// Mix in methods from the area series
getSegmentPath: areaProto.getSegmentPath,
closeSegment: areaProto.closeSegment,
drawGraph: areaProto.drawGraph,
drawLegendSymbol: LegendSymbolMixin.drawRectangle
});
seriesTypes.areaspline = AreaSplineSeries;
/**
* Set the default options for column
*/
defaultPlotOptions.column = merge(defaultSeriesOptions, {
borderColor: '#FFFFFF',
//borderWidth: 1,
borderRadius: 0,
//colorByPoint: undefined,
groupPadding: 0.2,
//grouping: true,
marker: null, // point options are specified in the base options
pointPadding: 0.1,
//pointWidth: null,
minPointLength: 0,
cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
states: {
hover: {
brightness: 0.1,
shadow: false,
halo: false
},
select: {
color: '#C0C0C0',
borderColor: '#000000',
shadow: false
}
},
dataLabels: {
align: null, // auto
verticalAlign: null, // auto
y: null
},
stickyTracking: false,
tooltip: {
distance: 6
},
threshold: 0
});
/**
* ColumnSeries object
*/
var ColumnSeries = extendClass(Series, {
type: 'column',
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'borderColor',
fill: 'color',
r: 'borderRadius'
},
cropShoulder: 0,
directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
trackerGroups: ['group', 'dataLabelsGroup'],
negStacks: true, // use separate negative stacks, unlike area stacks where a negative
// point is substracted from previous (#1910)
/**
* Initialize the series
*/
init: function () {
Series.prototype.init.apply(this, arguments);
var series = this,
chart = series.chart;
// if the series is added dynamically, force redraw of other
// series affected by a new column
if (chart.hasRendered) {
each(chart.series, function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
},
/**
* Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
* pointWidth etc.
*/
getColumnMetrics: function () {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
reversedXAxis = xAxis.reversed,
stackKey,
stackGroups = {},
columnIndex,
columnCount = 0;
// Get the total number of column type series.
// This is called on every series. Consider moving this logic to a
// chart.orderStacks() function and call it on init, addSeries and removeSeries
if (options.grouping === false) {
columnCount = 1;
} else {
each(series.chart.series, function (otherSeries) {
var otherOptions = otherSeries.options,
otherYAxis = otherSeries.yAxis;
if (otherSeries.type === series.type && otherSeries.visible &&
yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
if (otherOptions.stacking) {
stackKey = otherSeries.stackKey;
if (stackGroups[stackKey] === UNDEFINED) {
stackGroups[stackKey] = columnCount++;
}
columnIndex = stackGroups[stackKey];
} else if (otherOptions.grouping !== false) { // #1162
columnIndex = columnCount++;
}
otherSeries.columnIndex = columnIndex;
}
});
}
var categoryWidth = mathMin(
mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
xAxis.len // #1535
),
groupPadding = categoryWidth * options.groupPadding,
groupWidth = categoryWidth - 2 * groupPadding,
pointOffsetWidth = groupWidth / columnCount,
optionPointWidth = options.pointWidth,
pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
pointOffsetWidth * options.pointPadding,
pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
colIndex = (reversedXAxis ?
columnCount - (series.columnIndex || 0) : // #1251
series.columnIndex) || 0,
pointXOffset = pointPadding + (groupPadding + colIndex *
pointOffsetWidth - (categoryWidth / 2)) *
(reversedXAxis ? -1 : 1);
// Save it for reading in linked series (Error bars particularly)
return (series.columnMetrics = {
width: pointWidth,
offset: pointXOffset
});
},
/**
* Translate each point to the plot area coordinate system and find shape positions
*/
translate: function () {
var series = this,
chart = series.chart,
options = series.options,
borderWidth = series.borderWidth = pick(
options.borderWidth,
series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635
),
yAxis = series.yAxis,
threshold = options.threshold,
translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
minPointLength = pick(options.minPointLength, 5),
metrics = series.getColumnMetrics(),
pointWidth = metrics.width,
seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width
pointXOffset = series.pointXOffset = metrics.offset,
xCrisp = -(borderWidth % 2 ? 0.5 : 0),
yCrisp = borderWidth % 2 ? 0.5 : 1;
if (chart.renderer.isVML && chart.inverted) {
yCrisp += 1;
}
// When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual
// columns to have individual sizes. When pointPadding is greater, we strive for equal-width
// columns (#2694).
if (options.pointPadding) {
seriesBarW = mathCeil(seriesBarW);
}
Series.prototype.translate.apply(series);
// Record the new values
each(series.points, function (point) {
var yBottom = pick(point.yBottom, translatedThreshold),
plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241)
barX = point.plotX + pointXOffset,
barW = seriesBarW,
barY = mathMin(plotY, yBottom),
right,
bottom,
fromTop,
barH = mathMax(plotY, yBottom) - barY;
// Handle options.minPointLength
if (mathAbs(barH) < minPointLength) {
if (minPointLength) {
barH = minPointLength;
barY =
mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
yBottom - minPointLength : // keep position
translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485)
}
}
// Cache for access in polar
point.barX = barX;
point.pointWidth = pointWidth;
// Fix the tooltip on center of grouped columns (#1216, #424, #3648)
point.tooltipPos = chart.inverted ?
[yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2] :
[barX + barW / 2, plotY + yAxis.pos - chart.plotTop];
// Round off to obtain crisp edges and avoid overlapping with neighbours (#2694)
right = mathRound(barX + barW) + xCrisp;
barX = mathRound(barX) + xCrisp;
barW = right - barX;
fromTop = mathAbs(barY) < 0.5;
bottom = mathMin(mathRound(barY + barH) + yCrisp, 9e4); // #3575
barY = mathRound(barY) + yCrisp;
barH = bottom - barY;
// Top edges are exceptions
if (fromTop) {
barY -= 1;
barH += 1;
}
// Register shape type and arguments to be used in drawPoints
point.shapeType = 'rect';
point.shapeArgs = {
x: barX,
y: barY,
width: barW,
height: barH
};
});
},
getSymbol: noop,
/**
* Use a solid rectangle like the area series types
*/
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* Columns have no graph
*/
drawGraph: noop,
/**
* Draw the columns. For bars, the series.group is rotated, so the same coordinates
* apply for columns and bars. This method is inherited by scatter series.
*
*/
drawPoints: function () {
var series = this,
chart = this.chart,
options = series.options,
renderer = chart.renderer,
animationLimit = options.animationLimit || 250,
shapeArgs,
pointAttr;
// draw the columns
each(series.points, function (point) {
var plotY = point.plotY,
graphic = point.graphic,
borderAttr;
if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
shapeArgs = point.shapeArgs;
borderAttr = defined(series.borderWidth) ? {
'stroke-width': series.borderWidth
} : {};
pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE];
if (graphic) { // update
stop(graphic);
graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs));
} else {
point.graphic = graphic = renderer[point.shapeType](shapeArgs)
.attr(borderAttr)
.attr(pointAttr)
.add(series.group)
.shadow(options.shadow, null, options.stacking && !options.borderRadius);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
});
},
/**
* Animate the column heights one by one from zero
* @param {Boolean} init Whether to initialize the animation or run it
*/
animate: function (init) {
var series = this,
yAxis = this.yAxis,
options = series.options,
inverted = this.chart.inverted,
attr = {},
translatedThreshold;
if (hasSVG) { // VML is too slow anyway
if (init) {
attr.scaleY = 0.001;
translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
if (inverted) {
attr.translateX = translatedThreshold - yAxis.len;
} else {
attr.translateY = translatedThreshold;
}
series.group.attr(attr);
} else { // run the animation
attr.scaleY = 1;
attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
series.group.animate(attr, series.options.animation);
// delete this function to allow it only once
series.animate = null;
}
}
},
/**
* Remove this series from the chart
*/
remove: function () {
var series = this,
chart = series.chart;
// column and bar series affects other series of the same type
// as they are either stacked or grouped
if (chart.hasRendered) {
each(chart.series, function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
Series.prototype.remove.apply(series, arguments);
}
});
seriesTypes.column = ColumnSeries;
/**
* Set the default options for bar
*/
defaultPlotOptions.bar = merge(defaultPlotOptions.column);
/**
* The Bar series class
*/
var BarSeries = extendClass(ColumnSeries, {
type: 'bar',
inverted: true
});
seriesTypes.bar = BarSeries;
/**
* Set the default options for scatter
*/
defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
lineWidth: 0,
marker: {
enabled: true // Overrides auto-enabling in line series (#3647)
},
tooltip: {
headerFormat: '<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>',
pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
}
});
/**
* The scatter series class
*/
var ScatterSeries = extendClass(Series, {
type: 'scatter',
sorted: false,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
takeOrdinalPosition: false, // #2342
kdDimensions: 2,
kdComparer: 'distR',
drawGraph: function () {
if (this.options.lineWidth) {
Series.prototype.drawGraph.call(this);
}
}
});
seriesTypes.scatter = ScatterSeries;
/**
* Set the default options for pie
*/
defaultPlotOptions.pie = merge(defaultSeriesOptions, {
borderColor: '#FFFFFF',
borderWidth: 1,
center: [null, null],
clip: false,
colorByPoint: true, // always true for pies
dataLabels: {
// align: null,
// connectorWidth: 1,
// connectorColor: point.color,
// connectorPadding: 5,
distance: 30,
enabled: true,
formatter: function () { // #2945
return this.point.name;
},
// softConnector: true,
x: 0
// y: 0
},
ignoreHiddenPoint: true,
//innerSize: 0,
legendType: 'point',
marker: null, // point options are specified in the base options
size: null,
showInLegend: false,
slicedOffset: 10,
states: {
hover: {
brightness: 0.1,
shadow: false
}
},
stickyTracking: false,
tooltip: {
followPointer: true
}
});
/**
* Extended point object for pies
*/
var PiePoint = extendClass(Point, {
/**
* Initiate the pie slice
*/
init: function () {
Point.prototype.init.apply(this, arguments);
var point = this,
toggleSlice;
extend(point, {
visible: point.visible !== false,
name: pick(point.name, 'Slice')
});
// add event listener for select
toggleSlice = function (e) {
point.slice(e.type === 'select');
};
addEvent(point, 'select', toggleSlice);
addEvent(point, 'unselect', toggleSlice);
return point;
},
/**
* Toggle the visibility of the pie slice
* @param {Boolean} vis Whether to show the slice or not. If undefined, the
* visibility is toggled
*/
setVisible: function (vis) {
var point = this,
series = point.series,
chart = series.chart;
// if called without an argument, toggle visibility
point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
// Show and hide associated elements
each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
if (point[key]) {
point[key][vis ? 'show' : 'hide'](true);
}
});
if (point.legendItem) {
chart.legend.colorizeItem(point, vis);
}
// Handle ignore hidden slices
if (!series.isDirty && series.options.ignoreHiddenPoint) {
series.isDirty = true;
chart.redraw();
}
},
/**
* Set or toggle whether the slice is cut out from the pie
* @param {Boolean} sliced When undefined, the slice state is toggled
* @param {Boolean} redraw Whether to redraw the chart. True by default.
*/
slice: function (sliced, redraw, animation) {
var point = this,
series = point.series,
chart = series.chart,
translation;
setAnimation(animation, chart);
// redraw is true by default
redraw = pick(redraw, true);
// if called without an argument, toggle
point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
translation = sliced ? point.slicedTranslation : {
translateX: 0,
translateY: 0
};
point.graphic.animate(translation);
if (point.shadowGroup) {
point.shadowGroup.animate(translation);
}
},
haloPath: function (size) {
var shapeArgs = this.shapeArgs,
chart = this.series.chart;
return this.sliced || !this.visible ? [] : this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, {
innerR: this.shapeArgs.r,
start: shapeArgs.start,
end: shapeArgs.end
});
}
});
/**
* The Pie series class
*/
var PieSeries = {
type: 'pie',
isCartesian: false,
pointClass: PiePoint,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['group', 'dataLabelsGroup'],
axisTypes: [],
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'borderColor',
'stroke-width': 'borderWidth',
fill: 'color'
},
/**
* Pies have one color each point
*/
getColor: noop,
/**
* Animate the pies in
*/
animate: function (init) {
var series = this,
points = series.points,
startAngleRad = series.startAngleRad;
if (!init) {
each(points, function (point) {
var graphic = point.graphic,
args = point.shapeArgs;
if (graphic) {
// start values
graphic.attr({
r: series.center[3] / 2, // animate from inner radius (#779)
start: startAngleRad,
end: startAngleRad
});
// animate
graphic.animate({
r: args.r,
start: args.start,
end: args.end
}, series.options.animation);
}
});
// delete this function to allow it only once
series.animate = null;
}
},
/**
* Extend the basic setData method by running processData and generatePoints immediately,
* in order to access the points from the legend.
*/
setData: function (data, redraw, animation, updatePoints) {
Series.prototype.setData.call(this, data, false, animation, updatePoints);
this.processData();
this.generatePoints();
if (pick(redraw, true)) {
this.chart.redraw(animation);
}
},
/**
* Extend the generatePoints method by adding total and percentage properties to each point
*/
generatePoints: function () {
var i,
total = 0,
points,
len,
point,
ignoreHiddenPoint = this.options.ignoreHiddenPoint;
Series.prototype.generatePoints.call(this);
// Populate local vars
points = this.points;
len = points.length;
// Get the total sum
for (i = 0; i < len; i++) {
point = points[i];
// Disallow negative values (#1530, #3623)
if (point.y < 0) {
point.y = null;
}
total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
}
this.total = total;
// Set each point's properties
for (i = 0; i < len; i++) {
point = points[i];
point.percentage = total > 0 ? (point.y / total) * 100 : 0;
point.total = total;
}
},
/**
* Do translation for pie slices
*/
translate: function (positions) {
this.generatePoints();
var series = this,
cumulative = 0,
precision = 1000, // issue #172
options = series.options,
slicedOffset = options.slicedOffset,
connectorOffset = slicedOffset + options.borderWidth,
start,
end,
angle,
startAngle = options.startAngle || 0,
startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90),
endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90),
circ = endAngleRad - startAngleRad, //2 * mathPI,
points = series.points,
radiusX, // the x component of the radius vector for a given point
radiusY,
labelDistance = options.dataLabels.distance,
ignoreHiddenPoint = options.ignoreHiddenPoint,
i,
len = points.length,
point;
// Get positions - either an integer or a percentage string must be given.
// If positions are passed as a parameter, we're in a recursive loop for adjusting
// space for data labels.
if (!positions) {
series.center = positions = series.getCenter();
}
// utility for getting the x value from a given y, used for anticollision logic in data labels
series.getX = function (y, left) {
angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1));
return positions[0] +
(left ? -1 : 1) *
(mathCos(angle) * (positions[2] / 2 + labelDistance));
};
// Calculate the geometry for each point
for (i = 0; i < len; i++) {
point = points[i];
// set start and end angle
start = startAngleRad + (cumulative * circ);
if (!ignoreHiddenPoint || point.visible) {
cumulative += point.percentage / 100;
}
end = startAngleRad + (cumulative * circ);
// set the shape
point.shapeType = 'arc';
point.shapeArgs = {
x: positions[0],
y: positions[1],
r: positions[2] / 2,
innerR: positions[3] / 2,
start: mathRound(start * precision) / precision,
end: mathRound(end * precision) / precision
};
// The angle must stay within -90 and 270 (#2645)
angle = (end + start) / 2;
if (angle > 1.5 * mathPI) {
angle -= 2 * mathPI;
} else if (angle < -mathPI / 2) {
angle += 2 * mathPI;
}
// Center for the sliced out slice
point.slicedTranslation = {
translateX: mathRound(mathCos(angle) * slicedOffset),
translateY: mathRound(mathSin(angle) * slicedOffset)
};
// set the anchor point for tooltips
radiusX = mathCos(angle) * positions[2] / 2;
radiusY = mathSin(angle) * positions[2] / 2;
point.tooltipPos = [
positions[0] + radiusX * 0.7,
positions[1] + radiusY * 0.7
];
point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0;
point.angle = angle;
// set the anchor point for data labels
connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
point.labelPos = [
positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
positions[0] + radiusX, // landing point for connector
positions[1] + radiusY, // a/a
labelDistance < 0 ? // alignment
'center' :
point.half ? 'right' : 'left', // alignment
angle // center angle
];
}
},
drawGraph: null,
/**
* Draw the data points
*/
drawPoints: function () {
var series = this,
chart = series.chart,
renderer = chart.renderer,
groupTranslation,
//center,
graphic,
//group,
shadow = series.options.shadow,
shadowGroup,
shapeArgs;
if (shadow && !series.shadowGroup) {
series.shadowGroup = renderer.g('shadow')
.add(series.group);
}
// draw the slices
each(series.points, function (point) {
graphic = point.graphic;
shapeArgs = point.shapeArgs;
shadowGroup = point.shadowGroup;
// put the shadow behind all points
if (shadow && !shadowGroup) {
shadowGroup = point.shadowGroup = renderer.g('shadow')
.add(series.shadowGroup);
}
// if the point is sliced, use special translation, else use plot area traslation
groupTranslation = point.sliced ? point.slicedTranslation : {
translateX: 0,
translateY: 0
};
//group.translate(groupTranslation[0], groupTranslation[1]);
if (shadowGroup) {
shadowGroup.attr(groupTranslation);
}
// draw the slice
if (graphic) {
graphic.animate(extend(shapeArgs, groupTranslation));
} else {
point.graphic = graphic = renderer[point.shapeType](shapeArgs)
.setRadialReference(series.center)
.attr(
point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]
)
.attr({
'stroke-linejoin': 'round'
//zIndex: 1 // #2722 (reversed)
})
.attr(groupTranslation)
.add(series.group)
.shadow(shadow, shadowGroup);
}
// detect point specific visibility (#2430)
if (point.visible !== undefined) {
point.setVisible(point.visible);
}
});
},
searchPoint: noop,
/**
* Utility for sorting data labels
*/
sortByAngle: function (points, sign) {
points.sort(function (a, b) {
return a.angle !== undefined && (b.angle - a.angle) * sign;
});
},
/**
* Use a simple symbol from LegendSymbolMixin
*/
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* Use the getCenter method from drawLegendSymbol
*/
getCenter: CenteredSeriesMixin.getCenter,
/**
* Pies don't have point marker symbols
*/
getSymbol: noop
};
PieSeries = extendClass(Series, PieSeries);
seriesTypes.pie = PieSeries;
/**
* Draw the data labels
*/
Series.prototype.drawDataLabels = function () {
var series = this,
seriesOptions = series.options,
cursor = seriesOptions.cursor,
options = seriesOptions.dataLabels,
points = series.points,
pointOptions,
generalOptions,
hasRendered = series.hasRendered || 0,
str,
dataLabelsGroup,
renderer = series.chart.renderer;
if (options.enabled || series._hasPointLabels) {
// Process default alignment of data labels for columns
if (series.dlProcessOptions) {
series.dlProcessOptions(options);
}
// Create a separate group for the data labels to avoid rotation
dataLabelsGroup = series.plotGroup(
'dataLabelsGroup',
'data-labels',
options.defer ? HIDDEN : VISIBLE,
options.zIndex || 6
);
if (pick(options.defer, true)) {
dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300
if (!hasRendered) {
addEvent(series, 'afterAnimate', function () {
if (series.visible) { // #3023, #3024
dataLabelsGroup.show();
}
dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 });
});
}
}
// Make the labels for each point
generalOptions = options;
each(points, function (point) {
var enabled,
dataLabel = point.dataLabel,
labelConfig,
attr,
name,
rotation,
connector = point.connector,
isNew = true,
style,
moreStyle = {};
// Determine if each data label is enabled
pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps
enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282
// If the point is outside the plot area, destroy it. #678, #820
if (dataLabel && !enabled) {
point.dataLabel = dataLabel.destroy();
// Individual labels are disabled if the are explicitly disabled
// in the point options, or if they fall outside the plot area.
} else if (enabled) {
// Create individual options structure that can be extended without
// affecting others
options = merge(generalOptions, pointOptions);
style = options.style;
rotation = options.rotation;
// Get the string
labelConfig = point.getLabelConfig();
str = options.format ?
format(options.format, labelConfig) :
options.formatter.call(labelConfig, options);
// Determine the color
style.color = pick(options.color, style.color, series.color, 'black');
// update existing label
if (dataLabel) {
if (defined(str)) {
dataLabel
.attr({
text: str
});
isNew = false;
} else { // #1437 - the label is shown conditionally
point.dataLabel = dataLabel = dataLabel.destroy();
if (connector) {
point.connector = connector.destroy();
}
}
// create new label
} else if (defined(str)) {
attr = {
//align: align,
fill: options.backgroundColor,
stroke: options.borderColor,
'stroke-width': options.borderWidth,
r: options.borderRadius || 0,
rotation: rotation,
padding: options.padding,
zIndex: 1
};
// Get automated contrast color
if (style.color === 'contrast') {
moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ?
renderer.getContrast(point.color || series.color) :
'#000000';
}
if (cursor) {
moreStyle.cursor = cursor;
}
// Remove unused attributes (#947)
for (name in attr) {
if (attr[name] === UNDEFINED) {
delete attr[name];
}
}
dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation
str,
0,
-999,
null,
null,
null,
options.useHTML
)
.attr(attr)
.css(extend(style, moreStyle))
.add(dataLabelsGroup)
.shadow(options.shadow);
}
if (dataLabel) {
// Now the data label is created and placed at 0,0, so we need to align it
series.alignDataLabel(point, dataLabel, options, null, isNew);
}
}
});
}
};
/**
* Align each individual data label
*/
Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
var chart = this.chart,
inverted = chart.inverted,
plotX = pick(point.plotX, -999),
plotY = pick(point.plotY, -999),
bBox = dataLabel.getBBox(),
baseline = chart.renderer.fontMetrics(options.style.fontSize).b,
rotCorr, // rotation correction
// Math.round for rounding errors (#2683), alignTo to allow column labels (#2700)
visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) ||
(alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))),
alignAttr; // the final position;
if (visible) {
// The alignment box is a singular point
alignTo = extend({
x: inverted ? chart.plotWidth - plotY : plotX,
y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
width: 0,
height: 0
}, alignTo);
// Add the text size for alignment calculation
extend(options, {
width: bBox.width,
height: bBox.height
});
// Allow a hook for changing alignment in the last moment, then do the alignment
if (options.rotation) { // Fancy box alignment isn't supported for rotated text
rotCorr = chart.renderer.rotCorr(baseline, options.rotation); // #3723
dataLabel[isNew ? 'attr' : 'animate']({
x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x,
y: alignTo.y + options.y + alignTo.height / 2
})
.attr({ // #3003
align: options.align
});
} else {
dataLabel.align(options, null, alignTo);
alignAttr = dataLabel.alignAttr;
// Handle justify or crop
if (pick(options.overflow, 'justify') === 'justify') {
this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
} else if (pick(options.crop, true)) {
// Now check that the data label is within the plot area
visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
}
}
}
// Show or hide based on the final aligned position
if (!visible) {
dataLabel.attr({ y: -999 });
dataLabel.placed = false; // don't animate back in
}
};
/**
* If data labels fall partly outside the plot area, align them back in, in a way that
* doesn't hide the point.
*/
Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
var chart = this.chart,
align = options.align,
verticalAlign = options.verticalAlign,
off,
justified,
padding = dataLabel.box ? 0 : (dataLabel.padding || 0);
// Off left
off = alignAttr.x + padding;
if (off < 0) {
if (align === 'right') {
options.align = 'left';
} else {
options.x = -off;
}
justified = true;
}
// Off right
off = alignAttr.x + bBox.width - padding;
if (off > chart.plotWidth) {
if (align === 'left') {
options.align = 'right';
} else {
options.x = chart.plotWidth - off;
}
justified = true;
}
// Off top
off = alignAttr.y + padding;
if (off < 0) {
if (verticalAlign === 'bottom') {
options.verticalAlign = 'top';
} else {
options.y = -off;
}
justified = true;
}
// Off bottom
off = alignAttr.y + bBox.height - padding;
if (off > chart.plotHeight) {
if (verticalAlign === 'top') {
options.verticalAlign = 'bottom';
} else {
options.y = chart.plotHeight - off;
}
justified = true;
}
if (justified) {
dataLabel.placed = !isNew;
dataLabel.align(options, null, alignTo);
}
};
/**
* Override the base drawDataLabels method by pie specific functionality
*/
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawDataLabels = function () {
var series = this,
data = series.data,
point,
chart = series.chart,
options = series.options.dataLabels,
connectorPadding = pick(options.connectorPadding, 10),
connectorWidth = pick(options.connectorWidth, 1),
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
connector,
connectorPath,
softConnector = pick(options.softConnector, true),
distanceOption = options.distance,
seriesCenter = series.center,
radius = seriesCenter[2] / 2,
centerY = seriesCenter[1],
outside = distanceOption > 0,
dataLabel,
dataLabelWidth,
labelPos,
labelHeight,
halves = [// divide the points into right and left halves for anti collision
[], // right
[] // left
],
x,
y,
visibility,
rankArr,
i,
j,
overflow = [0, 0, 0, 0], // top, right, bottom, left
sort = function (a, b) {
return b.y - a.y;
};
// get out if not enabled
if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
return;
}
// run parent method
Series.prototype.drawDataLabels.apply(series);
// arrange points for detection collision
each(data, function (point) {
if (point.dataLabel && point.visible) { // #407, #2510
halves[point.half].push(point);
}
});
/* Loop over the points in each half, starting from the top and bottom
* of the pie to detect overlapping labels.
*/
i = 2;
while (i--) {
var slots = [],
slotsLength,
usedSlots = [],
points = halves[i],
pos,
bottom,
length = points.length,
slotIndex;
if (!length) {
continue;
}
// Sort by angle
series.sortByAngle(points, i - 0.5);
// Assume equal label heights on either hemisphere (#2630)
j = labelHeight = 0;
while (!labelHeight && points[j]) { // #1569
labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968
j++;
}
// Only do anti-collision when we are outside the pie and have connectors (#856)
if (distanceOption > 0) {
// Build the slots
bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight);
for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) {
slots.push(pos);
}
slotsLength = slots.length;
/* Visualize the slots
if (!series.slotElements) {
series.slotElements = [];
}
if (i === 1) {
series.slotElements.forEach(function (elem) {
elem.destroy();
});
series.slotElements.length = 0;
}
slots.forEach(function (pos, no) {
var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
slotY = pos + chart.plotTop;
if (!isNaN(slotX)) {
series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
.attr({
'stroke-width': 1,
stroke: 'silver',
fill: 'rgba(0,0,255,0.1)'
})
.add());
series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4)
.attr({
fill: 'silver'
}).add());
}
});
// */
// if there are more values than available slots, remove lowest values
if (length > slotsLength) {
// create an array for sorting and ranking the points within each quarter
rankArr = [].concat(points);
rankArr.sort(sort);
j = length;
while (j--) {
rankArr[j].rank = j;
}
j = length;
while (j--) {
if (points[j].rank >= slotsLength) {
points.splice(j, 1);
}
}
length = points.length;
}
// The label goes to the nearest open slot, but not closer to the edge than
// the label's index.
for (j = 0; j < length; j++) {
point = points[j];
labelPos = point.labelPos;
var closest = 9999,
distance,
slotI;
// find the closest slot index
for (slotI = 0; slotI < slotsLength; slotI++) {
distance = mathAbs(slots[slotI] - labelPos[1]);
if (distance < closest) {
closest = distance;
slotIndex = slotI;
}
}
// if that slot index is closer to the edges of the slots, move it
// to the closest appropriate slot
if (slotIndex < j && slots[j] !== null) { // cluster at the top
slotIndex = j;
} else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
slotIndex = slotsLength - length + j;
while (slots[slotIndex] === null) { // make sure it is not taken
slotIndex++;
}
} else {
// Slot is taken, find next free slot below. In the next run, the next slice will find the
// slot above these, because it is the closest one
while (slots[slotIndex] === null) { // make sure it is not taken
slotIndex++;
}
}
usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
slots[slotIndex] = null; // mark as taken
}
// sort them in order to fill in from the top
usedSlots.sort(sort);
}
// now the used slots are sorted, fill them up sequentially
for (j = 0; j < length; j++) {
var slot, naturalY;
point = points[j];
labelPos = point.labelPos;
dataLabel = point.dataLabel;
visibility = point.visible === false ? HIDDEN : VISIBLE;
naturalY = labelPos[1];
if (distanceOption > 0) {
slot = usedSlots.pop();
slotIndex = slot.i;
// if the slot next to currrent slot is free, the y value is allowed
// to fall back to the natural position
y = slot.y;
if ((naturalY > y && slots[slotIndex + 1] !== null) ||
(naturalY < y && slots[slotIndex - 1] !== null)) {
y = mathMin(mathMax(0, naturalY), chart.plotHeight);
}
} else {
y = naturalY;
}
// get the x - use the natural x position for first and last slot, to prevent the top
// and botton slice connectors from touching each other on either side
x = options.justify ?
seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i);
// Record the placement and visibility
dataLabel._attr = {
visibility: visibility,
align: labelPos[6]
};
dataLabel._pos = {
x: x + options.x +
({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
y: y + options.y - 10 // 10 is for the baseline (label vs text)
};
dataLabel.connX = x;
dataLabel.connY = y;
// Detect overflowing data labels
if (this.options.size === null) {
dataLabelWidth = dataLabel.width;
// Overflow left
if (x - dataLabelWidth < connectorPadding) {
overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
// Overflow right
} else if (x + dataLabelWidth > plotWidth - connectorPadding) {
overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
}
// Overflow top
if (y - labelHeight / 2 < 0) {
overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
// Overflow left
} else if (y + labelHeight / 2 > plotHeight) {
overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
}
}
} // for each point
} // for each half
// Do not apply the final placement and draw the connectors until we have verified
// that labels are not spilling over.
if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
// Place the labels in the final position
this.placeDataLabels();
// Draw the connectors
if (outside && connectorWidth) {
each(this.points, function (point) {
connector = point.connector;
labelPos = point.labelPos;
dataLabel = point.dataLabel;
if (dataLabel && dataLabel._pos) {
visibility = dataLabel._attr.visibility;
x = dataLabel.connX;
y = dataLabel.connY;
connectorPath = softConnector ? [
M,
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'C',
x, y, // first break, next to the label
2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
labelPos[2], labelPos[3], // second break
L,
labelPos[4], labelPos[5] // base
] : [
M,
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
L,
labelPos[2], labelPos[3], // second break
L,
labelPos[4], labelPos[5] // base
];
if (connector) {
connector.animate({ d: connectorPath });
connector.attr('visibility', visibility);
} else {
point.connector = connector = series.chart.renderer.path(connectorPath).attr({
'stroke-width': connectorWidth,
stroke: options.connectorColor || point.color || '#606060',
visibility: visibility
//zIndex: 0 // #2722 (reversed)
})
.add(series.dataLabelsGroup);
}
} else if (connector) {
point.connector = connector.destroy();
}
});
}
}
};
/**
* Perform the final placement of the data labels after we have verified that they
* fall within the plot area.
*/
seriesTypes.pie.prototype.placeDataLabels = function () {
each(this.points, function (point) {
var dataLabel = point.dataLabel,
_pos;
if (dataLabel) {
_pos = dataLabel._pos;
if (_pos) {
dataLabel.attr(dataLabel._attr);
dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
dataLabel.moved = true;
} else if (dataLabel) {
dataLabel.attr({ y: -999 });
}
}
});
};
seriesTypes.pie.prototype.alignDataLabel = noop;
/**
* Verify whether the data labels are allowed to draw, or we should run more translation and data
* label positioning to keep them inside the plot area. Returns true when data labels are ready
* to draw.
*/
seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) {
var center = this.center,
options = this.options,
centerOption = options.center,
minSize = options.minSize || 80,
newSize = minSize,
ret;
// Handle horizontal size and center
if (centerOption[0] !== null) { // Fixed center
newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
} else { // Auto center
newSize = mathMax(
center[2] - overflow[1] - overflow[3], // horizontal overflow
minSize
);
center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
}
// Handle vertical size and center
if (centerOption[1] !== null) { // Fixed center
newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
} else { // Auto center
newSize = mathMax(
mathMin(
newSize,
center[2] - overflow[0] - overflow[2] // vertical overflow
),
minSize
);
center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
}
// If the size must be decreased, we need to run translate and drawDataLabels again
if (newSize < center[2]) {
center[2] = newSize;
this.translate(center);
each(this.points, function (point) {
if (point.dataLabel) {
point.dataLabel._pos = null; // reset
}
});
if (this.drawDataLabels) {
this.drawDataLabels();
}
// Else, return true to indicate that the pie and its labels is within the plot area
} else {
ret = true;
}
return ret;
};
}
if (seriesTypes.column) {
/**
* Override the basic data label alignment by adjusting for the position of the column
*/
seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
var inverted = this.chart.inverted,
series = point.series,
dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
below = point.below || (point.plotY > pick(this.translatedThreshold, series.yAxis.len)),
inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
// Align to the column itself, or the top of it
if (dlBox) { // Area range uses this method but not alignTo
alignTo = merge(dlBox);
if (inverted) {
alignTo = {
x: series.yAxis.len - alignTo.y - alignTo.height,
y: series.xAxis.len - alignTo.x - alignTo.width,
width: alignTo.height,
height: alignTo.width
};
}
// Compute the alignment box
if (!inside) {
if (inverted) {
alignTo.x += below ? 0 : alignTo.width;
alignTo.width = 0;
} else {
alignTo.y += below ? alignTo.height : 0;
alignTo.height = 0;
}
}
}
// When alignment is undefined (typically columns and bars), display the individual
// point below or above the point depending on the threshold
options.align = pick(
options.align,
!inverted || inside ? 'center' : below ? 'right' : 'left'
);
options.verticalAlign = pick(
options.verticalAlign,
inverted || inside ? 'middle' : below ? 'top' : 'bottom'
);
// Call the parent method
Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
};
}
/**
* Highcharts JS v4.1.1 (2015-02-17)
* Highcharts module to hide overlapping data labels. This module is included by default in Highmaps.
*
* (c) 2010-2014 Torstein Honsi
*
* License: www.highcharts.com/license
*/
/*global Highcharts, HighchartsAdapter */
(function (H) {
var Chart = H.Chart,
each = H.each,
addEvent = HighchartsAdapter.addEvent;
// Collect potensial overlapping data labels. Stack labels probably don't need to be
// considered because they are usually accompanied by data labels that lie inside the columns.
Chart.prototype.callbacks.push(function (chart) {
function collectAndHide() {
var labels = [];
each(chart.series, function (series) {
var dlOptions = series.options.dataLabels;
if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap) {
each(series.points, function (point) {
if (point.dataLabel) {
point.dataLabel.labelrank = point.labelrank;
labels.push(point.dataLabel);
}
});
}
});
chart.hideOverlappingLabels(labels);
}
// Do it now ...
collectAndHide();
// ... and after each chart redraw
addEvent(chart, 'redraw', collectAndHide);
});
/**
* Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
* visual imression.
*/
Chart.prototype.hideOverlappingLabels = function (labels) {
var len = labels.length,
label,
i,
j,
label1,
label2,
intersectRect = function (pos1, pos2, size1, size2) {
return !(
pos2.x > pos1.x + size1.width ||
pos2.x + size2.width < pos1.x ||
pos2.y > pos1.y + size1.height ||
pos2.y + size2.height < pos1.y
);
};
// Mark with initial opacity
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
label.oldOpacity = label.opacity;
label.newOpacity = 1;
}
}
// Detect overlapping labels
for (i = 0; i < len; i++) {
label1 = labels[i];
for (j = i + 1; j < len; ++j) {
label2 = labels[j];
if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0 &&
intersectRect(label1.alignAttr, label2.alignAttr, label1, label2)) {
(label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0;
}
}
}
// Hide or show
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
if (label.oldOpacity !== label.newOpacity && label.placed) {
label.alignAttr.opacity = label.newOpacity;
label[label.isOld && label.newOpacity ? 'animate' : 'attr'](label.alignAttr);
}
label.isOld = true;
}
}
};
}(Highcharts));/**
* TrackerMixin for points and graphs
*/
var TrackerMixin = Highcharts.TrackerMixin = {
drawTrackerPoint: function () {
var series = this,
chart = series.chart,
pointer = chart.pointer,
cursor = series.options.cursor,
css = cursor && { cursor: cursor },
onMouseOver = function (e) {
var target = e.target,
point;
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
while (target && !point) {
point = target.point;
target = target.parentNode;
}
if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
point.onMouseOver(e);
}
};
// Add reference to the point
each(series.points, function (point) {
if (point.graphic) {
point.graphic.element.point = point;
}
if (point.dataLabel) {
point.dataLabel.element.point = point;
}
});
// Add the event listeners, we need to do this only once
if (!series._hasTracking) {
each(series.trackerGroups, function (key) {
if (series[key]) { // we don't always have dataLabelsGroup
series[key]
.addClass(PREFIX + 'tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
.css(css);
if (hasTouch) {
series[key].on('touchstart', onMouseOver);
}
}
});
series._hasTracking = true;
}
},
/**
* Draw the tracker object that sits above all data labels and markers to
* track mouse events on the graph or points. For the line type charts
* the tracker uses the same graphPath, but with a greater stroke width
* for better control.
*/
drawTrackerGraph: function () {
var series = this,
options = series.options,
trackByArea = options.trackByArea,
trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
trackerPathLength = trackerPath.length,
chart = series.chart,
pointer = chart.pointer,
renderer = chart.renderer,
snap = chart.options.tooltip.snap,
tracker = series.tracker,
cursor = options.cursor,
css = cursor && { cursor: cursor },
singlePoints = series.singlePoints,
singlePoint,
i,
onMouseOver = function () {
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
},
/*
* Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable
* IE6: 0.002
* IE7: 0.002
* IE8: 0.002
* IE9: 0.00000000001 (unlimited)
* IE10: 0.0001 (exporting only)
* FF: 0.00000000001 (unlimited)
* Chrome: 0.000001
* Safari: 0.000001
* Opera: 0.00000000001 (unlimited)
*/
TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')';
// Extend end points. A better way would be to use round linecaps,
// but those are not clickable in VML.
if (trackerPathLength && !trackByArea) {
i = trackerPathLength + 1;
while (i--) {
if (trackerPath[i] === M) { // extend left side
trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
}
if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
}
}
}
// handle single points
for (i = 0; i < singlePoints.length; i++) {
singlePoint = singlePoints[i];
trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
L, singlePoint.plotX + snap, singlePoint.plotY);
}
// draw the tracker
if (tracker) {
tracker.attr({ d: trackerPath });
} else { // create
series.tracker = renderer.path(trackerPath)
.attr({
'stroke-linejoin': 'round', // #1225
visibility: series.visible ? VISIBLE : HIDDEN,
stroke: TRACKER_FILL,
fill: trackByArea ? TRACKER_FILL : NONE,
'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
zIndex: 2
})
.add(series.group);
// The tracker is added to the series group, which is clipped, but is covered
// by the marker group. So the marker group also needs to capture events.
each([series.tracker, series.markerGroup], function (tracker) {
tracker.addClass(PREFIX + 'tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
.css(css);
if (hasTouch) {
tracker.on('touchstart', onMouseOver);
}
});
}
}
};
/* End TrackerMixin */
/**
* Add tracking event listener to the series group, so the point graphics
* themselves act as trackers
*/
if (seriesTypes.column) {
ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.scatter) {
ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
/*
* Extend Legend for item events
*/
extend(Legend.prototype, {
setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) {
var legend = this;
// Set the events on the item group, or in case of useHTML, the item itself (#1249)
(useHTML ? legendItem : item.legendGroup).on('mouseover', function () {
item.setState(HOVER_STATE);
legendItem.css(legend.options.itemHoverStyle);
})
.on('mouseout', function () {
legendItem.css(item.visible ? itemStyle : itemHiddenStyle);
item.setState();
})
.on('click', function (event) {
var strLegendItemClick = 'legendItemClick',
fnLegendItemClick = function () {
item.setVisible();
};
// Pass over the click/touch event. #4.
event = {
browserEvent: event
};
// click the name or symbol
if (item.firePointEvent) { // point
item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
} else {
fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
}
});
},
createCheckboxForItem: function (item) {
var legend = this;
item.checkbox = createElement('input', {
type: 'checkbox',
checked: item.selected,
defaultChecked: item.selected // required by IE7
}, legend.options.itemCheckboxStyle, legend.chart.container);
addEvent(item.checkbox, 'click', function (event) {
var target = event.target;
fireEvent(item.series || item, 'checkboxClick', { // #3712
checked: target.checked,
item: item
},
function () {
item.select();
}
);
});
}
});
/*
* Add pointer cursor to legend itemstyle in defaultOptions
*/
defaultOptions.legend.itemStyle.cursor = 'pointer';
/*
* Extend the Chart object with interaction
*/
extend(Chart.prototype, {
/**
* Display the zoom button
*/
showResetZoom: function () {
var chart = this,
lang = defaultOptions.lang,
btnOptions = chart.options.chart.resetZoomButton,
theme = btnOptions.theme,
states = theme.states,
alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
.attr({
align: btnOptions.position.align,
title: lang.resetZoomTitle
})
.add()
.align(btnOptions.position, false, alignTo);
},
/**
* Zoom out to 1:1
*/
zoomOut: function () {
var chart = this;
fireEvent(chart, 'selection', { resetSelection: true }, function () {
chart.zoom();
});
},
/**
* Zoom into a given portion of the chart given by axis coordinates
* @param {Object} event
*/
zoom: function (event) {
var chart = this,
hasZoomed,
pointer = chart.pointer,
displayButton = false,
resetZoomButton;
// If zoom is called with no arguments, reset the axes
if (!event || event.resetSelection) {
each(chart.axes, function (axis) {
hasZoomed = axis.zoom();
});
} else { // else, zoom in on all axes
each(event.xAxis.concat(event.yAxis), function (axisData) {
var axis = axisData.axis,
isXAxis = axis.isXAxis;
// don't zoom more than minRange
if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
hasZoomed = axis.zoom(axisData.min, axisData.max);
if (axis.displayBtn) {
displayButton = true;
}
}
});
}
// Show or hide the Reset zoom button
resetZoomButton = chart.resetZoomButton;
if (displayButton && !resetZoomButton) {
chart.showResetZoom();
} else if (!displayButton && isObject(resetZoomButton)) {
chart.resetZoomButton = resetZoomButton.destroy();
}
// Redraw
if (hasZoomed) {
chart.redraw(
pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
);
}
},
/**
* Pan the chart by dragging the mouse across the pane. This function is called
* on mouse move, and the distance to pan is computed from chartX compared to
* the first chartX position in the dragging operation.
*/
pan: function (e, panning) {
var chart = this,
hoverPoints = chart.hoverPoints,
doRedraw;
// remove active points for shared tooltip
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
var mousePos = e[isX ? 'chartX' : 'chartY'],
axis = chart[isX ? 'xAxis' : 'yAxis'][0],
startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'],
halfPointRange = (axis.pointRange || 0) / 2,
extremes = axis.getExtremes(),
newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange,
goingLeft = startPos > mousePos; // #3613
if (axis.series.length &&
(goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) &&
(!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) {
axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
doRedraw = true;
}
chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run
});
if (doRedraw) {
chart.redraw(false);
}
css(chart.container, { cursor: 'move' });
}
});
/*
* Extend the Point object with interaction
*/
extend(Point.prototype, {
/**
* Toggle the selection status of a point
* @param {Boolean} selected Whether to select or unselect the point.
* @param {Boolean} accumulate Whether to add to the previous selection. By default,
* this happens if the control key (Cmd on Mac) was pressed during clicking.
*/
select: function (selected, accumulate) {
var point = this,
series = point.series,
chart = series.chart;
selected = pick(selected, !point.selected);
// fire the event with the defalut handler
point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
point.selected = point.options.selected = selected;
series.options.data[inArray(point, series.data)] = point.options;
point.setState(selected && SELECT_STATE);
// unselect all other points unless Ctrl or Cmd + click
if (!accumulate) {
each(chart.getSelectedPoints(), function (loopPoint) {
if (loopPoint.selected && loopPoint !== point) {
loopPoint.selected = loopPoint.options.selected = false;
series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
loopPoint.setState(NORMAL_STATE);
loopPoint.firePointEvent('unselect');
}
});
}
});
},
/**
* Runs on mouse over the point
*/
onMouseOver: function (e) {
var point = this,
series = point.series,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
// set normal state to previous series
if (hoverPoint && hoverPoint !== point) {
hoverPoint.onMouseOut();
}
// trigger the event
point.firePointEvent('mouseOver');
// update the tooltip
if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.refresh(point, e);
}
// hover this
point.setState(HOVER_STATE);
chart.hoverPoint = point;
},
/**
* Runs on mouse out from the point
*/
onMouseOut: function () {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
this.firePointEvent('mouseOut');
if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
this.setState();
chart.hoverPoint = null;
}
},
/**
* Import events from the series' and point's options. Only do it on
* demand, to save processing time on hovering.
*/
importEvents: function () {
if (!this.hasImportedEvents) {
var point = this,
options = merge(point.series.options.point, point.options),
events = options.events,
eventType;
point.events = events;
for (eventType in events) {
addEvent(point, eventType, events[eventType]);
}
this.hasImportedEvents = true;
}
},
/**
* Set the point's state
* @param {String} state
*/
setState: function (state, move) {
var point = this,
plotX = point.plotX,
plotY = point.plotY,
series = point.series,
stateOptions = series.options.states,
markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
normalDisabled = markerOptions && !markerOptions.enabled,
markerStateOptions = markerOptions && markerOptions.states[state],
stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
stateMarkerGraphic = series.stateMarkerGraphic,
pointMarker = point.marker || {},
chart = series.chart,
radius,
halo = series.halo,
haloOptions,
newSymbol,
pointAttr;
state = state || NORMAL_STATE; // empty string
pointAttr = point.pointAttr[state] || series.pointAttr[state];
if (
// already has this state
(state === point.state && !move) ||
// selected points don't respond to hover
(point.selected && state !== SELECT_STATE) ||
// series' state options is disabled
(stateOptions[state] && stateOptions[state].enabled === false) ||
// general point marker's state options is disabled
(state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) ||
// individual point marker's state options is disabled
(state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
) {
return;
}
// apply hover styles to the existing point
if (point.graphic) {
radius = markerOptions && point.graphic.symbolName && pointAttr.r;
point.graphic.attr(merge(
pointAttr,
radius ? { // new symbol attributes (#507, #612)
x: plotX - radius,
y: plotY - radius,
width: 2 * radius,
height: 2 * radius
} : {}
));
// Zooming in from a range with no markers to a range with markers
if (stateMarkerGraphic) {
stateMarkerGraphic.hide();
}
} else {
// if a graphic is not applied to each point in the normal state, create a shared
// graphic for the hover state
if (state && markerStateOptions) {
radius = markerStateOptions.radius;
newSymbol = pointMarker.symbol || series.symbol;
// If the point has another symbol than the previous one, throw away the
// state marker graphic and force a new one (#1459)
if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
stateMarkerGraphic = stateMarkerGraphic.destroy();
}
// Add a new state marker graphic
if (!stateMarkerGraphic) {
if (newSymbol) {
series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
newSymbol,
plotX - radius,
plotY - radius,
2 * radius,
2 * radius
)
.attr(pointAttr)
.add(series.markerGroup);
stateMarkerGraphic.currentSymbol = newSymbol;
}
// Move the existing graphic
} else {
stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054
x: plotX - radius,
y: plotY - radius
});
}
}
if (stateMarkerGraphic) {
stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450
}
}
// Show me your halo
haloOptions = stateOptions[state] && stateOptions[state].halo;
if (haloOptions && haloOptions.size) {
if (!halo) {
series.halo = halo = chart.renderer.path()
.add(chart.seriesGroup);
}
halo.attr(extend({
fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get()
}, haloOptions.attributes))[move ? 'animate' : 'attr']({
d: point.haloPath(haloOptions.size)
});
} else if (halo) {
halo.attr({ d: [] });
}
point.state = state;
},
haloPath: function (size) {
var series = this.series,
chart = series.chart,
plotBox = series.getPlotBox(),
inverted = chart.inverted;
return chart.renderer.symbols.circle(
plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size,
plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size,
size * 2,
size * 2
);
}
});
/*
* Extend the Series object with interaction
*/
extend(Series.prototype, {
/**
* Series mouse over handler
*/
onMouseOver: function () {
var series = this,
chart = series.chart,
hoverSeries = chart.hoverSeries;
// set normal state to previous series
if (hoverSeries && hoverSeries !== series) {
hoverSeries.onMouseOut();
}
// trigger the event, but to save processing time,
// only if defined
if (series.options.events.mouseOver) {
fireEvent(series, 'mouseOver');
}
// hover this
series.setState(HOVER_STATE);
chart.hoverSeries = series;
},
/**
* Series mouse out handler
*/
onMouseOut: function () {
// trigger the event only if listeners exist
var series = this,
options = series.options,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
// trigger mouse out on the point, which must be in this series
if (hoverPoint) {
hoverPoint.onMouseOut();
}
// fire the mouse out event
if (series && options.events.mouseOut) {
fireEvent(series, 'mouseOut');
}
// hide the tooltip
if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.hide();
}
// set normal state
series.setState();
chart.hoverSeries = null;
},
/**
* Set the state of the graph
*/
setState: function (state) {
var series = this,
options = series.options,
graph = series.graph,
graphNeg = series.graphNeg,
stateOptions = options.states,
lineWidth = options.lineWidth,
attribs;
state = state || NORMAL_STATE;
if (series.state !== state) {
series.state = state;
if (stateOptions[state] && stateOptions[state].enabled === false) {
return;
}
if (state) {
lineWidth = (stateOptions[state].lineWidth || lineWidth) + (stateOptions[state].lineWidthPlus || 0);
}
if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
attribs = {
'stroke-width': lineWidth
};
// use attr because animate will cause any other animation on the graph to stop
graph.attr(attribs);
if (graphNeg) {
graphNeg.attr(attribs);
}
}
}
},
/**
* Set the visibility of the graph
*
* @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
* the visibility is toggled.
*/
setVisible: function (vis, redraw) {
var series = this,
chart = series.chart,
legendItem = series.legendItem,
showOrHide,
ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
oldVisibility = series.visible;
// if called without an argument, toggle visibility
series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
showOrHide = vis ? 'show' : 'hide';
// show or hide elements
each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
if (series[key]) {
series[key][showOrHide]();
}
});
// hide tooltip (#1361)
if (chart.hoverSeries === series) {
series.onMouseOut();
}
if (legendItem) {
chart.legend.colorizeItem(series, vis);
}
// rescale or adapt to resized chart
series.isDirty = true;
// in a stack, all other series are affected
if (series.options.stacking) {
each(chart.series, function (otherSeries) {
if (otherSeries.options.stacking && otherSeries.visible) {
otherSeries.isDirty = true;
}
});
}
// show or hide linked series
each(series.linkedSeries, function (otherSeries) {
otherSeries.setVisible(vis, false);
});
if (ignoreHiddenSeries) {
chart.isDirtyBox = true;
}
if (redraw !== false) {
chart.redraw();
}
fireEvent(series, showOrHide);
},
/**
* Show the graph
*/
show: function () {
this.setVisible(true);
},
/**
* Hide the graph
*/
hide: function () {
this.setVisible(false);
},
/**
* Set the selected state of the graph
*
* @param selected {Boolean} True to select the series, false to unselect. If
* UNDEFINED, the selection state is toggled.
*/
select: function (selected) {
var series = this;
// if called without an argument, toggle
series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
if (series.checkbox) {
series.checkbox.checked = selected;
}
fireEvent(series, selected ? 'select' : 'unselect');
},
drawTracker: TrackerMixin.drawTrackerGraph
});
// global variables
extend(Highcharts, {
// Constructors
Color: Color,
Point: Point,
Tick: Tick,
Renderer: Renderer,
SVGElement: SVGElement,
SVGRenderer: SVGRenderer,
// Various
arrayMin: arrayMin,
arrayMax: arrayMax,
charts: charts,
dateFormat: dateFormat,
error: error,
format: format,
pathAnim: pathAnim,
getOptions: getOptions,
hasBidiBug: hasBidiBug,
isTouchDevice: isTouchDevice,
setOptions: setOptions,
addEvent: addEvent,
removeEvent: removeEvent,
createElement: createElement,
discardElement: discardElement,
css: css,
each: each,
map: map,
merge: merge,
splat: splat,
extendClass: extendClass,
pInt: pInt,
svg: hasSVG,
canvas: useCanVG,
vml: !hasSVG && !useCanVG,
product: PRODUCT,
version: VERSION
});
}());
|
packages/material-ui-icons/lib/FormatItalicTwoTone.js | mbrookes/material-ui | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M6 15v3h8v-3h-2.21l3.42-8H18V4h-8v3h2.21l-3.42 8z"
}), 'FormatItalicTwoTone');
exports.default = _default; |
data-browser-ui/public/app/components/tableComponents/td/relationComponents/list.js | CloudBoost/cloudboost | import React from 'react';
import ReactDOM from 'react-dom';
import TextList from '../listComponents/textList.js'
import BooleanList from '../listComponents/booleanList.js'
import PasswordList from '../listComponents/passwordList.js'
import ObjectList from '../listComponents/objectList.js'
import GeoList from '../listComponents/geoList.js'
import FileList from '../listComponents/fileList.js'
import NumberList from '../listComponents/numberList.js'
import DateTimeList from '../listComponents/dateTimeList.js'
import RelationList from '../listComponents/relationList.js'
import GenericAddToList from '../listComponents/genericAddToList.js'
class ListTdComponent extends React.Component {
constructor() {
super()
this.state = {
elementData: [],
elementToRender: TextList
}
}
componentDidMount() {
this.generaliseList(this.props)
}
componentWillReceiveProps(props) {
this.generaliseList(props)
}
generaliseList(props) {
switch (props.columnData.relatedTo) {
case "Text":
this.state.elementToRender = TextList
break;
case "EncryptedText":
this.state.elementToRender = PasswordList
break;
case "Boolean":
this.state.elementToRender = BooleanList
break;
case "Email":
this.state.elementToRender = TextList
break;
case "URL":
this.state.elementToRender = TextList
break;
case "Url":
this.state.elementToRender = TextList
break;
case "DateTime":
this.state.elementToRender = DateTimeList
break;
case "File":
this.state.elementToRender = FileList
break;
case "Object":
this.state.elementToRender = ObjectList
break;
case "Number":
this.state.elementToRender = NumberList
break;
case "GeoPoint":
this.state.elementToRender = GeoList
break;
default:
this.state.elementToRender = RelationList
break;
}
this.state.elementData = props.elementData
this.setState(this.state)
}
updateElementData(data, index) {
this.state.elementData[index] = data
this.setState(this.state)
this.props.updateElementData(this.state.elementData, this.props.columnData.name)
}
addToElementData(data) {
if(!this.state.elementData){
this.state.elementData = []
}
// if data is not provided then compute it here
if(data === false){
// check type of related to , and add elemnt accordingly
let type = this.props.columnData.relatedTo
if(type == 'Number'){
data = 0
} else if(type == 'DateTime'){
data = new Date()
} else if(type == 'GeoPoint'){
data = new CB.CloudGeoPoint(0,0)
} else if(type == 'Boolean'){
data = false
} else {
data = ''
}
}
// push the empty data into elementData
this.state.elementData.push(data)
this.setState(this.state)
this.props.updateElementData(this.state.elementData, this.props.columnData.name)
}
removeFromElementData(index) {
this.state.elementData.splice(index, 1)
this.setState(this.state)
this.props.updateElementData(this.state.elementData, this.props.columnData.name)
}
handleClose() {
}
render() {
let elements = []
if (this.state.elementData) {
elements = this.state.elementData.map((data, index) => {
return React.createElement(this.state.elementToRender, {
index: index,
key: index,
data: data,
addToElementData: this.addToElementData.bind(this),
removeFromElementData: this.removeFromElementData.bind(this),
updateElementData: this.updateElementData.bind(this),
isListOfRelation: true
})
})
}
return (
<div className="listrelationdiv">
<span className="textnamerlationrle"> {this.props.columnData.name} </span>
<div className="listdivrel">
<GenericAddToList
addToElementData={this.addToElementData.bind(this)}
columnType={this.props.columnData.relatedTo}
/>
<div className="listdivscontentrelation">
{
// if no elementData are found then show empty list( only for non file data types )
elements.length || this.props.columnData.relatedTo === 'File' ? elements : <p className="emptylisttext">This list is empty.</p>
}
</div>
</div>
</div>
);
}
}
export default ListTdComponent; |
src/js/components/Header.js | y04nqt/react-tuts | import React from 'react';
import Title from "./Header/Title";
export default class Header extends React.Component{
constructor(){
super();
this.name = 'Universe';
name = this.name;
}
handleChange(e){
const title = e.target.value;
//don't forget to add the prop in the change method --duhhh
this.props.changeTitle(title);
console.log(title);
}
render(){
console.log(this.props);
return(
<header>
<Title title={this.props.title}/>
<input onChange={this.handleChange.bind(this)} />
<h2>Greetings, {name}. I am glad to be here with you</h2>
</header>
);
}
}
|
app/javascript/mastodon/features/direct_timeline/components/conversation.js | KnzkDev/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import StatusContainer from '../../../containers/status_container';
export default class Conversation extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
conversationId: PropTypes.string.isRequired,
accounts: ImmutablePropTypes.list.isRequired,
lastStatusId: PropTypes.string,
unread:PropTypes.bool.isRequired,
onMoveUp: PropTypes.func,
onMoveDown: PropTypes.func,
markRead: PropTypes.func.isRequired,
};
handleClick = () => {
if (!this.context.router) {
return;
}
const { lastStatusId, unread, markRead } = this.props;
if (unread) {
markRead();
}
this.context.router.history.push(`/statuses/${lastStatusId}`);
}
handleHotkeyMoveUp = () => {
this.props.onMoveUp(this.props.conversationId);
}
handleHotkeyMoveDown = () => {
this.props.onMoveDown(this.props.conversationId);
}
render () {
const { accounts, lastStatusId, unread } = this.props;
if (lastStatusId === null) {
return null;
}
return (
<StatusContainer
id={lastStatusId}
unread={unread}
otherAccounts={accounts}
onMoveUp={this.handleHotkeyMoveUp}
onMoveDown={this.handleHotkeyMoveDown}
onClick={this.handleClick}
/>
);
}
}
|
src/ModalHeader.js | lzcmaro/react-ratchet | import React from 'react';
import classnames from 'classnames';
import NavBar from './NavBar';
import Link from './Link';
let ModalHeader = React.createClass({
propTypes: {
closeButton: React.PropTypes.bool
},
getDefaultProps() {
return { closeButton: true }
},
contextTypes: {
onModalHide: React.PropTypes.func
},
render() {
return (
<NavBar
{...this.props}
className={classnames('modal-header', this.props.className)}>
{this.props.closeButton ? this.renderCloseButton() : null}
{this.props.children}
</NavBar>
);
},
renderCloseButton() {
return (
<Link right icon="close" onTouchEnd={this.context.onModalHide || this.props.onHide} />
)
}
});
export default ModalHeader;
|
src/routes.js | tvarner/PortfolioApp | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Application from './app/app';
import MainViewContainer from './app/components/pages/MainView/MainViewContainer';
import AboutPage from './app/components/pages/AboutPage/AboutPage'; // eslint-disable-line import/no-named-as-default
import NotFoundPage from './app/components/pages/NotFound/NotFoundPage';
export default (
<Route path="/" component={Application}>
<IndexRoute component={MainViewContainer}/>
<Route path="about" component={AboutPage}/>
<Route path="*" component={NotFoundPage}/>
</Route>
); |
docs/src/sections/NavbarSection.js | Terminux/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function NavbarSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="navbars">Navbars</Anchor> <small>Navbar</small>
</h2>
<p>Navbars are responsive meta components that serve as navigation headers for your application or site.</p>
<p>
They also support all the different Bootstrap classes as properties. Just camelCase
the css class and remove navbar from it.
</p>
<p>
For example <code>navbar-fixed-top</code> becomes the property <code>fixedTop</code>.
The different properties are <code>fixedTop</code>, <code>fixedBottom</code>, <code>staticTop</code>
, <code>inverse</code>, and <code>fluid</code>.
</p>
<p>
You can also align elements to the right by specifying the <code>pullRight</code> prop on
the <code>Nav</code>, and other sub-components.
</p>
<h3><Anchor id="navbars-basic">Navbar Basic Example</Anchor></h3>
<ReactPlayground codeText={Samples.NavbarBasic} />
<div className="bs-callout bs-callout-info">
<h4>Additional Import Options</h4>
<p>
The Navbar Header, Toggle, Brand, and Collapse components are available as static properties
the <code>{"<Navbar/>"}</code> component but you can also import them directly from
the <code>/lib</code> directory
like: <code>{'require("react-bootstrap/lib/NavbarHeader")'}</code>.
</p>
</div>
<h3><Anchor id="navbars-mobile-friendly">Responsive Navbars</Anchor></h3>
<p>
To have a mobile friendly Navbar, Add a <code>Navbar.Toggle</code> to your Header and wrap your
Navs in a <code>Navbar.Collapse</code> component. The <code>Navbar</code> will automatically wire
the toggle and collapse together!
</p>
<p>
By setting the prop <code>defaultNavExpanded</code> the Navbar will start
expanded by default. You can also finely control the collapsing behavior by using
the <code>expanded</code> and <code>onToggle</code> props.
</p>
<ReactPlayground codeText={Samples.NavbarCollapsible} />
<h3><Anchor id="navbars-form">Forms</Anchor></h3>
<p>
Use the <code>Navbar.Form</code> convenience component to apply proper margins and alignment to
form components.
</p>
<ReactPlayground codeText={Samples.NavbarForm} />
<h3><Anchor id="navbars-text-link">Text and Non-nav links</Anchor></h3>
<p>
Loose text and links can be wraped in the convenience
components: <code>Navbar.Link</code> and <code>Navbar.Text</code>
</p>
<ReactPlayground codeText={Samples.NavbarTextLink} />
<h3><Anchor id="navbar-props">Props</Anchor></h3>
<h4><Anchor id="navs-props-navbar">Navbar</Anchor></h4>
<PropTable component="Navbar"/>
<h4><Anchor id="navs-props-navbrand">NavbarToggle, Navbar.Toggle</Anchor></h4>
<PropTable component="NavbarToggle"/>
</div>
);
}
|
jquery-1.7.2.min.js | chamelea/jb-hiddenmenu | /*! jQuery v1.7.2 jquery.com | jquery.org/license */
(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(
a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f
.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); |
docs/src/app/components/pages/components/List/ExampleSettings.js | pradel/material-ui | import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import Subheader from 'material-ui/Subheader';
import Divider from 'material-ui/Divider';
import Checkbox from 'material-ui/Checkbox';
import Toggle from 'material-ui/Toggle';
const ListExampleSettings = () => (
<div>
<MobileTearSheet>
<List>
<Subheader>General</Subheader>
<ListItem
primaryText="Profile photo"
secondaryText="Change your Google+ profile photo"
/>
<ListItem
primaryText="Show your status"
secondaryText="Your status is visible to everyone you use with"
/>
</List>
<Divider />
<List>
<Subheader>Hangout Notifications</Subheader>
<ListItem
leftCheckbox={<Checkbox />}
primaryText="Notifications"
secondaryText="Allow notifications"
/>
<ListItem
leftCheckbox={<Checkbox />}
primaryText="Sounds"
secondaryText="Hangouts message"
/>
<ListItem
leftCheckbox={<Checkbox />}
primaryText="Video sounds"
secondaryText="Hangouts video call"
/>
</List>
</MobileTearSheet>
<MobileTearSheet>
<List>
<ListItem
primaryText="When calls and notifications arrive"
secondaryText="Always interrupt"
/>
</List>
<Divider />
<List>
<Subheader>Priority Interruptions</Subheader>
<ListItem primaryText="Events and reminders" rightToggle={<Toggle />} />
<ListItem primaryText="Calls" rightToggle={<Toggle />} />
<ListItem primaryText="Messages" rightToggle={<Toggle />} />
</List>
<Divider />
<List>
<Subheader>Hangout Notifications</Subheader>
<ListItem primaryText="Notifications" leftCheckbox={<Checkbox />} />
<ListItem primaryText="Sounds" leftCheckbox={<Checkbox />} />
<ListItem primaryText="Video sounds" leftCheckbox={<Checkbox />} />
</List>
</MobileTearSheet>
</div>
);
export default ListExampleSettings;
|
node_modules/react-dom/lib/ReactNodeTypes.js | yaolei/Node-Clound | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant');
var React = require('react/lib/React');
var invariant = require('fbjs/lib/invariant');
var ReactNodeTypes = {
HOST: 0,
COMPOSITE: 1,
EMPTY: 2,
getType: function (node) {
if (node === null || node === false) {
return ReactNodeTypes.EMPTY;
} else if (React.isValidElement(node)) {
if (typeof node.type === 'function') {
return ReactNodeTypes.COMPOSITE;
} else {
return ReactNodeTypes.HOST;
}
}
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0;
}
};
module.exports = ReactNodeTypes; |
ajax/libs/6to5/1.12.7/browser-polyfill.js | mzdani/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){if(typeof Symbol==="undefined"){require("es6-symbol/implement")}require("es6-shim");require("regenerator-6to5/runtime")},{"es6-shim":3,"es6-symbol/implement":4,"regenerator-6to5/runtime":27}],2:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],3:[function(require,module,exports){(function(process){(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.returnExports=factory()}})(this,function(){"use strict";var isCallableWithoutNew=function(func){try{func()}catch(e){return false}return true};var supportsSubclassing=function(C,f){try{var Sub=function(){C.apply(this,arguments)};if(!Sub.__proto__){return false}Object.setPrototypeOf(Sub,C);Sub.prototype=Object.create(C.prototype,{constructor:{value:C}});return f(Sub)}catch(e){return false}};var arePropertyDescriptorsSupported=function(){try{Object.defineProperty({},"x",{});return true}catch(e){return false}};var startsWithRejectsRegex=function(){var rejectsRegex=false;if(String.prototype.startsWith){try{"/a/".startsWith(/a/)}catch(e){rejectsRegex=true}}return rejectsRegex};var getGlobal=new Function("return this;");var globals=getGlobal();var global_isFinite=globals.isFinite;var supportsDescriptors=!!Object.defineProperty&&arePropertyDescriptorsSupported();var startsWithIsCompliant=startsWithRejectsRegex();var _slice=Array.prototype.slice;var _indexOf=String.prototype.indexOf;var _toString=Object.prototype.toString;var _hasOwnProperty=Object.prototype.hasOwnProperty;var ArrayIterator;var defineProperty=function(object,name,value,force){if(!force&&name in object){return}if(supportsDescriptors){Object.defineProperty(object,name,{configurable:true,enumerable:false,writable:true,value:value})}else{object[name]=value}};var defineProperties=function(object,map){Object.keys(map).forEach(function(name){var method=map[name];defineProperty(object,name,method,false)})};var create=Object.create||function(prototype,properties){function Type(){}Type.prototype=prototype;var object=new Type;if(typeof properties!=="undefined"){defineProperties(object,properties)}return object};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(globals.Set&&typeof(new globals.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var addIterator=function(prototype,impl){if(!impl){impl=function iterator(){return this}}var o={};o[$iterator$]=impl;defineProperties(prototype,o);if(!prototype[$iterator$]&&typeof $iterator$==="symbol"){prototype[$iterator$]=impl}};var isArguments=function isArguments(value){var str=_toString.call(value);var result=str==="[object Arguments]";if(!result){result=str!=="[object Array]"&&value!==null&&typeof value==="object"&&typeof value.length==="number"&&value.length>=0&&_toString.call(value.callee)==="[object Function]"}return result};var emulateES6construct=function(o){if(!ES.TypeIsObject(o)){throw new TypeError("bad object")}if(!o._es6construct){if(o.constructor&&ES.IsCallable(o.constructor["@@create"])){o=o.constructor["@@create"](o)}defineProperties(o,{_es6construct:true})}return o};var ES={CheckObjectCoercible:function(x,optMessage){if(x==null){throw new TypeError(optMessage||"Cannot call method on "+x)}return x},TypeIsObject:function(x){return x!=null&&Object(x)===x},ToObject:function(o,optMessage){return Object(ES.CheckObjectCoercible(o,optMessage))},IsCallable:function(x){return typeof x==="function"&&_toString.call(x)==="[object Function]"},ToInt32:function(x){return x>>0},ToUint32:function(x){return x>>>0},ToInteger:function(value){var number=+value;if(Number.isNaN(number)){return 0}if(number===0||!Number.isFinite(number)){return number}return(number>0?1:-1)*Math.floor(Math.abs(number))},ToLength:function(value){var len=ES.ToInteger(value);if(len<=0){return 0}if(len>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return len},SameValue:function(a,b){if(a===b){if(a===0){return 1/a===1/b}return true}return Number.isNaN(a)&&Number.isNaN(b)},SameValueZero:function(a,b){return a===b||Number.isNaN(a)&&Number.isNaN(b)},IsIterable:function(o){return ES.TypeIsObject(o)&&(typeof o[$iterator$]!=="undefined"||isArguments(o))},GetIterator:function(o){if(isArguments(o)){return new ArrayIterator(o,"value")}var it=o[$iterator$]();if(!ES.TypeIsObject(it)){throw new TypeError("bad iterator")}return it},IteratorNext:function(it){var result=arguments.length>1?it.next(arguments[1]):it.next();if(!ES.TypeIsObject(result)){throw new TypeError("bad iterator")}return result},Construct:function(C,args){var obj;if(ES.IsCallable(C["@@create"])){obj=C["@@create"]()}else{obj=create(C.prototype||null)}defineProperties(obj,{_es6construct:true});var result=C.apply(obj,args);return ES.TypeIsObject(result)?result:obj}};var numberConversion=function(){function roundToEven(n){var w=Math.floor(n),f=n-w;if(f<.5){return w}if(f>.5){return w+1}return w%2?w+1:w}function packIEEE754(v,ebits,fbits){var bias=(1<<ebits-1)-1,s,e,f,ln,i,bits,str,bytes;if(v!==v){e=(1<<ebits)-1;f=Math.pow(2,fbits-1);s=0}else if(v===Infinity||v===-Infinity){e=(1<<ebits)-1;f=0;s=v<0?1:0}else if(v===0){e=0;f=0;s=1/v===-Infinity?1:0}else{s=v<0;v=Math.abs(v);if(v>=Math.pow(2,1-bias)){e=Math.min(Math.floor(Math.log(v)/Math.LN2),1023);f=roundToEven(v/Math.pow(2,e)*Math.pow(2,fbits));if(f/Math.pow(2,fbits)>=2){e=e+1;f=1}if(e>bias){e=(1<<ebits)-1;f=0}else{e=e+bias;f=f-Math.pow(2,fbits)}}else{e=0;f=roundToEven(v/Math.pow(2,1-bias-fbits))}}bits=[];for(i=fbits;i;i-=1){bits.push(f%2?1:0);f=Math.floor(f/2)}for(i=ebits;i;i-=1){bits.push(e%2?1:0);e=Math.floor(e/2)}bits.push(s?1:0);bits.reverse();str=bits.join("");bytes=[];while(str.length){bytes.push(parseInt(str.slice(0,8),2));str=str.slice(8)}return bytes}function unpackIEEE754(bytes,ebits,fbits){var bits=[],i,j,b,str,bias,s,e,f;for(i=bytes.length;i;i-=1){b=bytes[i-1];for(j=8;j;j-=1){bits.push(b%2?1:0);b=b>>1}}bits.reverse();str=bits.join("");bias=(1<<ebits-1)-1;s=parseInt(str.slice(0,1),2)?-1:1;e=parseInt(str.slice(1,1+ebits),2);f=parseInt(str.slice(1+ebits),2);if(e===(1<<ebits)-1){return f!==0?NaN:s*Infinity}else if(e>0){return s*Math.pow(2,e-bias)*(1+f/Math.pow(2,fbits))}else if(f!==0){return s*Math.pow(2,-(bias-1))*(f/Math.pow(2,fbits))}else{return s<0?-0:0}}function unpackFloat64(b){return unpackIEEE754(b,11,52)}function packFloat64(v){return packIEEE754(v,11,52)}function unpackFloat32(b){return unpackIEEE754(b,8,23)}function packFloat32(v){return packIEEE754(v,8,23)}var conversions={toFloat32:function(num){return unpackFloat32(packFloat32(num))}};if(typeof Float32Array!=="undefined"){var float32array=new Float32Array(1);conversions.toFloat32=function(num){float32array[0]=num;return float32array[0]}}return conversions}();defineProperties(String,{fromCodePoint:function(_){var points=_slice.call(arguments,0,arguments.length);var result=[];var next;for(var i=0,length=points.length;i<length;i++){next=Number(points[i]);if(!ES.SameValue(next,ES.ToInteger(next))||next<0||next>1114111){throw new RangeError("Invalid code point "+next)}if(next<65536){result.push(String.fromCharCode(next))}else{next-=65536;result.push(String.fromCharCode((next>>10)+55296));result.push(String.fromCharCode(next%1024+56320))}}return result.join("")},raw:function(callSite){var substitutions=_slice.call(arguments,1,arguments.length);var cooked=ES.ToObject(callSite,"bad callSite");var rawValue=cooked.raw;var raw=ES.ToObject(rawValue,"bad raw value");var len=Object.keys(raw).length;var literalsegments=ES.ToLength(len);if(literalsegments===0){return""}var stringElements=[];var nextIndex=0;var nextKey,next,nextSeg,nextSub;while(nextIndex<literalsegments){nextKey=String(nextIndex);next=raw[nextKey];nextSeg=String(next);stringElements.push(nextSeg);if(nextIndex+1>=literalsegments){break}next=substitutions[nextKey];if(typeof next==="undefined"){break}nextSub=String(next);stringElements.push(nextSub);nextIndex++}return stringElements.join("")}});if(String.fromCodePoint.length!==1){var originalFromCodePoint=String.fromCodePoint;defineProperty(String,"fromCodePoint",function(_){return originalFromCodePoint.apply(this,arguments)},true)}var StringShims={repeat:function(){var repeat=function(s,times){if(times<1){return""}if(times%2){return repeat(s,times-1)+s}var half=repeat(s,times/2);return half+half};return function(times){var thisStr=String(ES.CheckObjectCoercible(this));times=ES.ToInteger(times);if(times<0||times===Infinity){throw new RangeError("Invalid String#repeat value")}return repeat(thisStr,times)}}(),startsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "startsWith" with a regex')}searchStr=String(searchStr);var startArg=arguments.length>1?arguments[1]:void 0;var start=Math.max(ES.ToInteger(startArg),0);return thisStr.slice(start,start+searchStr.length)===searchStr},endsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "endsWith" with a regex')}searchStr=String(searchStr);var thisLen=thisStr.length;var posArg=arguments.length>1?arguments[1]:void 0;var pos=typeof posArg==="undefined"?thisLen:ES.ToInteger(posArg);var end=Math.min(Math.max(pos,0),thisLen);return thisStr.slice(end-searchStr.length,end)===searchStr},contains:function(searchString){var position=arguments.length>1?arguments[1]:void 0;return _indexOf.call(this,searchString,position)!==-1},codePointAt:function(pos){var thisStr=String(ES.CheckObjectCoercible(this));var position=ES.ToInteger(pos);var length=thisStr.length;if(position<0||position>=length){return}var first=thisStr.charCodeAt(position);var isEnd=position+1===length;if(first<55296||first>56319||isEnd){return first}var second=thisStr.charCodeAt(position+1);if(second<56320||second>57343){return first}return(first-55296)*1024+(second-56320)+65536}};defineProperties(String.prototype,StringShims);var hasStringTrimBug="
".trim().length!==1;if(hasStringTrimBug){var originalStringTrim=String.prototype.trim;delete String.prototype.trim;var ws=[" \n\f\r "," \u2028","\u2029"].join("");var trimRegexp=new RegExp("(^["+ws+"]+)|(["+ws+"]+$)","g");defineProperties(String.prototype,{trim:function(){if(typeof this==="undefined"||this===null){throw new TypeError("can't convert "+this+" to object")}return String(this).replace(trimRegexp,"")}})}var StringIterator=function(s){this._s=String(ES.CheckObjectCoercible(s));this._i=0};StringIterator.prototype.next=function(){var s=this._s,i=this._i;if(typeof s==="undefined"||i>=s.length){this._s=void 0;return{value:void 0,done:true}}var first=s.charCodeAt(i),second,len;if(first<55296||first>56319||i+1==s.length){len=1}else{second=s.charCodeAt(i+1);len=second<56320||second>57343?1:2}this._i=i+len;return{value:s.substr(i,len),done:false}};addIterator(StringIterator.prototype);addIterator(String.prototype,function(){return new StringIterator(this)});if(!startsWithIsCompliant){String.prototype.startsWith=StringShims.startsWith;String.prototype.endsWith=StringShims.endsWith}var ArrayShims={from:function(iterable){var mapFn=arguments.length>1?arguments[1]:void 0;var list=ES.ToObject(iterable,"bad iterable");if(typeof mapFn!=="undefined"&&!ES.IsCallable(mapFn)){throw new TypeError("Array.from: when provided, the second argument must be a function")}var hasThisArg=arguments.length>2;var thisArg=hasThisArg?arguments[2]:void 0;var usingIterator=ES.IsIterable(list);var length;var result,i,value;if(usingIterator){i=0;result=ES.IsCallable(this)?Object(new this):[];var it=usingIterator?ES.GetIterator(list):null;var iterationValue;do{iterationValue=ES.IteratorNext(it);if(!iterationValue.done){value=iterationValue.value;if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}i+=1}}while(!iterationValue.done);length=i}else{length=ES.ToLength(list.length);result=ES.IsCallable(this)?Object(new this(length)):new Array(length);for(i=0;i<length;++i){value=list[i];if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}}}result.length=length;return result},of:function(){return Array.from(arguments)}};defineProperties(Array,ArrayShims);var arrayFromSwallowsNegativeLengths=function(){try{return Array.from({length:-1}).length===0}catch(e){return false}};if(!arrayFromSwallowsNegativeLengths()){defineProperty(Array,"from",ArrayShims.from,true)}ArrayIterator=function(array,kind){this.i=0;this.array=array;this.kind=kind};defineProperties(ArrayIterator.prototype,{next:function(){var i=this.i,array=this.array;if(!(this instanceof ArrayIterator)){throw new TypeError("Not an ArrayIterator")}if(typeof array!=="undefined"){var len=ES.ToLength(array.length);for(;i<len;i++){var kind=this.kind;var retval;if(kind==="key"){retval=i}else if(kind==="value"){retval=array[i]}else if(kind==="entry"){retval=[i,array[i]]}this.i=i+1;return{value:retval,done:false}}}this.array=void 0;return{value:void 0,done:true}}});addIterator(ArrayIterator.prototype);var ArrayPrototypeShims={copyWithin:function(target,start){var end=arguments[2];var o=ES.ToObject(this);var len=ES.ToLength(o.length);target=ES.ToInteger(target);start=ES.ToInteger(start);var to=target<0?Math.max(len+target,0):Math.min(target,len);var from=start<0?Math.max(len+start,0):Math.min(start,len);end=typeof end==="undefined"?len:ES.ToInteger(end);var fin=end<0?Math.max(len+end,0):Math.min(end,len);var count=Math.min(fin-from,len-to);var direction=1;if(from<to&&to<from+count){direction=-1;from+=count-1;to+=count-1}while(count>0){if(_hasOwnProperty.call(o,from)){o[to]=o[from]}else{delete o[from]}from+=direction;to+=direction;count-=1}return o},fill:function(value){var start=arguments.length>1?arguments[1]:void 0;var end=arguments.length>2?arguments[2]:void 0;var O=ES.ToObject(this);var len=ES.ToLength(O.length);start=ES.ToInteger(typeof start==="undefined"?0:start);end=ES.ToInteger(typeof end==="undefined"?len:end);var relativeStart=start<0?Math.max(len+start,0):Math.min(start,len);var relativeEnd=end<0?len+end:end;for(var i=relativeStart;i<len&&i<relativeEnd;++i){O[i]=value}return O},find:function find(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#find: predicate must be a function")}var thisArg=arguments[1];for(var i=0,value;i<length;i++){value=list[i];if(predicate.call(thisArg,value,i,list)){return value}}return},findIndex:function findIndex(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#findIndex: predicate must be a function")}var thisArg=arguments[1];for(var i=0;i<length;i++){if(predicate.call(thisArg,list[i],i,list)){return i}}return-1},keys:function(){return new ArrayIterator(this,"key")},values:function(){return new ArrayIterator(this,"value")},entries:function(){return new ArrayIterator(this,"entry")}};if(Array.prototype.keys&&!ES.IsCallable([1].keys().next)){delete Array.prototype.keys}if(Array.prototype.entries&&!ES.IsCallable([1].entries().next)){delete Array.prototype.entries}defineProperties(Array.prototype,ArrayPrototypeShims);addIterator(Array.prototype,function(){return this.values()});if(Object.getPrototypeOf){addIterator(Object.getPrototypeOf([].values()))}var maxSafeInteger=Math.pow(2,53)-1;defineProperties(Number,{MAX_SAFE_INTEGER:maxSafeInteger,MIN_SAFE_INTEGER:-maxSafeInteger,EPSILON:2.220446049250313e-16,parseInt:globals.parseInt,parseFloat:globals.parseFloat,isFinite:function(value){return typeof value==="number"&&global_isFinite(value)},isInteger:function(value){return Number.isFinite(value)&&ES.ToInteger(value)===value},isSafeInteger:function(value){return Number.isInteger(value)&&Math.abs(value)<=Number.MAX_SAFE_INTEGER},isNaN:function(value){return value!==value}});if(![,1].find(function(item,idx){return idx===0})){defineProperty(Array.prototype,"find",ArrayPrototypeShims.find,true)}if([,1].findIndex(function(item,idx){return idx===0})!==0){defineProperty(Array.prototype,"findIndex",ArrayPrototypeShims.findIndex,true)}if(supportsDescriptors){defineProperties(Object,{getPropertyDescriptor:function(subject,name){var pd=Object.getOwnPropertyDescriptor(subject,name);var proto=Object.getPrototypeOf(subject);while(typeof pd==="undefined"&&proto!==null){pd=Object.getOwnPropertyDescriptor(proto,name);proto=Object.getPrototypeOf(proto)}return pd},getPropertyNames:function(subject){var result=Object.getOwnPropertyNames(subject);var proto=Object.getPrototypeOf(subject);var addProperty=function(property){if(result.indexOf(property)===-1){result.push(property)}};while(proto!==null){Object.getOwnPropertyNames(proto).forEach(addProperty);proto=Object.getPrototypeOf(proto)}return result}});defineProperties(Object,{assign:function(target,source){if(!ES.TypeIsObject(target)){throw new TypeError("target must be an object")}return Array.prototype.reduce.call(arguments,function(target,source){return Object.keys(Object(source)).reduce(function(target,key){target[key]=source[key];return target},target)})},is:function(a,b){return ES.SameValue(a,b)},setPrototypeOf:function(Object,magic){var set;var checkArgs=function(O,proto){if(!ES.TypeIsObject(O)){throw new TypeError("cannot set prototype on a non-object")}if(!(proto===null||ES.TypeIsObject(proto))){throw new TypeError("can only set prototype to an object or null"+proto)}};var setPrototypeOf=function(O,proto){checkArgs(O,proto);set.call(O,proto);return O};try{set=Object.getOwnPropertyDescriptor(Object.prototype,magic).set;set.call({},null)}catch(e){if(Object.prototype!=={}[magic]){return}set=function(proto){this[magic]=proto};setPrototypeOf.polyfill=setPrototypeOf(setPrototypeOf({},null),Object.prototype)instanceof Object}return setPrototypeOf}(Object,"__proto__")})}if(Object.setPrototypeOf&&Object.getPrototypeOf&&Object.getPrototypeOf(Object.setPrototypeOf({},null))!==null&&Object.getPrototypeOf(Object.create(null))===null){(function(){var FAKENULL=Object.create(null);var gpo=Object.getPrototypeOf,spo=Object.setPrototypeOf;Object.getPrototypeOf=function(o){var result=gpo(o);return result===FAKENULL?null:result};Object.setPrototypeOf=function(o,p){if(p===null){p=FAKENULL}return spo(o,p)};Object.setPrototypeOf.polyfill=false})()}try{Object.keys("foo")}catch(e){var originalObjectKeys=Object.keys;Object.keys=function(obj){return originalObjectKeys(ES.ToObject(obj))}}var MathShims={acosh:function(value){value=Number(value);if(Number.isNaN(value)||value<1){return NaN}if(value===1){return 0}if(value===Infinity){return value}return Math.log(value+Math.sqrt(value*value-1))},asinh:function(value){value=Number(value);if(value===0||!global_isFinite(value)){return value}return value<0?-Math.asinh(-value):Math.log(value+Math.sqrt(value*value+1))},atanh:function(value){value=Number(value);if(Number.isNaN(value)||value<-1||value>1){return NaN}if(value===-1){return-Infinity}if(value===1){return Infinity}if(value===0){return value}return.5*Math.log((1+value)/(1-value))},cbrt:function(value){value=Number(value);if(value===0){return value}var negate=value<0,result;if(negate){value=-value}result=Math.pow(value,1/3);return negate?-result:result},clz32:function(value){value=Number(value);var number=ES.ToUint32(value);if(number===0){return 32}return 32-number.toString(2).length},cosh:function(value){value=Number(value);if(value===0){return 1}if(Number.isNaN(value)){return NaN}if(!global_isFinite(value)){return Infinity}if(value<0){value=-value}if(value>21){return Math.exp(value)/2}return(Math.exp(value)+Math.exp(-value))/2},expm1:function(value){value=Number(value);if(value===-Infinity){return-1}if(!global_isFinite(value)||value===0){return value}return Math.exp(value)-1},hypot:function(x,y){var anyNaN=false;var allZero=true;var anyInfinity=false;var numbers=[];Array.prototype.every.call(arguments,function(arg){var num=Number(arg);if(Number.isNaN(num)){anyNaN=true}else if(num===Infinity||num===-Infinity){anyInfinity=true}else if(num!==0){allZero=false}if(anyInfinity){return false}else if(!anyNaN){numbers.push(Math.abs(num))}return true});if(anyInfinity){return Infinity}if(anyNaN){return NaN}if(allZero){return 0}numbers.sort(function(a,b){return b-a});var largest=numbers[0];var divided=numbers.map(function(number){return number/largest});var sum=divided.reduce(function(sum,number){return sum+=number*number},0);return largest*Math.sqrt(sum)},log2:function(value){return Math.log(value)*Math.LOG2E},log10:function(value){return Math.log(value)*Math.LOG10E},log1p:function(value){value=Number(value);if(value<-1||Number.isNaN(value)){return NaN}if(value===0||value===Infinity){return value}if(value===-1){return-Infinity}var result=0;var n=50;if(value<0||value>1){return Math.log(1+value)}for(var i=1;i<n;i++){if(i%2===0){result-=Math.pow(value,i)/i}else{result+=Math.pow(value,i)/i}}return result},sign:function(value){var number=+value;if(number===0){return number}if(Number.isNaN(number)){return number}return number<0?-1:1},sinh:function(value){value=Number(value);if(!global_isFinite(value)||value===0){return value}return(Math.exp(value)-Math.exp(-value))/2},tanh:function(value){value=Number(value);if(Number.isNaN(value)||value===0){return value}if(value===Infinity){return 1}if(value===-Infinity){return-1}return(Math.exp(value)-Math.exp(-value))/(Math.exp(value)+Math.exp(-value))},trunc:function(value){var number=Number(value);return number<0?-Math.floor(-number):Math.floor(number)},imul:function(x,y){x=ES.ToUint32(x);y=ES.ToUint32(y);var ah=x>>>16&65535;var al=x&65535;var bh=y>>>16&65535;var bl=y&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0},fround:function(x){if(x===0||x===Infinity||x===-Infinity||Number.isNaN(x)){return x}var num=Number(x);return numberConversion.toFloat32(num)}};defineProperties(Math,MathShims);if(Math.imul(4294967295,5)!==-5){Math.imul=MathShims.imul}var PromiseShim=function(){var Promise,Promise$prototype;ES.IsPromise=function(promise){if(!ES.TypeIsObject(promise)){return false}if(!promise._promiseConstructor){return false}if(typeof promise._status==="undefined"){return false}return true};var PromiseCapability=function(C){if(!ES.IsCallable(C)){throw new TypeError("bad promise constructor")}var capability=this;var resolver=function(resolve,reject){capability.resolve=resolve;capability.reject=reject};capability.promise=ES.Construct(C,[resolver]);if(!capability.promise._es6construct){throw new TypeError("bad promise constructor")}if(!(ES.IsCallable(capability.resolve)&&ES.IsCallable(capability.reject))){throw new TypeError("bad promise constructor")}};var setTimeout=globals.setTimeout;var makeZeroTimeout;if(typeof window!=="undefined"&&ES.IsCallable(window.postMessage)){makeZeroTimeout=function(){var timeouts=[];var messageName="zero-timeout-message";var setZeroTimeout=function(fn){timeouts.push(fn);window.postMessage(messageName,"*")};var handleMessage=function(event){if(event.source==window&&event.data==messageName){event.stopPropagation();if(timeouts.length===0){return}var fn=timeouts.shift();fn()}};window.addEventListener("message",handleMessage,true);return setZeroTimeout}}var makePromiseAsap=function(){var P=globals.Promise;return P&&P.resolve&&function(task){return P.resolve().then(task)}};var enqueue=ES.IsCallable(globals.setImmediate)?globals.setImmediate.bind(globals):typeof process==="object"&&process.nextTick?process.nextTick:makePromiseAsap()||(ES.IsCallable(makeZeroTimeout)?makeZeroTimeout():function(task){setTimeout(task,0)});var triggerPromiseReactions=function(reactions,x){reactions.forEach(function(reaction){enqueue(function(){var handler=reaction.handler;var capability=reaction.capability;var resolve=capability.resolve;var reject=capability.reject;try{var result=handler(x);if(result===capability.promise){throw new TypeError("self resolution")}var updateResult=updatePromiseFromPotentialThenable(result,capability);if(!updateResult){resolve(result)}}catch(e){reject(e)}})})};var updatePromiseFromPotentialThenable=function(x,capability){if(!ES.TypeIsObject(x)){return false}var resolve=capability.resolve;var reject=capability.reject;try{var then=x.then;if(!ES.IsCallable(then)){return false}then.call(x,resolve,reject)}catch(e){reject(e)}return true};var promiseResolutionHandler=function(promise,onFulfilled,onRejected){return function(x){if(x===promise){return onRejected(new TypeError("self resolution"))}var C=promise._promiseConstructor;var capability=new PromiseCapability(C);var updateResult=updatePromiseFromPotentialThenable(x,capability);if(updateResult){return capability.promise.then(onFulfilled,onRejected)}else{return onFulfilled(x)}}};Promise=function(resolver){var promise=this;promise=emulateES6construct(promise);if(!promise._promiseConstructor){throw new TypeError("bad promise")}if(typeof promise._status!=="undefined"){throw new TypeError("promise already initialized")}if(!ES.IsCallable(resolver)){throw new TypeError("not a valid resolver")}promise._status="unresolved";promise._resolveReactions=[];promise._rejectReactions=[];var resolve=function(resolution){if(promise._status!=="unresolved"){return}var reactions=promise._resolveReactions;promise._result=resolution;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-resolution";triggerPromiseReactions(reactions,resolution)};var reject=function(reason){if(promise._status!=="unresolved"){return}var reactions=promise._rejectReactions;promise._result=reason;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-rejection";triggerPromiseReactions(reactions,reason)};try{resolver(resolve,reject)}catch(e){reject(e)}return promise};Promise$prototype=Promise.prototype;defineProperties(Promise,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Promise$prototype;obj=obj||create(prototype);defineProperties(obj,{_status:void 0,_result:void 0,_resolveReactions:void 0,_rejectReactions:void 0,_promiseConstructor:void 0});obj._promiseConstructor=constructor;return obj}});var _promiseAllResolver=function(index,values,capability,remaining){var done=false;return function(x){if(done){return}done=true;values[index]=x;if(--remaining.count===0){var resolve=capability.resolve;resolve(values)}}};Promise.all=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);var values=[],remaining={count:1};for(var index=0;;index++){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);var resolveElement=_promiseAllResolver(index,values,capability,remaining);remaining.count++;nextPromise.then(resolveElement,capability.reject)}if(--remaining.count===0){resolve(values)}}catch(e){reject(e)}return capability.promise};Promise.race=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);nextPromise.then(resolve,reject)}}catch(e){reject(e)}return capability.promise};Promise.reject=function(reason){var C=this;var capability=new PromiseCapability(C);var reject=capability.reject;reject(reason);return capability.promise};Promise.resolve=function(v){var C=this;if(ES.IsPromise(v)){var constructor=v._promiseConstructor;if(constructor===C){return v}}var capability=new PromiseCapability(C);var resolve=capability.resolve;resolve(v);return capability.promise};Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){var promise=this;if(!ES.IsPromise(promise)){throw new TypeError("not a promise")}var C=this.constructor;var capability=new PromiseCapability(C);if(!ES.IsCallable(onRejected)){onRejected=function(e){throw e}}if(!ES.IsCallable(onFulfilled)){onFulfilled=function(x){return x}}var resolutionHandler=promiseResolutionHandler(promise,onFulfilled,onRejected);var resolveReaction={capability:capability,handler:resolutionHandler};var rejectReaction={capability:capability,handler:onRejected};switch(promise._status){case"unresolved":promise._resolveReactions.push(resolveReaction);promise._rejectReactions.push(rejectReaction);break;case"has-resolution":triggerPromiseReactions([resolveReaction],promise._result);break;case"has-rejection":triggerPromiseReactions([rejectReaction],promise._result);break;default:throw new TypeError("unexpected")}return capability.promise};return Promise}();defineProperties(globals,{Promise:PromiseShim});var promiseSupportsSubclassing=supportsSubclassing(globals.Promise,function(S){return S.resolve(42)instanceof S});var promiseIgnoresNonFunctionThenCallbacks=function(){try{globals.Promise.reject(42).then(null,5).then(null,function(){});return true}catch(ex){return false}}();var promiseRequiresObjectContext=function(){try{Promise.call(3,function(){})}catch(e){return true}return false}();if(!promiseSupportsSubclassing||!promiseIgnoresNonFunctionThenCallbacks||!promiseRequiresObjectContext){globals.Promise=PromiseShim}var testOrder=function(a){var b=Object.keys(a.reduce(function(o,k){o[k]=true;return o},{}));return a.join(":")===b.join(":")};var preservesInsertionOrder=testOrder(["z","a","bb"]);var preservesNumericInsertionOrder=testOrder(["z",1,"a","3",2]);if(supportsDescriptors){var fastkey=function fastkey(key){if(!preservesInsertionOrder){return null}var type=typeof key;if(type==="string"){return"$"+key}else if(type==="number"){if(!preservesNumericInsertionOrder){return"n"+key}return key}return null};var emptyObject=function emptyObject(){return Object.create?Object.create(null):{}};var collectionShims={Map:function(){var empty={};function MapEntry(key,value){this.key=key;this.value=value;this.next=null;this.prev=null}MapEntry.prototype.isRemoved=function(){return this.key===empty
};function MapIterator(map,kind){this.head=map._head;this.i=this.head;this.kind=kind}MapIterator.prototype={next:function(){var i=this.i,kind=this.kind,head=this.head,result;if(typeof this.i==="undefined"){return{value:void 0,done:true}}while(i.isRemoved()&&i!==head){i=i.prev}while(i.next!==head){i=i.next;if(!i.isRemoved()){if(kind==="key"){result=i.key}else if(kind==="value"){result=i.value}else{result=[i.key,i.value]}this.i=i;return{value:result,done:false}}}this.i=void 0;return{value:void 0,done:true}}};addIterator(MapIterator.prototype);function Map(iterable){var map=this;map=emulateES6construct(map);if(!map._es6map){throw new TypeError("bad map")}var head=new MapEntry(null,null);head.next=head.prev=head;defineProperties(map,{_head:head,_storage:emptyObject(),_size:0});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=map.set;if(!ES.IsCallable(adder)){throw new TypeError("bad map")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;if(!ES.TypeIsObject(nextItem)){throw new TypeError("expected iterable of pairs")}adder.call(map,nextItem[0],nextItem[1])}}return map}var Map$prototype=Map.prototype;defineProperties(Map,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Map$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6map:true});return obj}});Object.defineProperty(Map.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._size==="undefined"){throw new TypeError("size method called on incompatible Map")}return this._size}});defineProperties(Map.prototype,{get:function(key){var fkey=fastkey(key);if(fkey!==null){var entry=this._storage[fkey];if(entry){return entry.value}else{return}}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return i.value}}return},has:function(key){var fkey=fastkey(key);if(fkey!==null){return typeof this._storage[fkey]!=="undefined"}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return true}}return false},set:function(key,value){var head=this._head,i=head,entry;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]!=="undefined"){this._storage[fkey].value=value;return}else{entry=this._storage[fkey]=new MapEntry(key,value);i=head.prev}}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.value=value;return}}entry=entry||new MapEntry(key,value);if(ES.SameValue(-0,key)){entry.key=+0}entry.next=this._head;entry.prev=this._head.prev;entry.prev.next=entry;entry.next.prev=entry;this._size+=1;return this},"delete":function(key){var head=this._head,i=head;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]==="undefined"){return false}i=this._storage[fkey].prev;delete this._storage[fkey]}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.key=i.value=empty;i.prev.next=i.next;i.next.prev=i.prev;this._size-=1;return true}}return false},clear:function(){this._size=0;this._storage=emptyObject();var head=this._head,i=head,p=i.next;while((i=p)!==head){i.key=i.value=empty;p=i.next;i.next=i.prev=head}head.next=head.prev=head},keys:function(){return new MapIterator(this,"key")},values:function(){return new MapIterator(this,"value")},entries:function(){return new MapIterator(this,"key+value")},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var it=this.entries();for(var entry=it.next();!entry.done;entry=it.next()){callback.call(context,entry.value[1],entry.value[0],this)}}});addIterator(Map.prototype,function(){return this.entries()});return Map}(),Set:function(){var SetShim=function Set(iterable){var set=this;set=emulateES6construct(set);if(!set._es6set){throw new TypeError("bad set")}defineProperties(set,{"[[SetData]]":null,_storage:emptyObject()});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=set.add;if(!ES.IsCallable(adder)){throw new TypeError("bad set")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;adder.call(set,nextItem)}}return set};var Set$prototype=SetShim.prototype;defineProperties(SetShim,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Set$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6set:true});return obj}});var ensureMap=function ensureMap(set){if(!set["[[SetData]]"]){var m=set["[[SetData]]"]=new collectionShims.Map;Object.keys(set._storage).forEach(function(k){if(k.charCodeAt(0)===36){k=k.slice(1)}else if(k.charAt(0)==="n"){k=+k.slice(1)}else{k=+k}m.set(k,k)});set._storage=null}};Object.defineProperty(SetShim.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._storage==="undefined"){throw new TypeError("size method called on incompatible Set")}ensureMap(this);return this["[[SetData]]"].size}});defineProperties(SetShim.prototype,{has:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){return!!this._storage[fkey]}ensureMap(this);return this["[[SetData]]"].has(key)},add:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){this._storage[fkey]=true;return}ensureMap(this);this["[[SetData]]"].set(key,key);return this},"delete":function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){var hasFKey=_hasOwnProperty.call(this._storage,fkey);return delete this._storage[fkey]&&hasFKey}ensureMap(this);return this["[[SetData]]"]["delete"](key)},clear:function(){if(this._storage){this._storage=emptyObject();return}return this["[[SetData]]"].clear()},keys:function(){ensureMap(this);return this["[[SetData]]"].keys()},values:function(){ensureMap(this);return this["[[SetData]]"].values()},entries:function(){ensureMap(this);return this["[[SetData]]"].entries()},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var entireSet=this;ensureMap(this);this["[[SetData]]"].forEach(function(value,key){callback.call(context,key,key,entireSet)})}});addIterator(SetShim.prototype,function(){return this.values()});return SetShim}()};defineProperties(globals,collectionShims);if(globals.Map||globals.Set){if(typeof globals.Map.prototype.clear!=="function"||(new globals.Set).size!==0||(new globals.Map).size!==0||typeof globals.Map.prototype.keys!=="function"||typeof globals.Set.prototype.keys!=="function"||typeof globals.Map.prototype.forEach!=="function"||typeof globals.Set.prototype.forEach!=="function"||isCallableWithoutNew(globals.Map)||isCallableWithoutNew(globals.Set)||!supportsSubclassing(globals.Map,function(M){var m=new M([]);m.set(42,42);return m instanceof M})){globals.Map=collectionShims.Map;globals.Set=collectionShims.Set}}addIterator(Object.getPrototypeOf((new globals.Map).keys()));addIterator(Object.getPrototypeOf((new globals.Set).keys()))}return globals})}).call(this,require("_process"))},{_process:2}],4:[function(require,module,exports){"use strict";if(!require("./is-implemented")()){Object.defineProperty(require("es5-ext/global"),"Symbol",{value:require("./polyfill"),configurable:true,enumerable:false,writable:true})}},{"./is-implemented":5,"./polyfill":20,"es5-ext/global":7}],5:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.isRegExp!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],6:[function(require,module,exports){"use strict";var assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),isCallable=require("es5-ext/object/is-callable"),contains=require("es5-ext/string/#/contains"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":8,"es5-ext/object/is-callable":11,"es5-ext/object/normalize-options":15,"es5-ext/string/#/contains":17}],7:[function(require,module,exports){"use strict";module.exports=new Function("return this")()},{}],8:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":9,"./shim":10}],9:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],10:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<l;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":12,"../valid-value":16}],11:[function(require,module,exports){"use strict";module.exports=function(obj){return typeof obj==="function"}},{}],12:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":13,"./shim":14}],13:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],14:[function(require,module,exports){"use strict";var keys=Object.keys;module.exports=function(object){return keys(object==null?object:Object(object))}},{}],15:[function(require,module,exports){"use strict";var assign=require("./assign"),forEach=Array.prototype.forEach,create=Object.create,getPrototypeOf=Object.getPrototypeOf,process;process=function(src,obj){var proto=getPrototypeOf(src);return assign(proto?process(proto,obj):obj,src)};module.exports=function(options){var result=create(null);forEach.call(arguments,function(options){if(options==null)return;process(Object(options),result)});return result}},{"./assign":8}],16:[function(require,module,exports){"use strict";module.exports=function(value){if(value==null)throw new TypeError("Cannot use null or undefined");return value}},{}],17:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":18,"./shim":19}],18:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],19:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],20:[function(require,module,exports){"use strict";var d=require("d"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;return"@@"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError("TypeError: Symbol is not a constructor")}symbol=create(Symbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};Object.defineProperties(Symbol,{create:d("",Symbol("create")),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),isRegExp:d("",Symbol("isRegExp")),iterator:d("",Symbol("iterator")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(Symbol.prototype,{properToString:d(function(){return"Symbol ("+this.__description__+")"}),toString:d("",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(hint){throw new TypeError("Conversion of symbol objects is not allowed")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"))},{d:6}],21:[function(require,module,exports){"use strict";module.exports=require("./lib/core.js");require("./lib/done.js");require("./lib/es6-extensions.js");require("./lib/node-extensions.js")},{"./lib/core.js":22,"./lib/done.js":23,"./lib/es6-extensions.js":24,"./lib/node-extensions.js":25}],22:[function(require,module,exports){"use strict";var asap=require("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 self.constructor(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{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}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:26}],23:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;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})})}},{"./core.js":22,asap:26}],24:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;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=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.all=function(arr){var args=Array.prototype.slice.call(arr);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)})})};Promise.prototype["catch"]=function(onRejected){return this.then(null,onRejected)}},{"./core.js":22,asap:26}],25:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;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;var ctx=this;try{return fn.apply(this,arguments).nodeify(callback,ctx)}catch(ex){if(callback===null||typeof callback=="undefined"){return new Promise(function(resolve,reject){reject(ex)})}else{asap(function(){callback.call(ctx,ex)})}}}};Promise.prototype.nodeify=function(callback,ctx){if(typeof callback!="function")return this;this.then(function(value){asap(function(){callback.call(ctx,null,value)})},function(err){asap(function(){callback.call(ctx,err)})})}},{"./core.js":22,asap:26}],26:[function(require,module,exports){(function(process){var head={task:void 0,next:null};var tail=head;var flushing=false;var requestFlush=void 0;var isNodeJS=false;function flush(){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){if(domain){domain.exit()}setTimeout(flush,0);if(domain){domain.enter()}throw e}else{setTimeout(function(){throw e},0)}}if(domain){domain.exit()}}flushing=false}if(typeof process!=="undefined"&&process.nextTick){isNodeJS=true;requestFlush=function(){process.nextTick(flush)}}else if(typeof setImmediate==="function"){if(typeof window!=="undefined"){requestFlush=setImmediate.bind(window,flush)}else{requestFlush=function(){setImmediate(flush)}}}else if(typeof MessageChannel!=="undefined"){var channel=new MessageChannel;channel.port1.onmessage=flush;requestFlush=function(){channel.port2.postMessage(0)}}else{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,require("_process"))},{_process:2}],27:[function(require,module,exports){!function(){var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";if(typeof Promise==="undefined")try{Promise=require("promise")}catch(ignored){}if(typeof regeneratorRuntime==="object"){return}var runtime=regeneratorRuntime=typeof exports==="undefined"?{}:exports;function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}var Gp=Generator.prototype;var GFp=GeneratorFunction.prototype=Object.create(Function.prototype);GFp.constructor=GeneratorFunction;GFp.prototype=Gp;Gp.constructor=GFp;if(GeneratorFunction.name!=="GeneratorFunction"){GeneratorFunction.name="GeneratorFunction"}if(GeneratorFunction.name!=="GeneratorFunction"){throw new Error("GeneratorFunction renamed?")}runtime.isGeneratorFunction=function(genFun){var ctor=genFun&&genFun.constructor;return ctor?GeneratorFunction.name===ctor.name:false};runtime.mark=function(genFun){genFun.__proto__=GFp;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator.throw);function step(arg){try{var info=this(arg);var value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){throw new Error("Generator has already finished")}while(true){var delegate=context.delegate;if(delegate){try{var info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator.throw=invoke.bind(generator,"throw");generator.return=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){var iterator=iterable;if(iteratorSymbol in iterable){iterator=iterable[iteratorSymbol]()}else if(!isNaN(iterable.length)){var i=-1;iterator=function next(){while(++i<iterable.length){if(i in iterable){next.value=iterable[i];next.done=false;return next}}next.done=true;return next};iterator.next=iterator}return iterator}runtime.values=values;Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}()},{promise:21}]},{},[1]); |
src/classic/class/__tests__/ReactClassMixin-test.js | Jericho25/react | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var mocks = require('mocks');
var React;
var ReactTestUtils;
var reactComponentExpect;
var TestComponent;
var TestComponentWithPropTypes;
var TestComponentWithReverseSpec;
var mixinPropValidator;
var componentPropValidator;
describe('ReactClass-mixin', function() {
beforeEach(function() {
React = require('React');
ReactTestUtils = require('ReactTestUtils');
reactComponentExpect = require('reactComponentExpect');
mixinPropValidator = mocks.getMockFunction();
componentPropValidator = mocks.getMockFunction();
var MixinA = {
propTypes: {
propA: function() {}
},
componentDidMount: function() {
this.props.listener('MixinA didMount');
}
};
var MixinB = {
mixins: [MixinA],
propTypes: {
propB: function() {}
},
componentDidMount: function() {
this.props.listener('MixinB didMount');
}
};
var MixinBWithReverseSpec = {
componentDidMount: function() {
this.props.listener('MixinBWithReverseSpec didMount');
},
mixins: [MixinA]
};
var MixinC = {
statics: {
staticC: function() {}
},
componentDidMount: function() {
this.props.listener('MixinC didMount');
}
};
var MixinD = {
propTypes: {
value: mixinPropValidator
}
};
TestComponent = React.createClass({
mixins: [MixinB, MixinC, MixinD],
statics: {
staticComponent: function() {}
},
propTypes: {
propComponent: function() {}
},
componentDidMount: function() {
this.props.listener('Component didMount');
},
render: function() {
return <div />;
}
});
TestComponentWithReverseSpec = React.createClass({
render: function() {
return <div />;
},
componentDidMount: function() {
this.props.listener('Component didMount');
},
mixins: [MixinBWithReverseSpec, MixinC, MixinD]
});
TestComponentWithPropTypes = React.createClass({
mixins: [MixinD],
propTypes: {
value: componentPropValidator
},
render: function() {
return <div />;
}
});
});
it('should support merging propTypes and statics', function() {
var listener = mocks.getMockFunction();
var instance = <TestComponent listener={listener} />;
instance = ReactTestUtils.renderIntoDocument(instance);
var instancePropTypes = instance.constructor.propTypes;
expect('propA' in instancePropTypes).toBe(true);
expect('propB' in instancePropTypes).toBe(true);
expect('propComponent' in instancePropTypes).toBe(true);
expect('staticC' in TestComponent).toBe(true);
expect('staticComponent' in TestComponent).toBe(true);
});
it('should support chaining delegate functions', function() {
var listener = mocks.getMockFunction();
var instance = <TestComponent listener={listener} />;
instance = ReactTestUtils.renderIntoDocument(instance);
expect(listener.mock.calls).toEqual([
['MixinA didMount'],
['MixinB didMount'],
['MixinC didMount'],
['Component didMount']
]);
});
it('should chain functions regardless of spec property order', function() {
var listener = mocks.getMockFunction();
var instance = <TestComponentWithReverseSpec listener={listener} />;
instance = ReactTestUtils.renderIntoDocument(instance);
expect(listener.mock.calls).toEqual([
['MixinA didMount'],
['MixinBWithReverseSpec didMount'],
['MixinC didMount'],
['Component didMount']
]);
});
it('should validate prop types via mixins', function() {
expect(TestComponent.propTypes).toBeDefined();
expect(TestComponent.propTypes.value)
.toBe(mixinPropValidator);
});
it('should override mixin prop types with class prop types', function() {
// Sanity check...
expect(componentPropValidator).toNotBe(mixinPropValidator);
// Actually check...
expect(TestComponentWithPropTypes.propTypes)
.toBeDefined();
expect(TestComponentWithPropTypes.propTypes.value)
.toNotBe(mixinPropValidator);
expect(TestComponentWithPropTypes.propTypes.value)
.toBe(componentPropValidator);
});
it('should support mixins with getInitialState()', function() {
var Mixin = {
getInitialState: function() {
return {mixin: true};
}
};
var Component = React.createClass({
mixins: [Mixin],
getInitialState: function() {
return {component: true};
},
render: function() {
return <span />;
}
});
var instance = <Component />;
instance = ReactTestUtils.renderIntoDocument(instance);
expect(instance.state.component).toBe(true);
expect(instance.state.mixin).toBe(true);
});
it('should throw with conflicting getInitialState() methods', function() {
var Mixin = {
getInitialState: function() {
return {x: true};
}
};
var Component = React.createClass({
mixins: [Mixin],
getInitialState: function() {
return {x: true};
},
render: function() {
return <span />;
}
});
var instance = <Component />;
expect(function() {
instance = ReactTestUtils.renderIntoDocument(instance);
}).toThrow(
'Invariant Violation: mergeIntoWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: `x`. This conflict ' +
'may be due to a mixin; in particular, this may be caused by two ' +
'getInitialState() or getDefaultProps() methods returning objects ' +
'with clashing keys.'
);
});
it('should not mutate objects returned by getInitialState()', function() {
var Mixin = {
getInitialState: function() {
return Object.freeze({mixin: true});
}
};
var Component = React.createClass({
mixins: [Mixin],
getInitialState: function() {
return Object.freeze({component: true});
},
render: function() {
return <span />;
}
});
expect(() => {
ReactTestUtils.renderIntoDocument(<Component />);
}).not.toThrow();
});
it('should support statics in mixins', function() {
var Mixin = {
statics: {
foo: 'bar'
}
};
var Component = React.createClass({
mixins: [Mixin],
statics: {
abc: 'def'
},
render: function() {
return <span />;
}
});
var instance = <Component />;
instance = ReactTestUtils.renderIntoDocument(instance);
expect(instance.constructor.foo).toBe('bar');
expect(Component.foo).toBe('bar');
expect(instance.constructor.abc).toBe('def');
expect(Component.abc).toBe('def');
});
it("should throw if mixins override each others' statics", function() {
expect(function() {
var Mixin = {
statics: {
abc: 'foo'
}
};
React.createClass({
mixins: [Mixin],
statics: {
abc: 'bar'
},
render: function() {
return <span />;
}
});
}).toThrow(
'Invariant Violation: ReactClass: You are attempting to ' +
'define `abc` on your component more than once. This conflict may be ' +
'due to a mixin.'
);
});
it("should throw if mixins override functions in statics", function() {
expect(function() {
var Mixin = {
statics: {
abc: function() { console.log('foo'); }
}
};
React.createClass({
mixins: [Mixin],
statics: {
abc: function() { console.log('bar'); }
},
render: function() {
return <span />;
}
});
}).toThrow(
'Invariant Violation: ReactClass: You are attempting to ' +
'define `abc` on your component more than once. This conflict may be ' +
'due to a mixin.'
);
});
it("should throw if the mixin is a React component", function() {
expect(function() {
React.createClass({
mixins: [<div />],
render: function() {
return <span />;
}
});
}).toThrow(
'Invariant Violation: ReactClass: You\'re attempting to ' +
'use a component as a mixin. Instead, just use a regular object.'
);
});
it("should throw if the mixin is a React component class", function() {
expect(function() {
var Component = React.createClass({
render: function() {
return <span />;
}
});
React.createClass({
mixins: [Component],
render: function() {
return <span />;
}
});
}).toThrow(
'Invariant Violation: ReactClass: You\'re attempting to ' +
'use a component class as a mixin. Instead, just use a regular object.'
);
});
it('should have bound the mixin methods to the component', function() {
var mixin = {
mixinFunc: function() {return this;}
};
var Component = React.createClass({
mixins: [mixin],
componentDidMount: function() {
expect(this.mixinFunc()).toBe(this);
},
render: function() {
return <span />;
}
});
var instance = <Component />;
instance = ReactTestUtils.renderIntoDocument(instance);
});
it('should include the mixin keys in even if their values are falsy',
function() {
var mixin = {
keyWithNullValue: null,
randomCounter: 0
};
var Component = React.createClass({
mixins: [mixin],
componentDidMount: function() {
expect(this.randomCounter).toBe(0);
expect(this.keyWithNullValue).toBeNull();
},
render: function() {
return <span />;
}
});
var instance = <Component />;
instance = ReactTestUtils.renderIntoDocument(instance);
});
it('should work with a null getInitialState return value and a mixin', () => {
var Component;
var instance;
var Mixin = {
getInitialState: function() {
return {foo: 'bar'};
}
};
Component = React.createClass({
mixins: [Mixin],
getInitialState: function() {
return null;
},
render: function() {
return <span />;
}
});
expect(
() => ReactTestUtils.renderIntoDocument(<Component />)
).not.toThrow();
instance = <Component />;
instance = ReactTestUtils.renderIntoDocument(instance);
expect(instance.state).toEqual({foo: 'bar'});
// Also the other way round should work
var Mixin2 = {
getInitialState: function() {
return null;
}
};
Component = React.createClass({
mixins: [Mixin2],
getInitialState: function() {
return {foo: 'bar'};
},
render: function() {
return <span />;
}
});
expect(
() => ReactTestUtils.renderIntoDocument(<Component />)
).not.toThrow();
instance = <Component />;
instance = ReactTestUtils.renderIntoDocument(instance);
expect(instance.state).toEqual({foo: 'bar'});
// Multiple mixins should be fine too
Component = React.createClass({
mixins: [Mixin, Mixin2],
getInitialState: function() {
return {x: true};
},
render: function() {
return <span />;
}
});
expect(
() => ReactTestUtils.renderIntoDocument(<Component />)
).not.toThrow();
instance = <Component />;
instance = ReactTestUtils.renderIntoDocument(instance);
expect(instance.state).toEqual({foo: 'bar', x: true});
});
});
|
node_modules/react/lib/ReactTransitionGroup.js | wrleskovec/thoughtcrime | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = require('./React');
var ReactAddonsDOMDependencies = require('./ReactAddonsDOMDependencies');
var ReactTransitionChildMapping = require('./ReactTransitionChildMapping');
var emptyFunction = require('fbjs/lib/emptyFunction');
/**
* A basis for animations. When children are declaratively added or removed,
* special lifecycle hooks are called.
* See https://facebook.github.io/react/docs/animation.html#low-level-api-reacttransitiongroup
*/
var ReactTransitionGroup = function (_React$Component) {
_inherits(ReactTransitionGroup, _React$Component);
function ReactTransitionGroup() {
var _temp, _this, _ret;
_classCallCheck(this, ReactTransitionGroup);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
// TODO: can we get useful debug information to show at this point?
children: ReactTransitionChildMapping.getChildMapping(_this.props.children)
}, _this.performAppear = function (key) {
_this.currentlyTransitioningKeys[key] = true;
var component = _this.refs[key];
if (component.componentWillAppear) {
component.componentWillAppear(_this._handleDoneAppearing.bind(_this, key));
} else {
_this._handleDoneAppearing(key);
}
}, _this._handleDoneAppearing = function (key) {
var component = _this.refs[key];
if (component.componentDidAppear) {
component.componentDidAppear();
}
delete _this.currentlyTransitioningKeys[key];
var currentChildMapping;
if (process.env.NODE_ENV !== 'production') {
currentChildMapping = ReactTransitionChildMapping.getChildMapping(_this.props.children, ReactAddonsDOMDependencies.getReactInstanceMap().get(_this)._debugID);
} else {
currentChildMapping = ReactTransitionChildMapping.getChildMapping(_this.props.children);
}
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
// This was removed before it had fully appeared. Remove it.
_this.performLeave(key);
}
}, _this.performEnter = function (key) {
_this.currentlyTransitioningKeys[key] = true;
var component = _this.refs[key];
if (component.componentWillEnter) {
component.componentWillEnter(_this._handleDoneEntering.bind(_this, key));
} else {
_this._handleDoneEntering(key);
}
}, _this._handleDoneEntering = function (key) {
var component = _this.refs[key];
if (component.componentDidEnter) {
component.componentDidEnter();
}
delete _this.currentlyTransitioningKeys[key];
var currentChildMapping;
if (process.env.NODE_ENV !== 'production') {
currentChildMapping = ReactTransitionChildMapping.getChildMapping(_this.props.children, ReactAddonsDOMDependencies.getReactInstanceMap().get(_this)._debugID);
} else {
currentChildMapping = ReactTransitionChildMapping.getChildMapping(_this.props.children);
}
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
// This was removed before it had fully entered. Remove it.
_this.performLeave(key);
}
}, _this.performLeave = function (key) {
_this.currentlyTransitioningKeys[key] = true;
var component = _this.refs[key];
if (component.componentWillLeave) {
component.componentWillLeave(_this._handleDoneLeaving.bind(_this, key));
} else {
// Note that this is somewhat dangerous b/c it calls setState()
// again, effectively mutating the component before all the work
// is done.
_this._handleDoneLeaving(key);
}
}, _this._handleDoneLeaving = function (key) {
var component = _this.refs[key];
if (component.componentDidLeave) {
component.componentDidLeave();
}
delete _this.currentlyTransitioningKeys[key];
var currentChildMapping;
if (process.env.NODE_ENV !== 'production') {
currentChildMapping = ReactTransitionChildMapping.getChildMapping(_this.props.children, ReactAddonsDOMDependencies.getReactInstanceMap().get(_this)._debugID);
} else {
currentChildMapping = ReactTransitionChildMapping.getChildMapping(_this.props.children);
}
if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) {
// This entered again before it fully left. Add it again.
_this.performEnter(key);
} else {
_this.setState(function (state) {
var newChildren = _assign({}, state.children);
delete newChildren[key];
return { children: newChildren };
});
}
}, _temp), _possibleConstructorReturn(_this, _ret);
}
ReactTransitionGroup.prototype.componentWillMount = function componentWillMount() {
this.currentlyTransitioningKeys = {};
this.keysToEnter = [];
this.keysToLeave = [];
};
ReactTransitionGroup.prototype.componentDidMount = function componentDidMount() {
var initialChildMapping = this.state.children;
for (var key in initialChildMapping) {
if (initialChildMapping[key]) {
this.performAppear(key);
}
}
};
ReactTransitionGroup.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var nextChildMapping;
if (process.env.NODE_ENV !== 'production') {
nextChildMapping = ReactTransitionChildMapping.getChildMapping(nextProps.children, ReactAddonsDOMDependencies.getReactInstanceMap().get(this)._debugID);
} else {
nextChildMapping = ReactTransitionChildMapping.getChildMapping(nextProps.children);
}
var prevChildMapping = this.state.children;
this.setState({
children: ReactTransitionChildMapping.mergeChildMappings(prevChildMapping, nextChildMapping)
});
var key;
for (key in nextChildMapping) {
var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key);
if (nextChildMapping[key] && !hasPrev && !this.currentlyTransitioningKeys[key]) {
this.keysToEnter.push(key);
}
}
for (key in prevChildMapping) {
var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key);
if (prevChildMapping[key] && !hasNext && !this.currentlyTransitioningKeys[key]) {
this.keysToLeave.push(key);
}
}
// If we want to someday check for reordering, we could do it here.
};
ReactTransitionGroup.prototype.componentDidUpdate = function componentDidUpdate() {
var keysToEnter = this.keysToEnter;
this.keysToEnter = [];
keysToEnter.forEach(this.performEnter);
var keysToLeave = this.keysToLeave;
this.keysToLeave = [];
keysToLeave.forEach(this.performLeave);
};
ReactTransitionGroup.prototype.render = function render() {
// TODO: we could get rid of the need for the wrapper node
// by cloning a single child
var childrenToRender = [];
for (var key in this.state.children) {
var child = this.state.children[key];
if (child) {
// You may need to apply reactive updates to a child as it is leaving.
// The normal React way to do it won't work since the child will have
// already been removed. In case you need this behavior you can provide
// a childFactory function to wrap every child, even the ones that are
// leaving.
childrenToRender.push(React.cloneElement(this.props.childFactory(child), { ref: key, key: key }));
}
}
// Do not forward ReactTransitionGroup props to primitive DOM nodes
var props = _assign({}, this.props);
delete props.transitionLeave;
delete props.transitionName;
delete props.transitionAppear;
delete props.transitionEnter;
delete props.childFactory;
delete props.transitionLeaveTimeout;
delete props.transitionEnterTimeout;
delete props.transitionAppearTimeout;
delete props.component;
return React.createElement(this.props.component, props, childrenToRender);
};
return ReactTransitionGroup;
}(React.Component);
ReactTransitionGroup.displayName = 'ReactTransitionGroup';
ReactTransitionGroup.propTypes = {
component: React.PropTypes.any,
childFactory: React.PropTypes.func
};
ReactTransitionGroup.defaultProps = {
component: 'span',
childFactory: emptyFunction.thatReturnsArgument
};
module.exports = ReactTransitionGroup; |
docs/src/app/components/pages/components/Toggle/Page.js | barakmitz/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import toggleReadmeText from './README';
import ToggleExampleSimple from './ExampleSimple';
import toggleExampleSimpleCode from '!raw!./ExampleSimple';
import toggleCode from '!raw!material-ui/Toggle/Toggle';
const description = 'The second example is selected by default using the `defaultToggled` property. The third ' +
'example is disabled using the `disabled` property. The final example uses the `labelPosition` property to ' +
'position the label on the right.';
const TogglePage = () => (
<div>
<Title render={(previousTitle) => `Toggle - ${previousTitle}`} />
<MarkdownElement text={toggleReadmeText} />
<CodeExample
title="Examples"
description={description}
code={toggleExampleSimpleCode}
>
<ToggleExampleSimple />
</CodeExample>
<PropTypeDescription code={toggleCode} />
</div>
);
export default TogglePage;
|
ajax/libs/forerunnerdb/1.3.721/fdb-legacy.min.js | pombredanne/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/OldView"),a("../lib/OldView.Bind"),a("../lib/Grid");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":6,"../lib/Core":7,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;l>f;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(-1===g.value)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;g>b;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":33,"./Shared":39}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":33,"./Shared":39}],4:[function(a,b,c){"use strict";var d,e;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n;d=a("./Shared");var o=function(a,b){this.init.apply(this,arguments)};o.prototype.init=function(a,b){this.sharedPathSolver=n,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Events"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.CRUD"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Sorting"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.Updating"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=new h,d.synthesize(o.prototype,"deferredCalls"),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"metaData"),d.synthesize(o.prototype,"capped"),d.synthesize(o.prototype,"cappedSize"),o.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},o.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},o.prototype.data=function(){return this._data},o.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},o.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},o.prototype._onInsert=function(a,b){this.emit("insert",a,b)},o.prototype._onUpdate=function(a){this.emit("update",a)},o.prototype._onRemove=function(a){this.emit("remove",a)},o.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(o.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"mongoEmulation"),o.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),o.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},o.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},o.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},o.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},o.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},o.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},o.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},o.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length&&(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},o.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},o.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},o.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},o.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},o.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},o.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},o.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},o.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},o.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},o.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},o.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},o.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},o.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},o.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},o.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},o.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},o.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},o.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},o.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new o,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(o.prototype,"subsetOf"),o.prototype.isSubsetOf=function(a){return this._subsetOf===a},o.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},o.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},o.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new o,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},o.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},o.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},o.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},o.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},o.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},o.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},o.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},o.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},o.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,
dataIn:this._transformIn,dataOut:this._transformOut}},o.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},o.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},o.prototype.sort=function(a,b){var c=this,d=n.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(n.get(a,f.path),n.get(b,f.path)):-1===f.value&&(g=c.sortDesc(n.get(a,f.path),n.get(b,f.path))),0!==g)return g;return g}),b},o.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},o.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},o.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},o.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new o("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},o.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},o.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},o.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else c=new i(a,b,this);else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},o.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},o.prototype.lastOp=function(){return this._metrics.list()},o.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},o.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),o.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof o?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new o(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=o},{"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),d.mixin(h.prototype,"Mixin.Events"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.emit("create",b._collectionGroup[a],"collectionGroup",a),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":39}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],8:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(a){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0):!1},f.prototype.document=function(a){var b=this;if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document&&this._document[a]?this._document[a]:(this._document=this._document||{},this._document[a]=new g(a).db(this),b.emit("create",b._document[a],"document",a),this._document[a])}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":5,"./Shared":39}],10:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],11:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,delete this._listeners,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked> All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox"> {^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;
if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":5,"./CollectionGroup":6,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy,this._options),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this._collection.distinct(a),n=[],o=e&&e.chartOptions&&e.chartOptions.xAxis?e.chartOptions.xAxis:{categories:[]};for(k=0;k<m.length;k++){for(f=m[k],g={},g[a]=f,i=[],h=this._collection.find(g,{orderBy:d}),l=0;l<h.length;l++)o.categories?(o.categories.push(h[l][b]),i.push(h[l][c])):i.push([h[l][b],h[l][c]]);if(j={name:f,data:i},e.seriesOptions)for(l in e.seriesOptions)e.seriesOptions.hasOwnProperty(l)&&(j[l]=e.seriesOptions[l]);n.push(j)}return{xAxis:o,series:n}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy,a._options);for(d.xAxis.categories&&a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({string:function(a){return this._highcharts[a]},object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":31,"./Shared":39}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":33,"./Shared":39}],16:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":39}],17:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":30,"./Shared":39}],18:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainWillSend:function(){return Boolean(this._chain)},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":31,"./Serialiser":38}],21:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],22:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":31}],23:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],
q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],24:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],25:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":31}],27:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],28:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),e=d.modules.Core,f=d.modules.OldView,g=f.prototype.init,f.prototype.init=function(){var a=this;this._binds=[],this._renderStart=0,this._renderEnd=0,this._deferQueue={insert:[],update:[],remove:[],upsert:[],_bindInsert:[],_bindUpdate:[],_bindRemove:[],_bindUpsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100,_bindInsert:100,_bindUpdate:100,_bindRemove:100,_bindUpsert:100},this._deferTime={insert:100,update:1,remove:1,upsert:1,_bindInsert:100,_bindUpdate:1,_bindRemove:1,_bindUpsert:1},g.apply(this,arguments),this.on("insert",function(b,c){a._bindEvent("insert",b,c)}),this.on("update",function(b,c){a._bindEvent("update",b,c)}),this.on("remove",function(b,c){a._bindEvent("remove",b,c)}),this.on("change",a._bindChange)},f.prototype.bind=function(a,b){if(!b||!b.template)throw'ForerunnerDB.OldView "'+this.name()+'": Cannot bind data to element, missing options information!';return this._binds[a]=b,this},f.prototype.unBind=function(a){return delete this._binds[a],this},f.prototype.isBound=function(a){return Boolean(this._binds[a])},f.prototype.bindSortDom=function(a,b){var c,d,e,f=window.jQuery(a);for(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting data in DOM...",b),c=0;c<b.length;c++)d=b[c],e=f.find("#"+d[this._primaryKey]),e.length?0===c?(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index 0...",e),f.prepend(e)):(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index "+c+"...",e),e.insertAfter(f.children(":eq("+(c-1)+")"))):this.debug()&&console.log("ForerunnerDB.OldView.Bind: Warning, element for array item not found!",d)},f.prototype.bindRefresh=function(a){var b,c,d=this._binds;a||(a={data:this.find()});for(b in d)d.hasOwnProperty(b)&&(c=d[b],this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting DOM..."),this.bindSortDom(b,a.data),c.afterOperation&&c.afterOperation(),c.refresh&&c.refresh())},f.prototype.bindRender=function(a,b){var c,d,e,f,g,h=this._binds[a],i=window.jQuery(a),j=window.jQuery("<ul></ul>");if(h){for(c=this._data.find(),f=function(a){j.append(a)},g=0;g<c.length;g++)d=c[g],e=h.template(d,f);b?b(a,j.html()):i.append(j.html())}},f.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this._bindEvent(a,f,[])),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b(),this.emit("bindQueueComplete")},f.prototype._bindEvent=function(a,b,c){var d,e,f=this._binds,g=this.find({});for(e in f)if(f.hasOwnProperty(e))switch(d=f[e].reduce?this.find(f[e].reduce.query,f[e].reduce.options):g,a){case"insert":this._bindInsert(e,f[e],b,c,d);break;case"update":this._bindUpdate(e,f[e],b,c,d);break;case"remove":this._bindRemove(e,f[e],b,c,d)}},f.prototype._bindChange=function(a){this.debug()&&console.log("ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...",a),this.bindRefresh(a)},f.prototype._bindInsert=function(a,b,c,d,e){var f,g,h,i,j=window.jQuery(a);for(h=function(a,c,d,e){return function(a){b.insert?b.insert(a,c,d,e):b.prependInsert?j.prepend(a):j.append(a),b.afterInsert&&b.afterInsert(a,c,d,e)}},i=0;i<c.length;i++)f=j.find("#"+c[i][this._primaryKey]),f.length||(g=b.template(c[i],h(f,c[i],d,e)))},f.prototype._bindUpdate=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c){return function(d){b.update?b.update(d,c,e,a.length?"update":"append"):a.length?a.replaceWith(d):b.prependUpdate?i.prepend(d):i.append(d),b.afterUpdate&&b.afterUpdate(d,c,e)}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),b.template(c[h],g(f,c[h]))},f.prototype._bindRemove=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c,d){return function(){b.remove?b.remove(a,c,d):(a.remove(),b.afterRemove&&b.afterRemove(a,c,d))}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),f.length&&(b.beforeRemove?b.beforeRemove(f,c[h],e,g(f,c[h],e)):b.remove?b.remove(f,c[h],e):(f.remove(),b.afterRemove&&b.afterRemove(f,c[h],e)))}},{"./Shared":39}],29:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared");var k=function(a){this.init.apply(this,arguments)};k.prototype.init=function(a){var b=this;this._name=a,this._listeners={},this._query={query:{},options:{}},this._onFromSetData=function(){b._onSetData.apply(b,arguments)},this._onFromInsert=function(){b._onInsert.apply(b,arguments)},this._onFromUpdate=function(){b._onUpdate.apply(b,arguments)},this._onFromRemove=function(){b._onRemove.apply(b,arguments)},this._onFromChange=function(){b.debug()&&console.log("ForerunnerDB.OldView: Received change"),b._onChange.apply(b,arguments)}},d.addModule("OldView",k),f=a("./CollectionGroup"),g=a("./Collection"),h=g.prototype.init,i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.mixin(k.prototype,"Mixin.Events"),k.prototype.drop=function(){return(this._db||this._from)&&this._name?(this.debug()&&console.log("ForerunnerDB.OldView: Dropping view "+this._name),this._state="dropped",this.emit("drop",this),this._db&&this._db._oldViews&&delete this._db._oldViews[this._name],this._from&&this._from._oldViews&&delete this._from._oldViews[this._name],delete this._listeners,!0):!1},k.prototype.debug=function(){return!1},k.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},k.prototype.from=function(a){if(void 0!==a){if("string"==typeof a){if(!this._db.collectionExists(a))throw'ForerunnerDB.OldView "'+this.name()+'": Invalid collection in view.from() call.';a=this._db.collection(a)}return this._from!==a&&(this._from&&this.removeFrom(),this.addFrom(a)),this}return this._from},k.prototype.addFrom=function(a){if(this._from=a,this._from)return this._from.on("setData",this._onFromSetData),this._from.on("change",this._onFromChange),this._from._addOldView(this),this._primaryKey=this._from._primaryKey,this.refresh(),this;throw'ForerunnerDB.OldView "'+this.name()+'": Cannot determine collection type in view.from()'},k.prototype.removeFrom=function(){this._from.off("setData",this._onFromSetData),this._from.off("change",this._onFromChange),this._from._removeOldView(this)},k.prototype.primaryKey=function(){return this._from?this._from.primaryKey():void 0},k.prototype.queryData=function(a,b,c){return void 0!==a&&(this._query.query=a),void 0!==b&&(this._query.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._query},k.prototype.queryAdd=function(a,b,c){var d,e=this._query.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},k.prototype.queryRemove=function(a,b){var c,d=this._query.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()},k.prototype.query=function(a,b){return void 0!==a?(this._query.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.query},k.prototype.queryOptions=function(a,b){return void 0!==a?(this._query.options=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.options},k.prototype.refresh=function(a){if(this._from){var b,c,d,e,f,g,h,i,j=this._data,k=[],l=[],m=[],n=!1;if(this.debug()&&(console.log("ForerunnerDB.OldView: Refreshing view "+this._name),console.log("ForerunnerDB.OldView: Existing data: "+("undefined"!=typeof this._data)),"undefined"!=typeof this._data&&console.log("ForerunnerDB.OldView: Current data rows: "+this._data.find().length)),this._query?(this.debug()&&console.log("ForerunnerDB.OldView: View has query and options, getting subset..."),this._data=this._from.subset(this._query.query,this._query.options)):this._query.options?(this.debug()&&console.log("ForerunnerDB.OldView: View has options, getting subset..."),this._data=this._from.subset({},this._query.options)):(this.debug()&&console.log("ForerunnerDB.OldView: View has no query or options, getting subset..."),this._data=this._from.subset({})),!a&&j)if(this.debug()&&console.log("ForerunnerDB.OldView: Refresh not forced, old data detected..."),d=this._data,j.subsetOf()===d.subsetOf()){for(this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from same collection..."),e=d.find(),b=j.find(),g=d._primaryKey,i=0;i<e.length;i++)h=e[i],f={},f[g]=h[g],c=j.find(f)[0],c?JSON.stringify(c)!==JSON.stringify(h)&&l.push(h):k.push(h);for(i=0;i<b.length;i++)h=b[i],f={},f[g]=h[g],d.find(f)[0]||m.push(h);this.debug()&&(console.log("ForerunnerDB.OldView: Removed "+m.length+" rows"),console.log("ForerunnerDB.OldView: Inserted "+k.length+" rows"),console.log("ForerunnerDB.OldView: Updated "+l.length+" rows")),k.length&&(this._onInsert(k,[]),n=!0),l.length&&(this._onUpdate(l,[]),n=!0),m.length&&(this._onRemove(m,[]),n=!0)}else this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from different collections..."),m=j.find(),m.length&&(this._onRemove(m),n=!0),k=d.find(),k.length&&(this._onInsert(k),n=!0);else this.debug()&&console.log("ForerunnerDB.OldView: Forcing data update",e),this._data=this._from.subset(this._query.query,this._query.options),e=this._data.find(),this.debug()&&console.log("ForerunnerDB.OldView: Emitting change event with data",e),this._onInsert(e,[]);this.debug()&&console.log("ForerunnerDB.OldView: Emitting change"),this.emit("change")}return this},k.prototype.count=function(){return this._data&&this._data._data?this._data._data.length:0},k.prototype.find=function(){return this._data?(this.debug()&&console.log("ForerunnerDB.OldView: Finding data in view collection...",this._data),this._data.find.apply(this._data,arguments)):[]},k.prototype.insert=function(){return this._from?this._from.insert.apply(this._from,arguments):[]},k.prototype.update=function(){return this._from?this._from.update.apply(this._from,arguments):[]},k.prototype.remove=function(){return this._from?this._from.remove.apply(this._from,arguments):[]},k.prototype._onSetData=function(a,b){this.emit("remove",b,[]),this.emit("insert",a,[])},k.prototype._onInsert=function(a,b){this.emit("insert",a,b)},k.prototype._onUpdate=function(a,b){this.emit("update",a,b)},k.prototype._onRemove=function(a,b){this.emit("remove",a,b)},k.prototype._onChange=function(){this.debug()&&console.log("ForerunnerDB.OldView: Refreshing data"),this.refresh()},g.prototype.init=function(){this._oldViews=[],h.apply(this,arguments)},g.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},g.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},f.prototype.init=function(){this._oldViews=[],i.apply(this,arguments)},f.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},f.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},e.prototype.init=function(){this._oldViews={},j.apply(this,arguments)},e.prototype.oldView=function(a){return this._oldViews[a]||this.debug()&&console.log("ForerunnerDB.OldView: Creating view "+a),this._oldViews[a]=this._oldViews[a]||new k(a).db(this),this._oldViews[a]},e.prototype.oldViewExists=function(a){return Boolean(this._oldViews[a])},e.prototype.oldViews=function(){var a,b=[];for(a in this._oldViews)this._oldViews.hasOwnProperty(a)&&b.push({name:a,count:this._oldViews[a].count()});return b},d.finishModule("OldView"),b.exports=k},{"./Collection":5,"./CollectionGroup":6,"./Shared":39}],30:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":33,"./Shared":39}],31:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],32:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){var b=this;return a?a instanceof h?a:this._overview&&this._overview[a]?this._overview[a]:(this._overview=this._overview||{},this._overview[a]=new h(a).db(this),b.emit("create",b._overview[a],"overview",a),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":5,"./Document":9,"./Shared":39}],33:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":39}],34:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),
d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):(d&&(b.remove({}),b.insert(d)),b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,async:41,localforage:77}],35:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":39,pako:78}],36:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":39,"crypto-js":50}],37:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":39}],38:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],39:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.721",modules:{},plugins:{},index:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n=a("./Overload");d=a("./Shared");var o=function(a,b,c){this.init.apply(this,arguments)};d.addModule("View",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,l=d.modules.Path,m=new l,o.prototype.init=function(a,b,c){var d=this;this.sharedPathSolver=m,this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._data=new f(this.name()+"_internal")},o.prototype._handleChainIO=function(a,b){var c,d,e,f,g=a.type;return"setData"!==g&&"insert"!==g&&"update"!==g&&"remove"!==g?!1:(c=Boolean(b._querySettings.options&&b._querySettings.options.$join),d=Boolean(b._querySettings.query),e=void 0!==b._data._transformIn,c||d||e?(f={dataArr:[],removeArr:[]},"insert"===a.type?a.data.dataSet instanceof Array?f.dataArr=a.data.dataSet:f.dataArr=[a.data.dataSet]:"update"===a.type?f.dataArr=a.data.dataSet:"remove"===a.type&&(a.data.dataSet instanceof Array?f.removeArr=a.data.dataSet:f.removeArr=[a.data.dataSet]),f.dataArr instanceof Array||(console.warn("WARNING: dataArr being processed by chain reactor in View class is inconsistent!"),f.dataArr=[]),f.removeArr instanceof Array||(console.warn("WARNING: removeArr being processed by chain reactor in View class is inconsistent!"),f.removeArr=[]),c&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveJoin"),b._handleChainIO_ActiveJoin(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveJoin")),d&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveQuery"),b._handleChainIO_ActiveQuery(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveQuery")),e&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_TransformIn"),b._handleChainIO_TransformIn(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_TransformIn")),f.dataArr.length||f.removeArr.length?(f.pk=b._data.primaryKey(),f.removeArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_RemovePackets"),b._handleChainIO_RemovePackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_RemovePackets")),f.dataArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_UpsertPackets"),b._handleChainIO_UpsertPackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_UpsertPackets")),!0):!0):!1)},o.prototype._handleChainIO_ActiveJoin=function(a,b){var c,d=b.dataArr;c=this.applyJoin(d,this._querySettings.options.$join,{},{}),this.spliceArrayByIndexList(d,c),b.removeArr=b.removeArr.concat(c)},o.prototype._handleChainIO_ActiveQuery=function(a,b){var c,d=this,e=b.dataArr;for(c=e.length-1;c>=0;c--)d._match(e[c],d._querySettings.query,d._querySettings.options,"and",{})||(b.removeArr.push(e[c]),e.splice(c,1))},o.prototype._handleChainIO_TransformIn=function(a,b){var c,d=this,e=b.dataArr,f=b.removeArr,g=d._data._transformIn;for(c=0;c<e.length;c++)e[c]=g(e[c]);for(c=0;c<f.length;c++)f[c]=g(f[c])},o.prototype._handleChainIO_RemovePackets=function(a,b,c){var d,e,f=[],g=c.pk,h=c.removeArr,i={dataSet:h,query:{$or:f}};for(e=0;e<h.length;e++)d={},d[g]=h[e][g],f.push(d);a.chainSend("remove",i)},o.prototype._handleChainIO_UpsertPackets=function(a,b,c){var d,e,f,g=this._data,h=g._primaryIndex,i=g._primaryCrc,j=c.pk,k=c.dataArr,l=[],m=[];for(f=0;f<k.length;f++)d=k[f],h.get(d[j])?i.get(d[j])!==this.hash(d[j])&&m.push(d):l.push(d);if(l.length&&a.chainSend("insert",{dataSet:l}),m.length)for(f=0;f<m.length;f++)d=m[f],e={},e[j]=d[j],a.chainSend("update",{query:e,update:d,dataSet:[d]})},o.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},o.prototype.update=function(){this._from.update.apply(this._from,arguments)},o.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},o.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},o.prototype.find=function(a,b){return this._data.find(a,b)},o.prototype.findOne=function(a,b){return this._data.findOne(a,b)},o.prototype.findById=function(a,b){return this._data.findById(a,b)},o.prototype.findSub=function(a,b,c,d){return this._data.findSub(a,b,c,d)},o.prototype.findSubOne=function(a,b,c,d){return this._data.findSubOne(a,b,c,d)},o.prototype.data=function(){return this._data},o.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a._data,this.debug()&&console.log(this.logIdentifier()+' Using internal data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(this._from,this,function(a){return c._handleChainIO.call(this,a,c)}),this._data.primaryKey(a.primaryKey());var d=a.find(this._querySettings.query,this._querySettings.options);return this._data.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},o.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data: "+a.type),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._data.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._data.setData(j),this.rebuildActiveBucket(this._querySettings.options);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._data.name()+'"'),a.data.dataSet=this.decouple(a.data.dataSet),a.data.dataSet instanceof Array||(a.data.dataSet=[a.data.dataSet]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._data._insertHandle(b[d],e);else e=this._data._data.length,this._data._insertHandle(a.data.dataSet,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._data.name()+'"'),g=this._data.primaryKey(),f=this._data._handleUpdate(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._data._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._data._updateSpliceMove(this._data._data,i,e);break;case"remove":if(this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._data.name()+'"'),this._data.remove(a.data.query,a.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)this._activeBucket.remove(b[d])}},o.prototype._collectionDropped=function(a){a&&delete this._from},o.prototype.ensureIndex=function(){return this._data.ensureIndex.apply(this._data,arguments)},o.prototype.on=function(){return this._data.on.apply(this._data,arguments)},o.prototype.off=function(){return this._data.off.apply(this._data,arguments)},o.prototype.emit=function(){return this._data.emit.apply(this._data,arguments)},o.prototype.deferEmit=function(){return this._data.deferEmit.apply(this._data,arguments)},o.prototype.distinct=function(a,b,c){return this._data.distinct(a,b,c)},o.prototype.primaryKey=function(){return this._data.primaryKey()},o.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._data&&this._data.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._data,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},o.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),(void 0!==a||void 0!==b)&&(void 0===c||c===!0)&&this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this._querySettings},o.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh(),void 0!==e&&this.emit("queryChange",e)},o.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh(),void 0!==d&&this.emit("queryChange",d)}},o.prototype.query=new n({"":function(){return this._querySettings.query},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),(void 0!==a||void 0!==b)&&(void 0===c||c===!0)&&this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this._querySettings}}),o.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},o.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},o.prototype.pageFirst=function(){return this.page(0)},o.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},o.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},o.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),void 0!==a&&this.emit("queryOptionsChange",a),this):this._querySettings.options},o.prototype.rebuildActiveBucket=function(a){if(a){var b=this._data._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._data.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},o.prototype.refresh=function(){var a,b,c,d,e=this;if(this._from&&(this._data.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._data.insert(a),this._data._data.$cursor=a.$cursor,this._data._data.$cursor=a.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(e.__joinChange=e.__joinChange||function(){e._joinChange()},this._joinCollections&&this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).off("immediateChange",e.__joinChange);for(b=this._querySettings.options.$join,this._joinCollections=[],c=0;c<b.length;c++)for(d in b[c])b[c].hasOwnProperty(d)&&this._joinCollections.push(d);if(this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).on("immediateChange",e.__joinChange)}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},o.prototype._joinChange=function(a,b){this.emit("joinChange"),this.refresh()},o.prototype.count=function(){return this._data.count.apply(this._data,arguments)},o.prototype.subset=function(){return this._data.subset.apply(this._data,arguments)},o.prototype.transform=function(a){var b,c;return b=this._data.transform(),this._data.transform(a),c=this._data.transform(),c.enabled&&c.dataIn&&(b.enabled!==c.enabled||b.dataIn!==c.dataIn)&&this.refresh(),c},o.prototype.filter=function(a,b,c){return this._data.filter(a,b,c)},o.prototype.data=function(){return this._data},o.prototype.indexOf=function(){return this._data.indexOf.apply(this._data,arguments)},d.synthesize(o.prototype,"db",function(a){return a&&(this._data.db(a),this.debug(a.debug()),this._data.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new o(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof o?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new o(a).db(this),b.emit("create",b._view[a],"view",a),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=o},{"./ActiveBucket":2,"./Collection":5,"./CollectionGroup":6,"./Overload":31,"./ReactorIO":37,"./Shared":39}],41:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){if(!j.paused&&g<j.concurrency&&j.tasks.length)for(;g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){
K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){q.unshift(a)}function f(a){var b=p(q,a);b>=0&&q.splice(b,1)}function g(){j--,k(q.slice(0),function(a){a()})}c||(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(s,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](q,l))}for(var j,k=N(a[d])?a[d]:[a[d]],q=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,c(a,e)}else l[d]=b,K.setImmediate(g)}),s=k.slice(0,k.length-1),t=s.length;t--;){if(!(j=a[s[t]]))throw new Error("Has inexistant dependency");if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](q,l)):e(i)})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c(null)});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={};b=b||e;var f=r(function(e){var f=e.pop(),g=b.apply(null,e);g in c?K.setImmediate(function(){f.apply(null,c[g])}):g in d?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([r(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:76}],42:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":44}],44:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2;g[h>>>2]|=(j|k)<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":44}],46:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":44}],47:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":44,"./hmac":49,"./sha1":68}],48:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":43,"./core":44}],49:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":44}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":44}],52:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":44}],53:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":43,"./core":44}],54:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":43,"./core":44}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":43,"./core":44}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":43,"./core":44}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":43,"./core":44}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":43,"./core":44}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":43,"./core":44}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":43,"./core":44}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":43,"./core":44}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":43,"./core":44}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({
cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":44,"./hmac":49,"./sha1":68}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":44}],68:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":44}],69:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":44,"./sha256":70}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":44}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":44,"./x64-core":75}],72:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":44,"./x64-core":75}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();
return a}})}(),a})},{"./core":44}],76:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],77:[function(a,b,c){(function(a,d){!function(){var b,c,e,f;!function(){var a={},d={};b=function(b,c,d){a[b]={deps:c,callback:d}},f=e=c=function(b){function e(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(f._eak_seen=a,d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)"exports"===i[l]?k.push(g={}):k.push(c(e(i[l])));var n=j.apply(this,k);return d[b]=g||n}}(),b("promise/all",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to all.");return new b(function(b,c){function d(a){return function(b){f(a,b)}}function f(a,c){h[a]=c,0===--i&&b(h)}var g,h=[],i=a.length;0===i&&b([]);for(var j=0;j<a.length;j++)g=a[j],g&&e(g.then)?g.then(d(j),c):f(j,g)})}var d=a.isArray,e=a.isFunction;b.all=c}),b("promise/asap",["exports"],function(b){"use strict";function c(){return function(){a.nextTick(g)}}function e(){var a=0,b=new k(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function f(){return function(){l.setTimeout(g,1)}}function g(){for(var a=0;a<m.length;a++){var b=m[a],c=b[0],d=b[1];c(d)}m=[]}function h(a,b){var c=m.push([a,b]);1===c&&i()}var i,j="undefined"!=typeof window?window:{},k=j.MutationObserver||j.WebKitMutationObserver,l="undefined"!=typeof d?d:void 0===this?window:this,m=[];i="undefined"!=typeof a&&"[object process]"==={}.toString.call(a)?c():k?e():f(),b.asap=h}),b("promise/config",["exports"],function(a){"use strict";function b(a,b){return 2!==arguments.length?c[a]:void(c[a]=b)}var c={instrument:!1};a.config=c,a.configure=b}),b("promise/polyfill",["./promise","./utils","exports"],function(a,b,c){"use strict";function e(){var a;a="undefined"!=typeof d?d:"undefined"!=typeof window&&window.document?window:self;var b="Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;return new a.Promise(function(a){b=a}),g(b)}();b||(a.Promise=f)}var f=a.Promise,g=b.isFunction;c.polyfill=e}),b("promise/promise",["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],function(a,b,c,d,e,f,g,h){"use strict";function i(a){if(!v(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof i))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],j(a,this)}function j(a,b){function c(a){o(b,a)}function d(a){q(b,a)}try{a(c,d)}catch(e){d(e)}}function k(a,b,c,d){var e,f,g,h,i=v(c);if(i)try{e=c(d),g=!0}catch(j){h=!0,f=j}else e=d,g=!0;n(b,e)||(i&&g?o(b,e):h?q(b,f):a===D?o(b,e):a===E&&q(b,e))}function l(a,b,c,d){var e=a._subscribers,f=e.length;e[f]=b,e[f+D]=c,e[f+E]=d}function m(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],k(b,c,d,f);a._subscribers=null}function n(a,b){var c,d=null;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(u(b)&&(d=b.then,v(d)))return d.call(b,function(d){return c?!0:(c=!0,void(b!==d?o(a,d):p(a,d)))},function(b){return c?!0:(c=!0,void q(a,b))}),!0}catch(e){return c?!0:(q(a,e),!0)}return!1}function o(a,b){a===b?p(a,b):n(a,b)||p(a,b)}function p(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(r,a))}function q(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(s,a))}function r(a){m(a,a._state=D)}function s(a){m(a,a._state=E)}var t=a.config,u=(a.configure,b.objectOrFunction),v=b.isFunction,w=(b.now,c.all),x=d.race,y=e.resolve,z=f.reject,A=g.asap;t.async=A;var B=void 0,C=0,D=1,E=2;i.prototype={constructor:i,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){k(c._state,d,e[c._state-1],c._detail)})}else l(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}},i.all=w,i.race=x,i.resolve=y,i.reject=z,h.Promise=i}),b("promise/race",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to race.");return new b(function(b,c){for(var d,e=0;e<a.length;e++)d=a[e],d&&"function"==typeof d.then?d.then(b,c):b(d)})}var d=a.isArray;b.race=c}),b("promise/reject",["exports"],function(a){"use strict";function b(a){var b=this;return new b(function(b,c){c(a)})}a.reject=b}),b("promise/resolve",["exports"],function(a){"use strict";function b(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=this;return new b(function(b){b(a)})}a.resolve=b}),b("promise/utils",["exports"],function(a){"use strict";function b(a){return c(a)||"object"==typeof a&&null!==a}function c(a){return"function"==typeof a}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}var e=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=b,a.isFunction=c,a.isArray=d,a.now=e}),c("promise/polyfill").polyfill()}(),function(a,d){"object"==typeof c&&"object"==typeof b?b.exports=d():"function"==typeof define&&define.amd?define([],d):"object"==typeof c?c.localforage=d():a.localforage=d()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}b.__esModule=!0,function(){function a(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function e(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(m(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function f(a){for(var b in h)if(h.hasOwnProperty(b)&&h[b]===a)return!0;return!1}var g={},h={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},i=[h.INDEXEDDB,h.WEBSQL,h.LOCALSTORAGE],j=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],k={description:"",driver:i.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},l=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[h.WEBSQL]=!!a.openDatabase,c[h.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function b(a){d(this,b),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,a),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return b.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},b.prototype.defineDriver=function(a,b,c){var d=new Promise(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),h=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(f(a._driver))return void c(h);for(var i=j.concat("_initStorage"),k=0;k<i.length;k++){var m=i[k];if(!m||!a[m]||"function"!=typeof a[m])return void c(e)}var n=Promise.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():Promise.resolve(!!a._support)),n.then(function(c){l[d]=c,g[d]=a,b()},c)}catch(o){c(o)}});return d.then(b,c),d},b.prototype.driver=function(){return this._driver||null},b.prototype.getDriver=function(a,b,d){var e=this,h=function(){if(f(a))switch(a){case e.INDEXEDDB:return new Promise(function(a,b){a(c(1))});case e.LOCALSTORAGE:return new Promise(function(a,b){a(c(2))});case e.WEBSQL:return new Promise(function(a,b){a(c(4))})}else if(g[a])return Promise.resolve(g[a]);return Promise.reject(new Error("Driver not found."))}();return h.then(b,d),h},b.prototype.getSerializer=function(a){var b=new Promise(function(a,b){a(c(3))});return a&&"function"==typeof a&&b.then(function(b){a(b)}),b},b.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return c.then(a,a),c},b.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=Promise.reject(g),f._driverSet}var c=0;return b()}}var f=this;m(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return Promise.resolve()}):Promise.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=Promise.reject(a),f._driverSet}),this._driverSet.then(b,c),this._driverSet},b.prototype.supports=function(a){return!!l[a]},b.prototype._extend=function(a){e(this,a)},b.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},b.prototype._wrapLibraryMethodsWithReady=function(){for(var b=0;b<j.length;b++)a(this,j[b])},b.prototype.createInstance=function(a){return new b(a)},b}(),o=new n;b["default"]=o}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function d(a){return new Promise(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function e(b){return new Promise(function(c,e){var f=a([""],{type:"image/png"}),g=b.transaction([B],"readwrite");g.objectStore(B).put(f,"key"),g.oncomplete=function(){var a=b.transaction([B],"readwrite"),f=a.objectStore(B).get("key");f.onerror=e,f.onsuccess=function(a){var b=a.target.result,e=URL.createObjectURL(b);d(e).then(function(a){c(!(!a||"image/png"!==a.type))},function(){c(!1)}).then(function(){URL.revokeObjectURL(e)})}}})["catch"](function(){return!1})}function f(a){return"boolean"==typeof z?Promise.resolve(z):e(a).then(function(a){return z=a})}function g(a){return new Promise(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function h(b){var d=c(atob(b.data));return a([d],{type:b.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];A||(A={});var f=A[d.name];f||(f={forages:[],db:null},A[d.name]=f),f.forages.push(this);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==this&&g.push(i.ready()["catch"](b))}var j=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,k(d)}).then(function(a){return d.db=a,n(d,c._defaultConfig.version)?l(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b in j){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function k(a){return m(a,!1)}function l(a){return m(a,!0)}function m(a,b){return new Promise(function(c,d){if(a.db){if(!b)return c(a.db);a.db.close()}var e=[a.name];b&&e.push(a.version);var f=y.open.apply(y,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(B)}catch(d){if("ConstraintError"!==d.name)throw d;x.console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result)}})}function n(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&x.console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function o(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),i(a)&&(a=h(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function p(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),j=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;i(d)&&(d=h(d));var e=a(d,c.key,j++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function q(a,b,c){var d=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){var h;d.ready().then(function(){return h=d._dbInfo,f(h.db)}).then(function(a){return!a&&b instanceof Blob?g(b):b}).then(function(b){var d=h.db.transaction(h.storeName,"readwrite"),f=d.objectStore(h.storeName);null===b&&(b=void 0);var g=f.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=g.error?g.error:g.transaction.error;e(a)}})["catch"](e)});return w(e,c),e}function r(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return w(d,b),d}function s(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return w(c,a),c}function t(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function u(a,b){var c=this,d=new Promise(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return w(d,b),d}function v(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function w(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var x=this,y=y||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(y){var z,A,B="local-forage-detect-blob-support",C={_driver:"asyncStorage",_initStorage:j,iterate:p,getItem:o,setItem:q,removeItem:r,clear:s,length:t,key:u,keys:v};b["default"]=C}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={};if(a)for(var e in a)d[e]=a[e];return d.keyPrefix=d.name+"/",d.storeName!==b._defaultConfig.storeName&&(d.keyPrefix+=d.storeName+"/"),b._dbInfo=d,new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,Promise.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=n.length-1;c>=0;c--){var d=n.key(c);0===d.indexOf(a)&&n.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=n.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=n.length,g=1,h=0;f>h;h++){var i=n.key(h);if(0===i.indexOf(d)){var j=n.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=n.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=n.length,d=[],e=0;c>e;e++)0===n.key(e).indexOf(a.keyPrefix)&&d.push(n.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;n.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new Promise(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{n.setItem(g.keyPrefix+a,b),e(c)}catch(h){("QuotaExceededError"===h.name||"NS_ERROR_DOM_QUOTA_REACHED"===h.name)&&f(h),f(h)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;n=this.localStorage}catch(o){return}var p={_driver:"localStorageWrapper",_initStorage:a,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};b["default"]=p}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=j;a instanceof ArrayBuffer?(d=a,e+=l):(d=a.buffer,"[object Int8Array]"===c?e+=n:"[object Uint8Array]"===c?e+=o:"[object Uint8ClampedArray]"===c?e+=p:"[object Int16Array]"===c?e+=q:"[object Uint16Array]"===c?e+=s:"[object Int32Array]"===c?e+=r:"[object Uint32Array]"===c?e+=t:"[object Float32Array]"===c?e+=u:"[object Float64Array]"===c?e+=v:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var c=h+a.type+"~"+f(this.result);b(j+m+c)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(b){if(b.substring(0,k)!==j)return JSON.parse(b);var c,d=b.substring(w),f=b.substring(k,w);if(f===m&&i.test(d)){var g=d.match(i);c=g[1],d=d.substring(g[0].length)}var h=e(d);switch(f){case l:return h;case m:return a([h],{type:c});case n:return new Int8Array(h);case o:return new Uint8Array(h);case p:return new Uint8ClampedArray(h);case q:return new Int16Array(h);case s:return new Uint16Array(h);case r:return new Int32Array(h);case t:return new Uint32Array(h);case u:return new Float32Array(h);case v:return new Float64Array(h);default:throw new Error("Unkown type: "+f)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="~~local_forage_type~",i=/^~~local_forage_type~([^~]+)~/,j="__lfsc__:",k=j.length,l="arbf",m="blob",n="si08",o="ui08",p="uic8",q="si16",r="si32",s="ur16",t="ui32",u="fl32",v="fl64",w=k+l.length,x=this,y={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};b["default"]=y}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={db:null};if(a)for(var e in a)d[e]="string"!=typeof a[e]?a[e].toString():a[e];var f=new Promise(function(c,e){try{d.db=n(d.name,String(d.version),d.description,d.size)}catch(f){return b.setDriver(b.LOCALSTORAGE).then(function(){return b._initStorage(a)}).then(c)["catch"](e)}d.db.transaction(function(a){a.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,c()},function(a,b){e(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=this.openDatabase;if(n){var o={_driver:"webSQLStorage",_initStorage:a,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};b["default"]=o}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:76}],78:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c===i.Z_BUF_ERROR&&o===!0&&(c=i.Z_OK,o=!1),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0;
},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],82:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":81}],83:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],84:[function(a,b,c){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],85:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],86:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ha-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ha)););}while(a.lookahead<ja&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ha-1)/ha),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],88:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],89:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;
for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":81}],91:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],92:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],aa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":81}],93:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[1]); |
node_modules/react-bootstrap/es/TabPane.js | geng890518/editor-ui | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import elementType from 'react-prop-types/lib/elementType';
import warning from 'warning';
import { bsClass, getClassSet, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
import Fade from './Fade';
var propTypes = {
/**
* Uniquely identify the `<TabPane>` among its siblings.
*/
eventKey: PropTypes.any,
/**
* Use animation when showing or hiding `<TabPane>`s. Use `false` to disable,
* `true` to enable the default `<Fade>` animation or any `<Transition>`
* component.
*/
animation: PropTypes.oneOfType([PropTypes.bool, elementType]),
/** @private **/
id: PropTypes.string,
/** @private **/
'aria-labelledby': PropTypes.string,
/**
* If not explicitly specified and rendered in the context of a
* `<TabContent>`, the `bsClass` of the `<TabContent>` suffixed by `-pane`.
* If otherwise not explicitly specified, `tab-pane`.
*/
bsClass: PropTypes.string,
/**
* Transition onEnter callback when animation is not `false`
*/
onEnter: PropTypes.func,
/**
* Transition onEntering callback when animation is not `false`
*/
onEntering: PropTypes.func,
/**
* Transition onEntered callback when animation is not `false`
*/
onEntered: PropTypes.func,
/**
* Transition onExit callback when animation is not `false`
*/
onExit: PropTypes.func,
/**
* Transition onExiting callback when animation is not `false`
*/
onExiting: PropTypes.func,
/**
* Transition onExited callback when animation is not `false`
*/
onExited: PropTypes.func,
/**
* Wait until the first "enter" transition to mount the tab (add it to the DOM)
*/
mountOnEnter: PropTypes.bool,
/**
* Unmount the tab (remove it from the DOM) when it is no longer visible
*/
unmountOnExit: PropTypes.bool
};
var contextTypes = {
$bs_tabContainer: PropTypes.shape({
getTabId: PropTypes.func,
getPaneId: PropTypes.func
}),
$bs_tabContent: PropTypes.shape({
bsClass: PropTypes.string,
animation: PropTypes.oneOfType([PropTypes.bool, elementType]),
activeKey: PropTypes.any,
mountOnEnter: PropTypes.bool,
unmountOnExit: PropTypes.bool,
onPaneEnter: PropTypes.func.isRequired,
onPaneExited: PropTypes.func.isRequired,
exiting: PropTypes.bool.isRequired
})
};
/**
* We override the `<TabContainer>` context so `<Nav>`s in `<TabPane>`s don't
* conflict with the top level one.
*/
var childContextTypes = {
$bs_tabContainer: PropTypes.oneOf([null])
};
var TabPane = function (_React$Component) {
_inherits(TabPane, _React$Component);
function TabPane(props, context) {
_classCallCheck(this, TabPane);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleEnter = _this.handleEnter.bind(_this);
_this.handleExited = _this.handleExited.bind(_this);
_this['in'] = false;
return _this;
}
TabPane.prototype.getChildContext = function getChildContext() {
return {
$bs_tabContainer: null
};
};
TabPane.prototype.componentDidMount = function componentDidMount() {
if (this.shouldBeIn()) {
// In lieu of the action event firing.
this.handleEnter();
}
};
TabPane.prototype.componentDidUpdate = function componentDidUpdate() {
if (this['in']) {
if (!this.shouldBeIn()) {
// We shouldn't be active any more. Notify the parent.
this.handleExited();
}
} else if (this.shouldBeIn()) {
// We are the active child. Notify the parent.
this.handleEnter();
}
};
TabPane.prototype.componentWillUnmount = function componentWillUnmount() {
if (this['in']) {
// In lieu of the action event firing.
this.handleExited();
}
};
TabPane.prototype.handleEnter = function handleEnter() {
var tabContent = this.context.$bs_tabContent;
if (!tabContent) {
return;
}
this['in'] = tabContent.onPaneEnter(this, this.props.eventKey);
};
TabPane.prototype.handleExited = function handleExited() {
var tabContent = this.context.$bs_tabContent;
if (!tabContent) {
return;
}
tabContent.onPaneExited(this);
this['in'] = false;
};
TabPane.prototype.getAnimation = function getAnimation() {
if (this.props.animation != null) {
return this.props.animation;
}
var tabContent = this.context.$bs_tabContent;
return tabContent && tabContent.animation;
};
TabPane.prototype.isActive = function isActive() {
var tabContent = this.context.$bs_tabContent;
var activeKey = tabContent && tabContent.activeKey;
return this.props.eventKey === activeKey;
};
TabPane.prototype.shouldBeIn = function shouldBeIn() {
return this.getAnimation() && this.isActive();
};
TabPane.prototype.render = function render() {
var _props = this.props,
eventKey = _props.eventKey,
className = _props.className,
onEnter = _props.onEnter,
onEntering = _props.onEntering,
onEntered = _props.onEntered,
onExit = _props.onExit,
onExiting = _props.onExiting,
onExited = _props.onExited,
propsMountOnEnter = _props.mountOnEnter,
propsUnmountOnExit = _props.unmountOnExit,
props = _objectWithoutProperties(_props, ['eventKey', 'className', 'onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'onExited', 'mountOnEnter', 'unmountOnExit']);
var _context = this.context,
tabContent = _context.$bs_tabContent,
tabContainer = _context.$bs_tabContainer;
var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['animation']),
bsProps = _splitBsPropsAndOmit[0],
elementProps = _splitBsPropsAndOmit[1];
var active = this.isActive();
var animation = this.getAnimation();
var mountOnEnter = propsMountOnEnter != null ? propsMountOnEnter : tabContent && tabContent.mountOnEnter;
var unmountOnExit = propsUnmountOnExit != null ? propsUnmountOnExit : tabContent && tabContent.unmountOnExit;
if (!active && !animation && unmountOnExit) {
return null;
}
var Transition = animation === true ? Fade : animation || null;
if (tabContent) {
bsProps.bsClass = prefix(tabContent, 'pane');
}
var classes = _extends({}, getClassSet(bsProps), {
active: active
});
if (tabContainer) {
process.env.NODE_ENV !== 'production' ? warning(!elementProps.id && !elementProps['aria-labelledby'], 'In the context of a `<TabContainer>`, `<TabPanes>` are given ' + 'generated `id` and `aria-labelledby` attributes for the sake of ' + 'proper component accessibility. Any provided ones will be ignored. ' + 'To control these attributes directly provide a `generateChildId` ' + 'prop to the parent `<TabContainer>`.') : void 0;
elementProps.id = tabContainer.getPaneId(eventKey);
elementProps['aria-labelledby'] = tabContainer.getTabId(eventKey);
}
var pane = React.createElement('div', _extends({}, elementProps, {
role: 'tabpanel',
'aria-hidden': !active,
className: classNames(className, classes)
}));
if (Transition) {
var exiting = tabContent && tabContent.exiting;
return React.createElement(
Transition,
{
'in': active && !exiting,
onEnter: createChainedFunction(this.handleEnter, onEnter),
onEntering: onEntering,
onEntered: onEntered,
onExit: onExit,
onExiting: onExiting,
onExited: createChainedFunction(this.handleExited, onExited),
mountOnEnter: mountOnEnter,
unmountOnExit: unmountOnExit
},
pane
);
}
return pane;
};
return TabPane;
}(React.Component);
TabPane.propTypes = propTypes;
TabPane.contextTypes = contextTypes;
TabPane.childContextTypes = childContextTypes;
export default bsClass('tab-pane', TabPane); |
src/index.js | surabhig412/digital-clock | import React from 'react';
import ReactDom from 'react-dom';
import App from './App'
import './index.css'
ReactDom.render(<App />, document.getElementById('root'));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.