code
stringlengths 2
1.05M
|
|---|
import eq from './eq.js';
/**
* 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)) ||
(typeof key == 'number' && value === undefined && !(key in object))) {
object[key] = value;
}
}
export default assignMergeValue;
|
module.exports = function method(matchMethod) {
if (typeof matchMethod === 'string') {
matchMethod = [ matchMethod ]
}
if (!matchMethod) {
matchMethod = [ 'GET' ]
}
return function method(req, res, next) {
var notMatches = !~matchMethod.indexOf(req.method)
next(null, notMatches)
}
}
|
import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
import deprecationWarning from './utils/deprecationWarning';
const CollapsibleMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState() {
const defaultExpanded = this.props.defaultExpanded != null ?
this.props.defaultExpanded : !!this.props.expanded;
return {
expanded: defaultExpanded,
collapsing: false
};
},
componentWillMount() {
deprecationWarning('CollapsibleMixin', 'Collapse Component');
},
componentWillUpdate(nextProps, nextState) {
let willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded;
if (willExpanded === this.isExpanded()) {
return;
}
// if the expanded state is being toggled, ensure node has a dimension value
// this is needed for the animation to work and needs to be set before
// the collapsing class is applied (after collapsing is applied the in class
// is removed and the node's dimension will be wrong)
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = '0';
if (!willExpanded) {
value = this.getCollapsibleDimensionValue();
}
node.style[dimension] = value + 'px';
this._afterWillUpdate();
},
componentDidUpdate(prevProps, prevState) {
// check if expanded is being toggled; if so, set collapsing
this._checkToggleCollapsing(prevProps, prevState);
// check if collapsing was turned on; if so, start animation
this._checkStartAnimation();
},
// helps enable test stubs
_afterWillUpdate() {
},
_checkStartAnimation() {
if (!this.state.collapsing) {
return;
}
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = this.getCollapsibleDimensionValue();
// setting the dimension here starts the transition animation
let result;
if (this.isExpanded()) {
result = value + 'px';
} else {
result = '0px';
}
node.style[dimension] = result;
},
_checkToggleCollapsing(prevProps, prevState) {
let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded;
let isExpanded = this.isExpanded();
if (wasExpanded !== isExpanded) {
if (wasExpanded) {
this._handleCollapse();
} else {
this._handleExpand();
}
}
},
_handleExpand() {
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let complete = () => {
this._removeEndEventListener(node, complete);
// remove dimension value - this ensures the collapsible item can grow
// in dimension after initial display (such as an image loading)
node.style[dimension] = '';
this.setState({
collapsing:false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
_handleCollapse() {
let node = this.getCollapsibleDOMNode();
let complete = () => {
this._removeEndEventListener(node, complete);
this.setState({
collapsing: false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
// helps enable test stubs
_addEndEventListener(node, complete) {
TransitionEvents.addEndEventListener(node, complete);
},
// helps enable test stubs
_removeEndEventListener(node, complete) {
TransitionEvents.removeEndEventListener(node, complete);
},
dimension() {
return (typeof this.getCollapsibleDimension === 'function') ?
this.getCollapsibleDimension() :
'height';
},
isExpanded() {
return this.props.expanded != null ? this.props.expanded : this.state.expanded;
},
getCollapsibleClassSet(className) {
let classes = {};
if (typeof className === 'string') {
className.split(' ').forEach(subClasses => {
if (subClasses) {
classes[subClasses] = true;
}
});
}
classes.collapsing = this.state.collapsing;
classes.collapse = !this.state.collapsing;
classes.in = this.isExpanded() && !this.state.collapsing;
return classes;
}
};
export default CollapsibleMixin;
|
import React, { PropTypes, Component } from 'react';
import { DropTarget } from 'react-dnd';
const style = {
height: '12rem',
width: '12rem',
marginRight: '1.5rem',
marginBottom: '1.5rem',
color: 'white',
padding: '1rem',
textAlign: 'center',
fontSize: '1rem',
lineHeight: 'normal',
float: 'left'
};
const dustbinTarget = {
drop(props, monitor) {
props.onDrop(monitor.getItem());
}
};
@DropTarget(props => props.accepts, dustbinTarget, (connect, monitor) => ({
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop()
}))
export default class Dustbin extends Component {
static propTypes = {
connectDropTarget: PropTypes.func.isRequired,
isOver: PropTypes.bool.isRequired,
canDrop: PropTypes.bool.isRequired,
accepts: PropTypes.arrayOf(PropTypes.string).isRequired,
lastDroppedItem: PropTypes.object,
onDrop: PropTypes.func.isRequired
};
render() {
const { accepts, isOver, canDrop, connectDropTarget, lastDroppedItem } = this.props;
const isActive = isOver && canDrop;
let backgroundColor = '#222';
if (isActive) {
backgroundColor = 'darkgreen';
} else if (canDrop) {
backgroundColor = 'darkkhaki';
}
return connectDropTarget(
<div style={{ ...style, backgroundColor }}>
{isActive ?
'Release to drop' :
'This dustbin accepts: ' + accepts.join(', ')
}
{lastDroppedItem &&
<p>Last dropped: {JSON.stringify(lastDroppedItem)}</p>
}
</div>
);
}
}
|
/*
AngularJS v1.6.7
(c) 2010-2017 Google, Inc. http://angularjs.org
License: MIT
*/
(function(U,a){'use strict';function L(m,f){f=f||{};a.forEach(f,function(a,d){delete f[d]});for(var d in m)!m.hasOwnProperty(d)||"$"===d.charAt(0)&&"$"===d.charAt(1)||(f[d]=m[d]);return f}var B=a.$$minErr("$resource"),Q=/^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;a.module("ngResource",["ng"]).info({angularVersion:"1.6.7"}).provider("$resource",function(){var m=/^https?:\/\/\[[^\]]*][^/]*/,f=this;this.defaults={stripTrailingSlashes:!0,cancellable:!1,actions:{get:{method:"GET"},save:{method:"POST"},query:{method:"GET",
isArray:!0},remove:{method:"DELETE"},"delete":{method:"DELETE"}}};this.$get=["$http","$log","$q","$timeout",function(d,P,F,M){function C(a,d){this.template=a;this.defaults=n({},f.defaults,d);this.urlParams={}}var D=a.noop,r=a.forEach,n=a.extend,R=a.copy,N=a.isArray,w=a.isDefined,x=a.isFunction,S=a.isNumber,y=a.$$encodeUriQuery,T=a.$$encodeUriSegment;C.prototype={setUrlParams:function(a,d,f){var g=this,c=f||g.template,s,h,n="",b=g.urlParams=Object.create(null);r(c.split(/\W/),function(a){if("hasOwnProperty"===
a)throw B("badname");!/^\d+$/.test(a)&&a&&(new RegExp("(^|[^\\\\]):"+a+"(\\W|$)")).test(c)&&(b[a]={isQueryParamValue:(new RegExp("\\?.*=:"+a+"(?:\\W|$)")).test(c)})});c=c.replace(/\\:/g,":");c=c.replace(m,function(b){n=b;return""});d=d||{};r(g.urlParams,function(b,a){s=d.hasOwnProperty(a)?d[a]:g.defaults[a];w(s)&&null!==s?(h=b.isQueryParamValue?y(s,!0):T(s),c=c.replace(new RegExp(":"+a+"(\\W|$)","g"),function(b,a){return h+a})):c=c.replace(new RegExp("(/?):"+a+"(\\W|$)","g"),function(a,b,e){return"/"===
e.charAt(0)?e:b+e})});g.defaults.stripTrailingSlashes&&(c=c.replace(/\/+$/,"")||"/");c=c.replace(/\/\.(?=\w+($|\?))/,".");a.url=n+c.replace(/\/(\\|%5C)\./,"/.");r(d,function(b,c){g.urlParams[c]||(a.params=a.params||{},a.params[c]=b)})}};return function(m,y,z,g){function c(b,c){var d={};c=n({},y,c);r(c,function(c,f){x(c)&&(c=c(b));var e;if(c&&c.charAt&&"@"===c.charAt(0)){e=b;var k=c.substr(1);if(null==k||""===k||"hasOwnProperty"===k||!Q.test("."+k))throw B("badmember",k);for(var k=k.split("."),h=0,
n=k.length;h<n&&a.isDefined(e);h++){var g=k[h];e=null!==e?e[g]:void 0}}else e=c;d[f]=e});return d}function s(b){return b.resource}function h(b){L(b||{},this)}var O=new C(m,g);z=n({},f.defaults.actions,z);h.prototype.toJSON=function(){var b=n({},this);delete b.$promise;delete b.$resolved;delete b.$cancelRequest;return b};r(z,function(b,a){var f=!0===b.hasBody||!1!==b.hasBody&&/^(POST|PUT|PATCH)$/i.test(b.method),g=b.timeout,m=w(b.cancellable)?b.cancellable:O.defaults.cancellable;g&&!S(g)&&(P.debug("ngResource:\n Only numeric values are allowed as `timeout`.\n Promises are not supported in $resource, because the same value would be used for multiple requests. If you are looking for a way to cancel requests, you should use the `cancellable` option."),
delete b.timeout,g=null);h[a]=function(e,k,G,y){function z(a){p.catch(D);null!==t&&t.resolve(a)}var H={},u,v,A;switch(arguments.length){case 4:A=y,v=G;case 3:case 2:if(x(k)){if(x(e)){v=e;A=k;break}v=k;A=G}else{H=e;u=k;v=G;break}case 1:x(e)?v=e:f?u=e:H=e;break;case 0:break;default:throw B("badargs",arguments.length);}var E=this instanceof h,l=E?u:b.isArray?[]:new h(u),q={},C=b.interceptor&&b.interceptor.response||s,w=b.interceptor&&b.interceptor.responseError||void 0,I=!!A,J=!!w,t,K;r(b,function(a,
b){switch(b){default:q[b]=R(a);case "params":case "isArray":case "interceptor":case "cancellable":}});!E&&m&&(t=F.defer(),q.timeout=t.promise,g&&(K=M(t.resolve,g)));f&&(q.data=u);O.setUrlParams(q,n({},c(u,b.params||{}),H),b.url);var p=d(q).then(function(c){var e=c.data;if(e){if(N(e)!==!!b.isArray)throw B("badcfg",a,b.isArray?"array":"object",N(e)?"array":"object",q.method,q.url);if(b.isArray)l.length=0,r(e,function(a){"object"===typeof a?l.push(new h(a)):l.push(a)});else{var d=l.$promise;L(e,l);l.$promise=
d}}c.resource=l;return c},function(a){a.resource=l;return F.reject(a)}),p=p["finally"](function(){l.$resolved=!0;!E&&m&&(l.$cancelRequest=D,M.cancel(K),t=K=q.timeout=null)}),p=p.then(function(a){var b=C(a);(v||D)(b,a.headers,a.status,a.statusText);return b},I||J?function(a){I&&!J&&p.catch(D);I&&A(a);return J?w(a):F.reject(a)}:void 0);return E?p:(l.$promise=p,l.$resolved=!1,m&&(l.$cancelRequest=z),l)};h.prototype["$"+a]=function(b,c,d){x(b)&&(d=c,c=b,b={});b=h[a].call(this,b,this,c,d);return b.$promise||
b}});return h}}]})})(window,window.angular);
//# sourceMappingURL=angular-resource.min.js.map
|
/**
* Language Generator
*/
const fs = require('fs');
const exec = require('child_process').exec;
function languageIsSupported(language) {
try {
fs.accessSync(`app/translations/${language}.json`, fs.F_OK);
return true;
} catch (e) {
return false;
}
}
module.exports = {
description: 'Add a language',
prompts: [{
type: 'input',
name: 'language',
message: 'What is the language you want to add i18n support for (e.g. "fr", "de")?',
default: 'fr',
validate: (value) => {
if ((/.+/).test(value) && value.length === 2) {
return languageIsSupported(value) ? `The language "${value}" is already supported.` : true;
}
return '2 character language specifier is required';
},
}],
actions: () => {
const actions = [];
actions.push({
type: 'modify',
path: '../../app/i18n.js',
pattern: /('react-intl\/locale-data\/[a-z]+';\n)(?!.*'react-intl\/locale-data\/[a-z]+';)/g,
templateFile: './language/intl-locale-data.hbs',
});
actions.push({
type: 'modify',
path: '../../app/i18n.js',
pattern: /(\s+'[a-z]+',\n)(?!.*\s+'[a-z]+',)/g,
templateFile: './language/app-locale.hbs',
});
actions.push({
type: 'modify',
path: '../../app/i18n.js',
pattern: /(from\s'.\/translations\/[a-z]+.json';\n)(?!.*from\s'.\/translations\/[a-z]+.json';)/g,
templateFile: './language/translation-messages.hbs',
});
actions.push({
type: 'modify',
path: '../../app/i18n.js',
pattern: /(addLocaleData\([a-z]+LocaleData\);\n)(?!.*addLocaleData\([a-z]+LocaleData\);)/g,
templateFile: './language/add-locale-data.hbs',
});
actions.push({
type: 'modify',
path: '../../app/i18n.js',
pattern: /([a-z]+:\sformatTranslationMessages\('[a-z]+',\s[a-z]+TranslationMessages\),\n)(?!.*[a-z]+:\sformatTranslationMessages\('[a-z]+',\s[a-z]+TranslationMessages\),)/g,
templateFile: './language/format-translation-messages.hbs',
});
actions.push({
type: 'add',
path: '../../app/translations/{{language}}.json',
templateFile: './language/translations-json.hbs',
abortOnFail: true,
});
actions.push({
type: 'modify',
path: '../../app/app.js',
pattern: /(import\('intl\/locale-data\/jsonp\/[a-z]+\.js'\),\n)(?!.*import\('intl\/locale-data\/jsonp\/[a-z]+\.js'\),)/g,
templateFile: './language/polyfill-intl-locale.hbs',
});
actions.push(
() => {
const cmd = 'npm run extract-intl';
exec(cmd, (err, result, stderr) => {
if (err || stderr) {
throw err || stderr;
}
process.stdout.write(result);
});
return 'modify translation messages';
}
);
return actions;
},
};
|
/*!
* Module dependencies.
*/
var EmbeddedDocument = require('./embedded');
var Document = require('../document');
var ObjectId = require('./objectid');
var utils = require('../utils');
var isMongooseObject = utils.isMongooseObject;
/**
* Mongoose Array constructor.
*
* ####NOTE:
*
* _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._
*
* @param {Array} values
* @param {String} path
* @param {Document} doc parent document
* @api private
* @inherits Array
* @see http://bit.ly/f6CnZU
*/
function MongooseArray (values, path, doc) {
var arr = [];
arr.push.apply(arr, values);
utils.decorate( arr, MongooseArray.mixin );
arr.isMongooseArray = true;
arr._atomics = {};
arr.validators = [];
arr._path = path;
if (doc) {
arr._parent = doc;
arr._schema = doc.schema.path(path);
}
return arr;
}
MongooseArray.mixin = {
/**
* Stores a queue of atomic operations to perform
*
* @property _atomics
* @api private
*/
_atomics: undefined,
/**
* Parent owner document
*
* @property _parent
* @api private
*/
_parent: undefined,
/**
* Casts a member based on this arrays schema.
*
* @param {any} value
* @return value the casted value
* @method _cast
* @api private
*/
_cast: function (value) {
var owner = this._owner;
var populated = false;
var Model;
if (this._parent) {
// if a populated array, we must cast to the same model
// instance as specified in the original query.
if (!owner) {
owner = this._owner = this._parent.ownerDocument
? this._parent.ownerDocument()
: this._parent;
}
populated = owner.populated(this._path, true);
}
if (populated && null != value) {
// cast to the populated Models schema
Model = populated.options.model;
// only objects are permitted so we can safely assume that
// non-objects are to be interpreted as _id
if (Buffer.isBuffer(value) ||
value instanceof ObjectId || !utils.isObject(value)) {
value = { _id: value };
}
// gh-2399
// we should cast model only when it's not a discriminator
var isDisc = value.schema && value.schema.discriminatorMapping &&
value.schema.discriminatorMapping.key !== undefined;
if (!isDisc) {
value = new Model(value);
}
return this._schema.caster.cast(value, this._parent, true)
}
return this._schema.caster.cast(value, this._parent, false)
},
/**
* Marks this array as modified.
*
* If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)
*
* @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array
* @param {String} embeddedPath the path which changed in the embeddedDoc
* @method _markModified
* @api private
*/
_markModified: function (elem, embeddedPath) {
var parent = this._parent
, dirtyPath;
if (parent) {
dirtyPath = this._path;
if (arguments.length) {
if (null != embeddedPath) {
// an embedded doc bubbled up the change
dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath;
} else {
// directly set an index
dirtyPath = dirtyPath + '.' + elem;
}
}
parent.markModified(dirtyPath);
}
return this;
},
/**
* Register an atomic operation with the parent.
*
* @param {Array} op operation
* @param {any} val
* @method _registerAtomic
* @api private
*/
_registerAtomic: function (op, val) {
if ('$set' == op) {
// $set takes precedence over all other ops.
// mark entire array modified.
this._atomics = { $set: val };
return this;
}
var atomics = this._atomics;
// reset pop/shift after save
if ('$pop' == op && !('$pop' in atomics)) {
var self = this;
this._parent.once('save', function () {
self._popped = self._shifted = null;
});
}
// check for impossible $atomic combos (Mongo denies more than one
// $atomic op on a single path
if (this._atomics.$set ||
Object.keys(atomics).length && !(op in atomics)) {
// a different op was previously registered.
// save the entire thing.
this._atomics = { $set: this };
return this;
}
if (op === '$pullAll' || op === '$pushAll' || op === '$addToSet') {
atomics[op] || (atomics[op] = []);
atomics[op] = atomics[op].concat(val);
} else if (op === '$pullDocs') {
var pullOp = atomics['$pull'] || (atomics['$pull'] = {})
, selector = pullOp['_id'] || (pullOp['_id'] = {'$in' : [] });
selector['$in'] = selector['$in'].concat(val);
} else {
atomics[op] = val;
}
return this;
},
/**
* Depopulates stored atomic operation values as necessary for direct insertion to MongoDB.
*
* If no atomics exist, we return all array values after conversion.
*
* @return {Array}
* @method $__getAtomics
* @memberOf MongooseArray
* @api private
*/
$__getAtomics: function () {
var ret = [];
var keys = Object.keys(this._atomics);
var i = keys.length;
if (0 === i) {
ret[0] = ['$set', this.toObject({ depopulate: 1 })];
return ret;
}
while (i--) {
var op = keys[i];
var val = this._atomics[op];
// the atomic values which are arrays are not MongooseArrays. we
// need to convert their elements as if they were MongooseArrays
// to handle populated arrays versus DocumentArrays properly.
if (isMongooseObject(val)) {
val = val.toObject({ depopulate: 1 });
} else if (Array.isArray(val)) {
val = this.toObject.call(val, { depopulate: 1 });
} else if (val.valueOf) {
val = val.valueOf();
}
if ('$addToSet' == op) {
val = { $each: val }
}
ret.push([op, val]);
}
return ret;
},
/**
* Returns the number of pending atomic operations to send to the db for this array.
*
* @api private
* @return {Number}
* @method hasAtomics
*/
hasAtomics: function hasAtomics () {
if (!(this._atomics && 'Object' === this._atomics.constructor.name)) {
return 0;
}
return Object.keys(this._atomics).length;
},
/**
* Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
*
* @param {Object} [args...]
* @api public
* @method push
*/
push: function () {
var values = [].map.call(arguments, this._cast, this)
, ret = [].push.apply(this, values);
// $pushAll might be fibbed (could be $push). But it makes it easier to
// handle what could have been $push, $pushAll combos
this._registerAtomic('$pushAll', values);
this._markModified();
return ret;
},
/**
* Pushes items to the array non-atomically.
*
* ####NOTE:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @param {any} [args...]
* @api public
* @method nonAtomicPush
*/
nonAtomicPush: function () {
var values = [].map.call(arguments, this._cast, this)
, ret = [].push.apply(this, values);
this._registerAtomic('$set', this);
this._markModified();
return ret;
},
/**
* Pops the array atomically at most one time per document `save()`.
*
* #### NOTE:
*
* _Calling this mulitple times on an array before saving sends the same command as calling it once._
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
*
* doc.array = [1,2,3];
*
* var popped = doc.array.$pop();
* console.log(popped); // 3
* console.log(doc.array); // [1,2]
*
* // no affect
* popped = doc.array.$pop();
* console.log(doc.array); // [1,2]
*
* doc.save(function (err) {
* if (err) return handleError(err);
*
* // we saved, now $pop works again
* popped = doc.array.$pop();
* console.log(popped); // 2
* console.log(doc.array); // [1]
* })
*
* @api public
* @method $pop
* @memberOf MongooseArray
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
* @method $pop
*/
$pop: function () {
this._registerAtomic('$pop', 1);
this._markModified();
// only allow popping once
if (this._popped) return;
this._popped = true;
return [].pop.call(this);
},
/**
* Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.
*
* ####Note:
*
* _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @see MongooseArray#$pop #types_array_MongooseArray-%24pop
* @api public
* @method pop
*/
pop: function () {
var ret = [].pop.call(this);
this._registerAtomic('$set', this);
this._markModified();
return ret;
},
/**
* Atomically shifts the array at most one time per document `save()`.
*
* ####NOTE:
*
* _Calling this mulitple times on an array before saving sends the same command as calling it once._
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
*
* doc.array = [1,2,3];
*
* var shifted = doc.array.$shift();
* console.log(shifted); // 1
* console.log(doc.array); // [2,3]
*
* // no affect
* shifted = doc.array.$shift();
* console.log(doc.array); // [2,3]
*
* doc.save(function (err) {
* if (err) return handleError(err);
*
* // we saved, now $shift works again
* shifted = doc.array.$shift();
* console.log(shifted ); // 2
* console.log(doc.array); // [3]
* })
*
* @api public
* @memberOf MongooseArray
* @method $shift
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
*/
$shift: function $shift () {
this._registerAtomic('$pop', -1);
this._markModified();
// only allow shifting once
if (this._shifted) return;
this._shifted = true;
return [].shift.call(this);
},
/**
* Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
*
* ####Example:
*
* doc.array = [2,3];
* var res = doc.array.shift();
* console.log(res) // 2
* console.log(doc.array) // [3]
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
* @method shift
*/
shift: function () {
var ret = [].shift.call(this);
this._registerAtomic('$set', this);
this._markModified();
return ret;
},
/**
* Pulls items from the array atomically.
*
* ####Examples:
*
* doc.array.pull(ObjectId)
* doc.array.pull({ _id: 'someId' })
* doc.array.pull(36)
* doc.array.pull('tag 1', 'tag 2')
*
* To remove a document from a subdocument array we may pass an object with a matching `_id`.
*
* doc.subdocs.push({ _id: 4815162342 })
* doc.subdocs.pull({ _id: 4815162342 }) // removed
*
* Or we may passing the _id directly and let mongoose take care of it.
*
* doc.subdocs.push({ _id: 4815162342 })
* doc.subdocs.pull(4815162342); // works
*
* @param {any} [args...]
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
* @api public
* @method pull
*/
pull: function () {
var values = [].map.call(arguments, this._cast, this)
, cur = this._parent.get(this._path)
, i = cur.length
, mem;
while (i--) {
mem = cur[i];
if (mem instanceof EmbeddedDocument) {
if (values.some(function (v) { return v.equals(mem); } )) {
[].splice.call(cur, i, 1);
}
} else if (~cur.indexOf.call(values, mem)) {
[].splice.call(cur, i, 1);
}
}
if (values[0] instanceof EmbeddedDocument) {
this._registerAtomic('$pullDocs', values.map( function (v) { return v._id; } ));
} else {
this._registerAtomic('$pullAll', values);
}
this._markModified();
return this;
},
/**
* Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
* @method splice
*/
splice: function splice () {
var ret, vals, i;
if (arguments.length) {
vals = [];
for (i = 0; i < arguments.length; ++i) {
vals[i] = i < 2
? arguments[i]
: this._cast(arguments[i]);
}
ret = [].splice.apply(this, vals);
this._registerAtomic('$set', this);
this._markModified();
}
return ret;
},
/**
* Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
* @method unshift
*/
unshift: function () {
var values = [].map.call(arguments, this._cast, this);
[].unshift.apply(this, values);
this._registerAtomic('$set', this);
this._markModified();
return this.length;
},
/**
* Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking.
*
* ####NOTE:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
* @method sort
*/
sort: function () {
var ret = [].sort.apply(this, arguments);
this._registerAtomic('$set', this);
this._markModified();
return ret;
},
/**
* Adds values to the array if not already present.
*
* ####Example:
*
* console.log(doc.array) // [2,3,4]
* var added = doc.array.addToSet(4,5);
* console.log(doc.array) // [2,3,4,5]
* console.log(added) // [5]
*
* @param {any} [args...]
* @return {Array} the values that were added
* @api public
* @method addToSet
*/
addToSet: function addToSet () {
var values = [].map.call(arguments, this._cast, this)
, added = []
, type = values[0] instanceof EmbeddedDocument ? 'doc' :
values[0] instanceof Date ? 'date' :
'';
values.forEach(function (v) {
var found;
switch (type) {
case 'doc':
found = this.some(function(doc){ return doc.equals(v) });
break;
case 'date':
var val = +v;
found = this.some(function(d){ return +d === val });
break;
default:
found = ~this.indexOf(v);
}
if (!found) {
[].push.call(this, v);
this._registerAtomic('$addToSet', v);
this._markModified();
[].push.call(added, v);
}
}, this);
return added;
},
/**
* Sets the casted `val` at index `i` and marks the array modified.
*
* ####Example:
*
* // given documents based on the following
* var Doc = mongoose.model('Doc', new Schema({ array: [Number] }));
*
* var doc = new Doc({ array: [2,3,4] })
*
* console.log(doc.array) // [2,3,4]
*
* doc.array.set(1,"5");
* console.log(doc.array); // [2,5,4] // properly cast to number
* doc.save() // the change is saved
*
* // VS not using array#set
* doc.array[1] = "5";
* console.log(doc.array); // [2,"5",4] // no casting
* doc.save() // change is not saved
*
* @return {Array} this
* @api public
* @method set
*/
set: function set (i, val) {
this[i] = this._cast(val);
this._markModified(i);
return this;
},
/**
* Returns a native js Array.
*
* @param {Object} options
* @return {Array}
* @api public
* @method toObject
*/
toObject: function (options) {
if (options && options.depopulate) {
return this.map(function (doc) {
return doc instanceof Document
? doc.toObject(options)
: doc
});
}
return this.slice();
},
/**
* Helper for console.log
*
* @api public
* @method inspect
*/
inspect: function () {
return JSON.stringify(this);
},
/**
* Return the index of `obj` or `-1` if not found.
*
* @param {Object} obj the item to look for
* @return {Number}
* @api public
* @method indexOf
*/
indexOf: function indexOf (obj) {
if (obj instanceof ObjectId) obj = obj.toString();
for (var i = 0, len = this.length; i < len; ++i) {
if (obj == this[i])
return i;
}
return -1;
}
};
/**
* Alias of [pull](#types_array_MongooseArray-pull)
*
* @see MongooseArray#pull #types_array_MongooseArray-pull
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
* @api public
* @memberOf MongooseArray
* @method remove
*/
MongooseArray.mixin.remove = MongooseArray.mixin.pull;
/*!
* Module exports.
*/
module.exports = exports = MongooseArray;
|
'use strict';
var lint = require('./_lint');
//////////////////////////////
// SCSS syntax tests
//////////////////////////////
describe('placeholder in extend - scss', function () {
var file = lint.file('placeholder-in-extend.scss');
it('enforce', function (done) {
lint.test(file, {
'placeholder-in-extend': 1
}, function (data) {
lint.assert.equal(1, data.warningCount);
done();
});
});
});
//////////////////////////////
// Sass syntax tests
//////////////////////////////
describe('placeholder in extend - sass', function () {
var file = lint.file('placeholder-in-extend.sass');
it('enforce', function (done) {
lint.test(file, {
'placeholder-in-extend': 1
}, function (data) {
lint.assert.equal(1, data.warningCount);
done();
});
});
});
|
// KUTE.js v1.6.1 | © dnp_theme | jQuery Plugin | MIT-License
!function(e,t){if("function"==typeof define&&define.amd)define(["./kute.js","jquery"],function(e,n){return t(n,e),e});else if("object"==typeof module&&"function"==typeof require){var n=require("./kute.js"),r=require("jquery");module.exports=t(r,n)}else{if("undefined"==typeof e.KUTE||"undefined"==typeof e.$&&"undefined"==typeof e.jQuery)throw new Error("jQuery Plugin for KUTE.js depend on KUTE.js and jQuery");var r=e.jQuery||e.$,n=e.KUTE;t(r,n)}}(this,function(e,t){"use strict";return e.fn.fromTo=function(e,n,r){var i=this.length>1?this:this[0],o=this.length>1?"allFromTo":"fromTo";return t[o](i,e,n,r)},e.fn.to=function(e,n){var r=this.length>1?this:this[0],i=this.length>1?"allTo":"to";return t[i](r,e,n)},this});
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["ReactDataGrid"] = factory(require("react"), require("react-dom"));
else
root["ReactDataGrid"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_2__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var Grid = __webpack_require__(54);
var Row = __webpack_require__(18);
var Cell = __webpack_require__(24);
module.exports = Grid;
module.exports.Row = Row;
module.exports.Cell = Cell;
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(31);
/** 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) {
'use strict';
module.exports = {
getColumn: function getColumn(columns, idx) {
if (Array.isArray(columns)) {
return columns[idx];
} else if (typeof Immutable !== 'undefined') {
return columns.get(idx);
}
},
spliceColumn: function spliceColumn(metrics, idx, column) {
if (Array.isArray(metrics.columns)) {
metrics.columns.splice(idx, 1, column);
} else if (typeof Immutable !== 'undefined') {
metrics.columns = metrics.columns.splice(idx, 1, column);
}
return metrics;
},
getSize: function getSize(columns) {
if (Array.isArray(columns)) {
return columns.length;
} else if (typeof Immutable !== 'undefined') {
return columns.size;
}
},
// Logic extented to allow for functions to be passed down in column.editable
// this allows us to deicde whether we can be edting from a cell level
canEdit: function canEdit(col, rowData, enableCellSelect) {
if (col.editable != null && typeof col.editable === 'function') {
return enableCellSelect === true && col.editable(rowData);
}
return enableCellSelect === true && (!!col.editor || !!col.editable);
}
};
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2015 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
function classNames() {
var classes = '';
var arg;
for (var i = 0; i < arguments.length; i++) {
arg = arguments[i];
if (!arg) {
continue;
}
if ('string' === typeof arg || 'number' === typeof arg) {
classes += ' ' + arg;
} else if (Object.prototype.toString.call(arg) === '[object Array]') {
classes += ' ' + classNames.apply(null, arg);
} else if ('object' === typeof arg) {
for (var key in arg) {
if (!arg.hasOwnProperty(key) || !arg[key]) {
continue;
}
classes += ' ' + key;
}
}
}
return classes.substr(1);
}
// safely export classNames for node / browserify
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
}
// safely export classNames for RequireJS
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ExcelColumnShape = {
name: React.PropTypes.node.isRequired,
key: React.PropTypes.string.isRequired,
width: React.PropTypes.number.isRequired,
filterable: React.PropTypes.bool
};
module.exports = ExcelColumnShape;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(86),
getValue = __webpack_require__(97);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var PropTypes = __webpack_require__(1).PropTypes;
module.exports = {
selected: PropTypes.object.isRequired,
copied: PropTypes.object,
dragged: PropTypes.object,
onCellClick: PropTypes.func.isRequired,
onCellDoubleClick: PropTypes.func.isRequired,
onCommit: PropTypes.func.isRequired,
onCommitCancel: PropTypes.func.isRequired,
handleDragEnterRow: PropTypes.func.isRequired,
handleTerminateDrag: PropTypes.func.isRequired
};
/***/ },
/* 9 */
/***/ function(module, exports) {
"use strict";
function createObjectWithProperties(originalObj, properties) {
var result = {};
for (var _iterator = properties, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var property = _ref;
if (originalObj[property]) {
result[property] = originalObj[property];
}
}
return result;
}
module.exports = createObjectWithProperties;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var shallowCloneObject = __webpack_require__(20);
var contextTypes = {
metricsComputator: React.PropTypes.object
};
var MetricsComputatorMixin = {
childContextTypes: contextTypes,
getChildContext: function getChildContext() {
return { metricsComputator: this };
},
getMetricImpl: function getMetricImpl(name) {
return this._DOMMetrics.metrics[name].value;
},
registerMetricsImpl: function registerMetricsImpl(component, metrics) {
var getters = {};
var s = this._DOMMetrics;
for (var name in metrics) {
if (s.metrics[name] !== undefined) {
throw new Error('DOM metric ' + name + ' is already defined');
}
s.metrics[name] = { component: component, computator: metrics[name].bind(component) };
getters[name] = this.getMetricImpl.bind(null, name);
}
if (s.components.indexOf(component) === -1) {
s.components.push(component);
}
return getters;
},
unregisterMetricsFor: function unregisterMetricsFor(component) {
var s = this._DOMMetrics;
var idx = s.components.indexOf(component);
if (idx > -1) {
s.components.splice(idx, 1);
var name = void 0;
var metricsToDelete = {};
for (name in s.metrics) {
if (s.metrics[name].component === component) {
metricsToDelete[name] = true;
}
}
for (name in metricsToDelete) {
if (metricsToDelete.hasOwnProperty(name)) {
delete s.metrics[name];
}
}
}
},
updateMetrics: function updateMetrics() {
var s = this._DOMMetrics;
var needUpdate = false;
for (var name in s.metrics) {
if (!s.metrics.hasOwnProperty(name)) continue;
var newMetric = s.metrics[name].computator();
if (newMetric !== s.metrics[name].value) {
needUpdate = true;
}
s.metrics[name].value = newMetric;
}
if (needUpdate) {
for (var i = 0, len = s.components.length; i < len; i++) {
if (s.components[i].metricsUpdated) {
s.components[i].metricsUpdated();
}
}
}
},
componentWillMount: function componentWillMount() {
this._DOMMetrics = {
metrics: {},
components: []
};
},
componentDidMount: function componentDidMount() {
if (window.addEventListener) {
window.addEventListener('resize', this.updateMetrics);
} else {
window.attachEvent('resize', this.updateMetrics);
}
this.updateMetrics();
},
componentWillUnmount: function componentWillUnmount() {
window.removeEventListener('resize', this.updateMetrics);
}
};
var MetricsMixin = {
contextTypes: contextTypes,
componentWillMount: function componentWillMount() {
if (this.DOMMetrics) {
this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics);
this.DOMMetrics = {};
for (var name in this._DOMMetricsDefs) {
if (!this._DOMMetricsDefs.hasOwnProperty(name)) continue;
this.DOMMetrics[name] = function () {};
}
}
},
componentDidMount: function componentDidMount() {
if (this.DOMMetrics) {
this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs);
}
},
componentWillUnmount: function componentWillUnmount() {
if (!this.registerMetricsImpl) {
return this.context.metricsComputator.unregisterMetricsFor(this);
}
if (this.hasOwnProperty('DOMMetrics')) {
delete this.DOMMetrics;
}
},
registerMetrics: function registerMetrics(metrics) {
if (this.registerMetricsImpl) {
return this.registerMetricsImpl(this, metrics);
}
return this.context.metricsComputator.registerMetricsImpl(this, metrics);
},
getMetric: function getMetric(name) {
if (this.getMetricImpl) {
return this.getMetricImpl(name);
}
return this.context.metricsComputator.getMetricImpl(name);
}
};
module.exports = {
MetricsComputatorMixin: MetricsComputatorMixin,
MetricsMixin: MetricsMixin
};
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(107),
listCacheDelete = __webpack_require__(108),
listCacheGet = __webpack_require__(109),
listCacheHas = __webpack_require__(110),
listCacheSet = __webpack_require__(111);
/**
* 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;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var eq = __webpack_require__(33);
/**
* 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;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(22),
getRawTag = __webpack_require__(95),
objectToString = __webpack_require__(120);
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
value = Object(value);
return (symToStringTag && symToStringTag in value)
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(104);
/**
* 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;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ },
/* 16 */
/***/ 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;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var shallowCloneObject = __webpack_require__(20);
var sameColumn = __webpack_require__(43);
var ColumnUtils = __webpack_require__(4);
var getScrollbarSize = __webpack_require__(19);
var isColumnsImmutable = __webpack_require__(70);
function setColumnWidths(columns, totalWidth) {
return columns.map(function (column) {
var colInfo = Object.assign({}, column);
if (column.width) {
if (/^([0-9]+)%$/.exec(column.width.toString())) {
colInfo.width = Math.floor(column.width / 100 * totalWidth);
}
}
return colInfo;
});
}
function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) {
var defferedColumns = columns.filter(function (c) {
return !c.width;
});
return columns.map(function (column) {
if (!column.width) {
if (unallocatedWidth <= 0) {
column.width = minColumnWidth;
} else {
column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns));
}
}
return column;
});
}
function setColumnOffsets(columns) {
var left = 0;
return columns.map(function (column) {
column.left = left;
left += column.width;
return column;
});
}
/**
* Update column metrics calculation.
*
* @param {ColumnMetricsType} metrics
*/
function recalculate(metrics) {
// compute width for columns which specify width
var columns = setColumnWidths(metrics.columns, metrics.totalWidth);
var unallocatedWidth = columns.filter(function (c) {
return c.width;
}).reduce(function (w, column) {
return w - column.width;
}, metrics.totalWidth);
unallocatedWidth -= getScrollbarSize();
var width = columns.filter(function (c) {
return c.width;
}).reduce(function (w, column) {
return w + column.width;
}, 0);
// compute width for columns which doesn't specify width
columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth);
// compute left offset
columns = setColumnOffsets(columns);
return {
columns: columns,
width: width,
totalWidth: metrics.totalWidth,
minColumnWidth: metrics.minColumnWidth
};
}
/**
* Update column metrics calculation by resizing a column.
*
* @param {ColumnMetricsType} metrics
* @param {Column} column
* @param {number} width
*/
function resizeColumn(metrics, index, width) {
var column = ColumnUtils.getColumn(metrics.columns, index);
var metricsClone = shallowCloneObject(metrics);
metricsClone.columns = metrics.columns.slice(0);
var updatedColumn = shallowCloneObject(column);
updatedColumn.width = Math.max(width, metricsClone.minColumnWidth);
metricsClone = ColumnUtils.spliceColumn(metricsClone, index, updatedColumn);
return recalculate(metricsClone);
}
function areColumnsImmutable(prevColumns, nextColumns) {
return isColumnsImmutable(prevColumns) && isColumnsImmutable(nextColumns);
}
function compareEachColumn(prevColumns, nextColumns, isSameColumn) {
var i = void 0;
var len = void 0;
var column = void 0;
var prevColumnsByKey = {};
var nextColumnsByKey = {};
if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) {
return false;
}
for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) {
column = prevColumns[i];
prevColumnsByKey[column.key] = column;
}
for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) {
column = nextColumns[i];
nextColumnsByKey[column.key] = column;
var prevColumn = prevColumnsByKey[column.key];
if (prevColumn === undefined || !isSameColumn(prevColumn, column)) {
return false;
}
}
for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) {
column = prevColumns[i];
var nextColumn = nextColumnsByKey[column.key];
if (nextColumn === undefined) {
return false;
}
}
return true;
}
function sameColumns(prevColumns, nextColumns, isSameColumn) {
if (areColumnsImmutable(prevColumns, nextColumns)) {
return prevColumns === nextColumns;
}
return compareEachColumn(prevColumns, nextColumns, isSameColumn);
}
module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns };
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _OverflowCell = __webpack_require__(53);
var _OverflowCell2 = _interopRequireDefault(_OverflowCell);
var _RowComparer = __webpack_require__(56);
var _RowComparer2 = _interopRequireDefault(_RowComparer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(5);
var Cell = __webpack_require__(24);
var ColumnUtilsMixin = __webpack_require__(4);
var cellMetaDataShape = __webpack_require__(8);
var PropTypes = React.PropTypes;
var createObjectWithProperties = __webpack_require__(9);
var CellExpander = React.createClass({
displayName: 'CellExpander',
render: function render() {
return React.createElement(Cell, this.props);
}
});
// The list of the propTypes that we want to include in the Row div
var knownDivPropertyKeys = ['height'];
var Row = React.createClass({
displayName: 'Row',
propTypes: {
height: PropTypes.number.isRequired,
columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
row: PropTypes.any.isRequired,
cellRenderer: PropTypes.func,
cellMetaData: PropTypes.shape(cellMetaDataShape),
isSelected: PropTypes.bool,
idx: PropTypes.number.isRequired,
expandedRows: PropTypes.arrayOf(PropTypes.object),
extraClasses: PropTypes.string,
forceUpdate: PropTypes.bool,
subRowDetails: PropTypes.object,
isRowHovered: PropTypes.bool,
colVisibleStart: PropTypes.number.isRequired,
colVisibleEnd: PropTypes.number.isRequired,
colDisplayStart: PropTypes.number.isRequired,
colDisplayEnd: PropTypes.number.isRequired,
isScrolling: React.PropTypes.bool.isRequired
},
mixins: [ColumnUtilsMixin],
getDefaultProps: function getDefaultProps() {
return {
cellRenderer: Cell,
isSelected: false,
height: 35
};
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return (0, _RowComparer2['default'])(nextProps, this.props);
},
handleDragEnter: function handleDragEnter() {
var handleDragEnterRow = this.props.cellMetaData.handleDragEnterRow;
if (handleDragEnterRow) {
handleDragEnterRow(this.props.idx);
}
},
getSelectedColumn: function getSelectedColumn() {
if (this.props.cellMetaData) {
var selected = this.props.cellMetaData.selected;
if (selected && selected.idx) {
return this.getColumn(this.props.columns, selected.idx);
}
}
},
getCellRenderer: function getCellRenderer(columnKey) {
var CellRenderer = this.props.cellRenderer;
if (this.props.subRowDetails && this.props.subRowDetails.field === columnKey) {
return CellExpander;
}
return CellRenderer;
},
getCell: function getCell(column, i, selectedColumn) {
var CellRenderer = this.props.cellRenderer;
var _props = this.props,
colVisibleStart = _props.colVisibleStart,
colVisibleEnd = _props.colVisibleEnd,
idx = _props.idx,
cellMetaData = _props.cellMetaData;
var key = column.key,
formatter = column.formatter,
locked = column.locked;
var baseCellProps = { key: key + '-' + idx, idx: i, rowIdx: idx, height: this.getRowHeight(), column: column, cellMetaData: cellMetaData };
if ((i < colVisibleStart || i > colVisibleEnd) && !locked) {
return React.createElement(_OverflowCell2['default'], _extends({ ref: key }, baseCellProps));
}
var _props2 = this.props,
row = _props2.row,
isSelected = _props2.isSelected;
var cellProps = {
ref: key,
value: this.getCellValue(key || i),
rowData: row,
isRowSelected: isSelected,
expandableOptions: this.getExpandableOptions(key),
selectedColumn: selectedColumn,
formatter: formatter,
isScrolling: this.props.isScrolling
};
return React.createElement(CellRenderer, _extends({}, baseCellProps, cellProps));
},
getCells: function getCells() {
var _this = this;
var cells = [];
var lockedCells = [];
var selectedColumn = this.getSelectedColumn();
if (this.props.columns) {
this.props.columns.forEach(function (column, i) {
var cell = _this.getCell(column, i, selectedColumn);
if (column.locked) {
lockedCells.push(cell);
} else {
cells.push(cell);
}
});
}
return cells.concat(lockedCells);
},
getRowHeight: function getRowHeight() {
var rows = this.props.expandedRows || null;
if (rows && this.props.idx) {
var row = rows[this.props.idx] || null;
if (row) {
return row.height;
}
}
return this.props.height;
},
getCellValue: function getCellValue(key) {
var val = void 0;
if (key === 'select-row') {
return this.props.isSelected;
} else if (typeof this.props.row.get === 'function') {
val = this.props.row.get(key);
} else {
val = this.props.row[key];
}
return val;
},
isContextMenuDisplayed: function isContextMenuDisplayed() {
if (this.props.cellMetaData) {
var selected = this.props.cellMetaData.selected;
if (selected && selected.contextMenuDisplayed && selected.rowIdx === this.props.idx) {
return true;
}
}
return false;
},
getExpandableOptions: function getExpandableOptions(columnKey) {
return { canExpand: this.props.subRowDetails && this.props.subRowDetails.field === columnKey, expanded: this.props.subRowDetails && this.props.subRowDetails.expanded, children: this.props.subRowDetails && this.props.subRowDetails.children, treeDepth: this.props.subRowDetails ? this.props.subRowDetails.treeDepth : 0 };
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var _this2 = this;
this.props.columns.forEach(function (column) {
if (column.locked) {
if (!_this2.refs[column.key]) return;
_this2.refs[column.key].setScrollLeft(scrollLeft);
}
});
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
renderCell: function renderCell(props) {
if (typeof this.props.cellRenderer === 'function') {
this.props.cellRenderer.call(this, props);
}
if (React.isValidElement(this.props.cellRenderer)) {
return React.cloneElement(this.props.cellRenderer, props);
}
return this.props.cellRenderer(props);
},
render: function render() {
var className = joinClasses('react-grid-Row', 'react-grid-Row--' + (this.props.idx % 2 === 0 ? 'even' : 'odd'), {
'row-selected': this.props.isSelected,
'row-context-menu': this.isContextMenuDisplayed()
}, this.props.extraClasses);
var style = {
height: this.getRowHeight(this.props),
overflow: 'hidden',
contain: 'layout'
};
var cells = this.getCells();
return React.createElement(
'div',
_extends({}, this.getKnownDivProps(), { className: className, style: style, onDragEnter: this.handleDragEnter }),
React.isValidElement(this.props.row) ? this.props.row : cells
);
}
});
module.exports = Row;
/***/ },
/* 19 */
/***/ function(module, exports) {
'use strict';
var size = void 0;
function getScrollbarSize() {
if (size === undefined) {
var outer = document.createElement('div');
outer.style.width = '50px';
outer.style.height = '50px';
outer.style.position = 'absolute';
outer.style.top = '-200px';
outer.style.left = '-200px';
var inner = document.createElement('div');
inner.style.height = '100px';
inner.style.width = '100%';
outer.appendChild(inner);
document.body.appendChild(outer);
var outerWidth = outer.clientWidth;
outer.style.overflowY = 'scroll';
var innerWidth = inner.clientWidth;
document.body.removeChild(outer);
size = outerWidth - innerWidth;
}
return size;
}
module.exports = getScrollbarSize;
/***/ },
/* 20 */
/***/ function(module, exports) {
"use strict";
function shallowCloneObject(obj) {
var result = {};
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
result[k] = obj[k];
}
}
return result;
}
module.exports = shallowCloneObject;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ },
/* 23 */
/***/ 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;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _isEqual = __webpack_require__(132);
var _isEqual2 = _interopRequireDefault(_isEqual);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(5);
var EditorContainer = __webpack_require__(66);
var ExcelColumn = __webpack_require__(6);
var isFunction = __webpack_require__(27);
var CellMetaDataShape = __webpack_require__(8);
var SimpleCellFormatter = __webpack_require__(68);
var ColumnUtils = __webpack_require__(4);
var createObjectWithProperties = __webpack_require__(9);
// The list of the propTypes that we want to include in the Cell div
var knownDivPropertyKeys = ['height', 'tabIndex', 'value'];
var Cell = React.createClass({
displayName: 'Cell',
propTypes: {
rowIdx: React.PropTypes.number.isRequired,
idx: React.PropTypes.number.isRequired,
selected: React.PropTypes.shape({
idx: React.PropTypes.number.isRequired
}),
selectedColumn: React.PropTypes.object,
height: React.PropTypes.number,
tabIndex: React.PropTypes.number,
ref: React.PropTypes.string,
column: React.PropTypes.shape(ExcelColumn).isRequired,
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired,
isExpanded: React.PropTypes.bool,
isRowSelected: React.PropTypes.bool,
cellMetaData: React.PropTypes.shape(CellMetaDataShape).isRequired,
handleDragStart: React.PropTypes.func,
className: React.PropTypes.string,
cellControls: React.PropTypes.any,
rowData: React.PropTypes.object.isRequired,
forceUpdate: React.PropTypes.bool,
expandableOptions: React.PropTypes.object.isRequired,
isScrolling: React.PropTypes.bool.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
tabIndex: -1,
isExpanded: false,
value: ''
};
},
getInitialState: function getInitialState() {
return {
isCellValueChanging: false
};
},
componentDidMount: function componentDidMount() {
this.checkFocus();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.setState({
isCellValueChanging: this.props.value !== nextProps.value
});
},
componentDidUpdate: function componentDidUpdate() {
this.checkFocus();
var dragged = this.props.cellMetaData.dragged;
if (dragged && dragged.complete === true) {
this.props.cellMetaData.handleTerminateDrag();
}
if (this.state.isCellValueChanging && this.props.selectedColumn != null) {
this.applyUpdateClass();
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
var shouldUpdate = this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.column.cellClass !== nextProps.column.cellClass || this.props.height !== nextProps.height || this.props.rowIdx !== nextProps.rowIdx || this.isCellSelectionChanging(nextProps) || this.isDraggedCellChanging(nextProps) || this.isCopyCellChanging(nextProps) || this.props.isRowSelected !== nextProps.isRowSelected || this.isSelected() || this.props.value !== nextProps.value || this.props.forceUpdate === true || this.props.className !== nextProps.className || this.hasChangedDependentValues(nextProps);
return shouldUpdate;
},
onCellClick: function onCellClick(e) {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellClick && typeof meta.onCellClick === 'function') {
meta.onCellClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }, e);
}
},
onCellContextMenu: function onCellContextMenu() {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellContextMenu && typeof meta.onCellContextMenu === 'function') {
meta.onCellContextMenu({ rowIdx: this.props.rowIdx, idx: this.props.idx });
}
},
onCellDoubleClick: function onCellDoubleClick(e) {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellDoubleClick && typeof meta.onCellDoubleClick === 'function') {
meta.onCellDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }, e);
}
},
onCellExpand: function onCellExpand(e) {
e.stopPropagation();
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellExpand != null) {
meta.onCellExpand({ rowIdx: this.props.rowIdx, idx: this.props.idx, rowData: this.props.rowData, expandArgs: this.props.expandableOptions });
}
},
onCellKeyDown: function onCellKeyDown(e) {
if (this.canExpand() && e.key === 'Enter') {
this.onCellExpand(e);
}
},
onDragHandleDoubleClick: function onDragHandleDoubleClick(e) {
e.stopPropagation();
var meta = this.props.cellMetaData;
if (meta != null && meta.onDragHandleDoubleClick && typeof meta.onDragHandleDoubleClick === 'function') {
meta.onDragHandleDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx, rowData: this.getRowData(), e: e });
}
},
onDragOver: function onDragOver(e) {
e.preventDefault();
},
getStyle: function getStyle() {
var style = {
position: 'absolute',
width: this.props.column.width,
height: this.props.height,
left: this.props.column.left,
contain: 'layout'
};
return style;
},
getFormatter: function getFormatter() {
var col = this.props.column;
if (this.isActive()) {
return React.createElement(EditorContainer, { rowData: this.getRowData(), rowIdx: this.props.rowIdx, value: this.props.value, idx: this.props.idx, cellMetaData: this.props.cellMetaData, column: col, height: this.props.height });
}
return this.props.column.formatter;
},
getRowData: function getRowData() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
return props.rowData.toJSON ? props.rowData.toJSON() : props.rowData;
},
getFormatterDependencies: function getFormatterDependencies() {
// convention based method to get corresponding Id or Name of any Name or Id property
if (typeof this.props.column.getRowMetaData === 'function') {
return this.props.column.getRowMetaData(this.getRowData(), this.props.column);
}
},
getCellClass: function getCellClass() {
var className = joinClasses(this.props.column.cellClass, 'react-grid-Cell', this.props.className, this.props.column.locked ? 'react-grid-Cell--locked' : null);
var extraClasses = joinClasses({
'row-selected': this.props.isRowSelected,
editing: this.isActive(),
copied: this.isCopied() || this.wasDraggedOver() || this.isDraggedOverUpwards() || this.isDraggedOverDownwards(),
'is-dragged-over-up': this.isDraggedOverUpwards(),
'is-dragged-over-down': this.isDraggedOverDownwards(),
'was-dragged-over': this.wasDraggedOver()
});
return joinClasses(className, extraClasses);
},
getUpdateCellClass: function getUpdateCellClass() {
return this.props.column.getUpdateCellClass ? this.props.column.getUpdateCellClass(this.props.selectedColumn, this.props.column, this.state.isCellValueChanging) : '';
},
isColumnSelected: function isColumnSelected() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.selected && meta.selected.idx === this.props.idx;
},
isSelected: function isSelected() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.selected && meta.selected.rowIdx === this.props.rowIdx && meta.selected.idx === this.props.idx;
},
isActive: function isActive() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return this.isSelected() && meta.selected.active === true;
},
isCellSelectionChanging: function isCellSelectionChanging(nextProps) {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
var nextSelected = nextProps.cellMetaData.selected;
if (meta.selected && nextSelected) {
return this.props.idx === nextSelected.idx || this.props.idx === meta.selected.idx;
}
return true;
},
isCellSelectEnabled: function isCellSelectEnabled() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.enableCellSelect;
},
hasChangedDependentValues: function hasChangedDependentValues(nextProps) {
var currentColumn = this.props.column;
var hasChangedDependentValues = false;
if (currentColumn.getRowMetaData) {
var currentRowMetaData = currentColumn.getRowMetaData(this.getRowData(), currentColumn);
var nextColumn = nextProps.column;
var nextRowMetaData = nextColumn.getRowMetaData(this.getRowData(nextProps), nextColumn);
hasChangedDependentValues = !(0, _isEqual2['default'])(currentRowMetaData, nextRowMetaData);
}
return hasChangedDependentValues;
},
applyUpdateClass: function applyUpdateClass() {
var updateCellClass = this.getUpdateCellClass();
// -> removing the class
if (updateCellClass != null && updateCellClass !== '') {
var cellDOMNode = ReactDOM.findDOMNode(this);
if (cellDOMNode.classList) {
cellDOMNode.classList.remove(updateCellClass);
// -> and re-adding the class
cellDOMNode.classList.add(updateCellClass);
} else if (cellDOMNode.className.indexOf(updateCellClass) === -1) {
// IE9 doesn't support classList, nor (I think) altering element.className
// without replacing it wholesale.
cellDOMNode.className = cellDOMNode.className + ' ' + updateCellClass;
}
}
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var ctrl = this; // flow on windows has an outdated react declaration, once that gets updated, we can remove this
if (ctrl.isMounted()) {
var node = ReactDOM.findDOMNode(this);
var transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
node.style.webkitTransform = transform;
node.style.transform = transform;
}
},
isCopied: function isCopied() {
var copied = this.props.cellMetaData.copied;
return copied && copied.rowIdx === this.props.rowIdx && copied.idx === this.props.idx;
},
isDraggedOver: function isDraggedOver() {
var dragged = this.props.cellMetaData.dragged;
return dragged && dragged.overRowIdx === this.props.rowIdx && dragged.idx === this.props.idx;
},
wasDraggedOver: function wasDraggedOver() {
var dragged = this.props.cellMetaData.dragged;
return dragged && (dragged.overRowIdx < this.props.rowIdx && this.props.rowIdx < dragged.rowIdx || dragged.overRowIdx > this.props.rowIdx && this.props.rowIdx > dragged.rowIdx) && dragged.idx === this.props.idx;
},
isDraggedCellChanging: function isDraggedCellChanging(nextProps) {
var isChanging = void 0;
var dragged = this.props.cellMetaData.dragged;
var nextDragged = nextProps.cellMetaData.dragged;
if (dragged) {
isChanging = nextDragged && this.props.idx === nextDragged.idx || dragged && this.props.idx === dragged.idx;
return isChanging;
}
return false;
},
isCopyCellChanging: function isCopyCellChanging(nextProps) {
var isChanging = void 0;
var copied = this.props.cellMetaData.copied;
var nextCopied = nextProps.cellMetaData.copied;
if (copied) {
isChanging = nextCopied && this.props.idx === nextCopied.idx || copied && this.props.idx === copied.idx;
return isChanging;
}
return false;
},
isDraggedOverUpwards: function isDraggedOverUpwards() {
var dragged = this.props.cellMetaData.dragged;
return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx < dragged.rowIdx;
},
isDraggedOverDownwards: function isDraggedOverDownwards() {
var dragged = this.props.cellMetaData.dragged;
return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx > dragged.rowIdx;
},
isFocusedOnBody: function isFocusedOnBody() {
return document.activeElement == null || document.activeElement.nodeName && typeof document.activeElement.nodeName === 'string' && document.activeElement.nodeName.toLowerCase() === 'body';
},
isFocusedOnCell: function isFocusedOnCell() {
return document.activeElement && document.activeElement.className === 'react-grid-Cell';
},
checkFocus: function checkFocus() {
if (this.isSelected() && !this.isActive()) {
if (this.props.isScrolling && !this.props.cellMetaData.isScrollingVerticallyWithKeyboard && !this.props.cellMetaData.isScrollingHorizontallyWithKeyboard) {
return;
}
// Only focus to the current cell if the currently active node in the document is within the data grid.
// Meaning focus should not be stolen from elements that the grid doesnt control.
var dataGridDOMNode = this.props.cellMetaData && this.props.cellMetaData.getDataGridDOMNode ? this.props.cellMetaData.getDataGridDOMNode() : null;
if (this.isFocusedOnCell() || this.isFocusedOnBody() || dataGridDOMNode && dataGridDOMNode.contains(document.activeElement)) {
var cellDOMNode = ReactDOM.findDOMNode(this);
if (cellDOMNode) {
cellDOMNode.focus();
}
}
}
},
canEdit: function canEdit() {
return this.props.column.editor != null || this.props.column.editable;
},
canExpand: function canExpand() {
return this.props.expandableOptions && this.props.expandableOptions.canExpand;
},
createColumEventCallBack: function createColumEventCallBack(onColumnEvent, info) {
return function (e) {
onColumnEvent(e, info);
};
},
createCellEventCallBack: function createCellEventCallBack(gridEvent, columnEvent) {
return function (e) {
gridEvent(e);
columnEvent(e);
};
},
createEventDTO: function createEventDTO(gridEvents, columnEvents, onColumnEvent) {
var allEvents = Object.assign({}, gridEvents);
for (var eventKey in columnEvents) {
if (columnEvents.hasOwnProperty(eventKey)) {
var event = columnEvents[event];
var eventInfo = { rowIdx: this.props.rowIdx, idx: this.props.idx, name: eventKey };
var eventCallback = this.createColumEventCallBack(onColumnEvent, eventInfo);
if (allEvents.hasOwnProperty(eventKey)) {
var currentEvent = allEvents[eventKey];
allEvents[eventKey] = this.createCellEventCallBack(currentEvent, eventCallback);
} else {
allEvents[eventKey] = eventCallback;
}
}
}
return allEvents;
},
getEvents: function getEvents() {
var columnEvents = this.props.column ? Object.assign({}, this.props.column.events) : undefined;
var onColumnEvent = this.props.cellMetaData ? this.props.cellMetaData.onColumnEvent : undefined;
var gridEvents = {
onClick: this.onCellClick,
onDoubleClick: this.onCellDoubleClick,
onContextMenu: this.onCellContextMenu,
onDragOver: this.onDragOver
};
if (!columnEvents || !onColumnEvent) {
return gridEvents;
}
return this.createEventDTO(gridEvents, columnEvents, onColumnEvent);
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
renderCellContent: function renderCellContent(props) {
var CellContent = void 0;
var Formatter = this.getFormatter();
if (React.isValidElement(Formatter)) {
props.dependentValues = this.getFormatterDependencies();
CellContent = React.cloneElement(Formatter, props);
} else if (isFunction(Formatter)) {
CellContent = React.createElement(Formatter, { value: this.props.value, dependentValues: this.getFormatterDependencies() });
} else {
CellContent = React.createElement(SimpleCellFormatter, { value: this.props.value });
}
var cellExpander = void 0;
var marginLeft = this.props.expandableOptions ? this.props.expandableOptions.treeDepth * 30 : 0;
if (this.canExpand()) {
cellExpander = React.createElement(
'span',
{ style: { float: 'left', marginLeft: marginLeft }, onClick: this.onCellExpand },
this.props.expandableOptions.expanded ? String.fromCharCode('9660') : String.fromCharCode('9658')
);
}
return React.createElement(
'div',
{ className: 'react-grid-Cell__value' },
cellExpander,
React.createElement(
'span',
null,
CellContent
),
' ',
this.props.cellControls,
' '
);
},
render: function render() {
if (this.props.column.hidden) {
return null;
}
var style = this.getStyle();
var className = this.getCellClass();
var cellContent = this.renderCellContent({
value: this.props.value,
column: this.props.column,
rowIdx: this.props.rowIdx,
isExpanded: this.props.isExpanded
});
var dragHandle = !this.isActive() && ColumnUtils.canEdit(this.props.column, this.props.rowData, this.props.cellMetaData.enableCellSelect) ? React.createElement(
'div',
{ className: 'drag-handle', draggable: 'true', onDoubleClick: this.onDragHandleDoubleClick },
React.createElement('span', { style: { display: 'none' } })
) : null;
var events = this.getEvents();
return React.createElement(
'div',
_extends({}, this.getKnownDivProps(), { className: className, style: style }, events),
cellContent,
dragHandle
);
}
});
module.exports = Cell;
/***/ },
/* 25 */
/***/ function(module, exports) {
'use strict';
var KeyboardHandlerMixin = {
onKeyDown: function onKeyDown(e) {
if (this.isCtrlKeyHeldDown(e)) {
this.checkAndCall('onPressKeyWithCtrl', e);
} else if (this.isKeyExplicitlyHandled(e.key)) {
// break up individual keyPress events to have their own specific callbacks
// this allows multiple mixins to listen to onKeyDown events and somewhat reduces methodName clashing
var callBack = 'onPress' + e.key;
this.checkAndCall(callBack, e);
} else if (this.isKeyPrintable(e.keyCode)) {
this.checkAndCall('onPressChar', e);
}
// Track which keys are currently down for shift clicking etc
this._keysDown = this._keysDown || {};
this._keysDown[e.keyCode] = true;
if (this.props.onGridKeyDown && typeof this.props.onGridKeyDown === 'function') {
this.props.onGridKeyDown(e);
}
},
onKeyUp: function onKeyUp(e) {
// Track which keys are currently down for shift clicking etc
this._keysDown = this._keysDown || {};
delete this._keysDown[e.keyCode];
if (this.props.onGridKeyUp && typeof this.props.onGridKeyUp === 'function') {
this.props.onGridKeyUp(e);
}
},
isKeyDown: function isKeyDown(keyCode) {
if (!this._keysDown) return false;
return keyCode in this._keysDown;
},
isSingleKeyDown: function isSingleKeyDown(keyCode) {
if (!this._keysDown) return false;
return keyCode in this._keysDown && Object.keys(this._keysDown).length === 1;
},
// taken from http://stackoverflow.com/questions/12467240/determine-if-javascript-e-keycode-is-a-printable-non-control-character
isKeyPrintable: function isKeyPrintable(keycode) {
var valid = keycode > 47 && keycode < 58 || // number keys
keycode === 32 || keycode === 13 || // spacebar & return key(s) (if you want to allow carriage returns)
keycode > 64 && keycode < 91 || // letter keys
keycode > 95 && keycode < 112 || // numpad keys
keycode > 185 && keycode < 193 || // ;=,-./` (in order)
keycode > 218 && keycode < 223; // [\]' (in order)
return valid;
},
isKeyExplicitlyHandled: function isKeyExplicitlyHandled(key) {
return typeof this['onPress' + key] === 'function';
},
isCtrlKeyHeldDown: function isCtrlKeyHeldDown(e) {
return e.ctrlKey === true && e.key !== 'Control';
},
checkAndCall: function checkAndCall(methodName, args) {
if (typeof this[methodName] === 'function') {
this[methodName](args);
}
}
};
module.exports = KeyboardHandlerMixin;
/***/ },
/* 26 */
/***/ function(module, exports) {
'use strict';
var RowUtils = {
get: function get(row, property) {
if (typeof row.get === 'function') {
return row.get(property);
}
return row[property];
},
isRowSelected: function isRowSelected(keys, indexes, isSelectedKey, rowData, rowIdx) {
if (indexes && Object.prototype.toString.call(indexes) === '[object Array]') {
return indexes.indexOf(rowIdx) > -1;
} else if (keys && keys.rowKey && keys.values && Object.prototype.toString.call(keys.values) === '[object Array]') {
return keys.values.indexOf(rowData[keys.rowKey]) > -1;
} else if (isSelectedKey && rowData && typeof isSelectedKey === 'string') {
return rowData[isSelectedKey];
}
return false;
}
};
module.exports = RowUtils;
/***/ },
/* 27 */
/***/ function(module, exports) {
'use strict';
var isFunction = function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
};
module.exports = isFunction;
/***/ },
/* 28 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule shallowEqual
* @typechecks
*
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var bHasOwnProperty = hasOwnProperty.bind(objB);
for (var i = 0; i < keysA.length; i++) {
if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(112),
mapCacheDelete = __webpack_require__(113),
mapCacheGet = __webpack_require__(114),
mapCacheHas = __webpack_require__(115),
mapCacheSet = __webpack_require__(116);
/**
* 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;
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(77),
arraySome = __webpack_require__(82),
cacheHas = __webpack_require__(91);
/** 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;
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof (window) == 'object' && (window) && (window).Object === Object && (window);
module.exports = freeGlobal;
/***/ },
/* 32 */
/***/ 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;
/***/ },
/* 33 */
/***/ 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;
/***/ },
/* 34 */
/***/ 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;
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3),
stubFalse = __webpack_require__(134);
/** 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__(40)(module)))
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(13),
isObject = __webpack_require__(23);
/** `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;
/***/ },
/* 37 */
/***/ 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;
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(87),
baseUnary = __webpack_require__(90),
nodeUtil = __webpack_require__(119);
/* 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;
/***/ },
/* 39 */
/***/ function(module, exports) {
'use strict';
function ToObject(val) {
if (val == null) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
module.exports = Object.assign || function (target, source) {
var from;
var keys;
var to = ToObject(target);
for (var s = 1; s < arguments.length; s++) {
from = arguments[s];
keys = Object.keys(Object(from));
for (var i = 0; i < keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
}
return to;
};
/***/ },
/* 40 */
/***/ function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
}
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _keyMirror = __webpack_require__(72);
var _keyMirror2 = _interopRequireDefault(_keyMirror);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var constants = {
UpdateActions: (0, _keyMirror2['default'])({
CELL_UPDATE: null,
COLUMN_FILL: null,
COPY_PASTE: null,
CELL_DRAG: null
})
};
exports['default'] = constants;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _shallowEqual = __webpack_require__(28);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _RowsContainer = __webpack_require__(58);
var _RowsContainer2 = _interopRequireDefault(_RowsContainer);
var _RowGroup = __webpack_require__(57);
var _RowGroup2 = _interopRequireDefault(_RowGroup);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(5);
var PropTypes = React.PropTypes;
var ScrollShim = __webpack_require__(59);
var Row = __webpack_require__(18);
var cellMetaDataShape = __webpack_require__(8);
var RowUtils = __webpack_require__(26);
var Canvas = React.createClass({
displayName: 'Canvas',
mixins: [ScrollShim],
propTypes: {
rowRenderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
rowHeight: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
width: PropTypes.number,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
style: PropTypes.string,
className: PropTypes.string,
displayStart: PropTypes.number.isRequired,
displayEnd: PropTypes.number.isRequired,
visibleStart: PropTypes.number.isRequired,
visibleEnd: PropTypes.number.isRequired,
colVisibleStart: PropTypes.number.isRequired,
colVisibleEnd: PropTypes.number.isRequired,
colDisplayStart: PropTypes.number.isRequired,
colDisplayEnd: PropTypes.number.isRequired,
rowsCount: PropTypes.number.isRequired,
rowGetter: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.array.isRequired]),
expandedRows: PropTypes.array,
onRows: PropTypes.func,
onScroll: PropTypes.func,
columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
cellMetaData: PropTypes.shape(cellMetaDataShape).isRequired,
selectedRows: PropTypes.array,
rowKey: React.PropTypes.string,
rowScrollTimeout: React.PropTypes.number,
contextMenu: PropTypes.element,
getSubRowDetails: PropTypes.func,
rowSelection: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]),
rowGroupRenderer: React.PropTypes.func,
isScrolling: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
rowRenderer: Row,
onRows: function onRows() {},
selectedRows: [],
rowScrollTimeout: 0
};
},
getInitialState: function getInitialState() {
return {
displayStart: this.props.displayStart,
displayEnd: this.props.displayEnd,
scrollingTimeout: null
};
},
componentWillMount: function componentWillMount() {
this._currentRowsLength = 0;
this._currentRowsRange = { start: 0, end: 0 };
this._scroll = { scrollTop: 0, scrollLeft: 0 };
},
componentDidMount: function componentDidMount() {
this.onRows();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.displayStart !== this.state.displayStart || nextProps.displayEnd !== this.state.displayEnd) {
this.setState({
displayStart: nextProps.displayStart,
displayEnd: nextProps.displayEnd
});
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
var shouldUpdate = nextState.displayStart !== this.state.displayStart || nextState.displayEnd !== this.state.displayEnd || nextState.scrollingTimeout !== this.state.scrollingTimeout || nextProps.rowsCount !== this.props.rowsCount || nextProps.rowHeight !== this.props.rowHeight || nextProps.columns !== this.props.columns || nextProps.width !== this.props.width || nextProps.cellMetaData !== this.props.cellMetaData || this.props.colDisplayStart !== nextProps.colDisplayStart || this.props.colDisplayEnd !== nextProps.colDisplayEnd || this.props.colVisibleStart !== nextProps.colVisibleStart || this.props.colVisibleEnd !== nextProps.colVisibleEnd || !(0, _shallowEqual2['default'])(nextProps.style, this.props.style);
return shouldUpdate;
},
componentWillUnmount: function componentWillUnmount() {
this._currentRowsLength = 0;
this._currentRowsRange = { start: 0, end: 0 };
this._scroll = { scrollTop: 0, scrollLeft: 0 };
},
componentDidUpdate: function componentDidUpdate() {
if (this._scroll.scrollTop !== 0 && this._scroll.scrollLeft !== 0) {
this.setScrollLeft(this._scroll.scrollLeft);
}
this.onRows();
},
onRows: function onRows() {
if (this._currentRowsRange !== { start: 0, end: 0 }) {
this.props.onRows(this._currentRowsRange);
this._currentRowsRange = { start: 0, end: 0 };
}
},
onScroll: function onScroll(e) {
if (ReactDOM.findDOMNode(this) !== e.target) {
return;
}
this.appendScrollShim();
var scrollLeft = e.target.scrollLeft;
var scrollTop = e.target.scrollTop;
var scroll = { scrollTop: scrollTop, scrollLeft: scrollLeft };
this._scroll = scroll;
this.props.onScroll(scroll);
},
getSubRows: function getSubRows(row) {
var subRowDetails = this.props.getSubRowDetails(row);
if (subRowDetails.expanded === true) {
return subRowDetails.children.map(function (r) {
return { row: r };
});
}
},
addSubRows: function addSubRows(rowsInput, row, i, displayEnd, treeDepth) {
var _this = this;
var subRowDetails = this.props.getSubRowDetails(row) || {};
var rows = rowsInput;
var increment = i;
if (increment < displayEnd) {
subRowDetails.treeDepth = treeDepth;
rows.push({ row: row, subRowDetails: subRowDetails });
increment++;
}
if (subRowDetails && subRowDetails.expanded) {
var subRows = this.getSubRows(row);
subRows.forEach(function (sr) {
var result = _this.addSubRows(rows, sr.row, increment, displayEnd, treeDepth + 1);
rows = result.rows;
increment = result.increment;
});
}
return { rows: rows, increment: increment };
},
getRows: function getRows(displayStart, displayEnd) {
this._currentRowsRange = { start: displayStart, end: displayEnd };
if (Array.isArray(this.props.rowGetter)) {
return this.props.rowGetter.slice(displayStart, displayEnd);
}
var rows = [];
var rowFetchIndex = displayStart;
var i = displayStart;
while (i < displayEnd) {
var row = this.props.rowGetter(rowFetchIndex);
if (this.props.getSubRowDetails) {
var treeDepth = 0;
var result = this.addSubRows(rows, row, i, displayEnd, treeDepth);
rows = result.rows;
i = result.increment;
} else {
rows.push({ row: row });
i++;
}
rowFetchIndex++;
}
return rows;
},
getScrollbarWidth: function getScrollbarWidth() {
var scrollbarWidth = 0;
// Get the scrollbar width
var canvas = ReactDOM.findDOMNode(this);
scrollbarWidth = canvas.offsetWidth - canvas.clientWidth;
return scrollbarWidth;
},
getScroll: function getScroll() {
var _ReactDOM$findDOMNode = ReactDOM.findDOMNode(this),
scrollTop = _ReactDOM$findDOMNode.scrollTop,
scrollLeft = _ReactDOM$findDOMNode.scrollLeft;
return { scrollTop: scrollTop, scrollLeft: scrollLeft };
},
isRowSelected: function isRowSelected(idx, row) {
var _this2 = this;
// Use selectedRows if set
if (this.props.selectedRows !== null) {
var selectedRows = this.props.selectedRows.filter(function (r) {
var rowKeyValue = row.get ? row.get(_this2.props.rowKey) : row[_this2.props.rowKey];
return r[_this2.props.rowKey] === rowKeyValue;
});
return selectedRows.length > 0 && selectedRows[0].isSelected;
}
// Else use new rowSelection props
if (this.props.rowSelection) {
var _props$rowSelection = this.props.rowSelection,
keys = _props$rowSelection.keys,
indexes = _props$rowSelection.indexes,
isSelectedKey = _props$rowSelection.isSelectedKey;
return RowUtils.isRowSelected(keys, indexes, isSelectedKey, row, idx);
}
return false;
},
_currentRowsLength: 0,
_currentRowsRange: { start: 0, end: 0 },
_scroll: { scrollTop: 0, scrollLeft: 0 },
setScrollLeft: function setScrollLeft(scrollLeft) {
if (this._currentRowsLength !== 0) {
if (!this.refs) return;
for (var i = 0, len = this._currentRowsLength; i < len; i++) {
if (this.refs[i]) {
var row = this.getRowByRef(i);
if (row && row.setScrollLeft) {
row.setScrollLeft(scrollLeft);
}
}
}
}
},
getRowByRef: function getRowByRef(i) {
// check if wrapped with React DND drop target
var wrappedRow = this.refs[i].getDecoratedComponentInstance ? this.refs[i].getDecoratedComponentInstance(i) : null;
if (wrappedRow) {
return wrappedRow.refs.row;
}
return this.refs[i];
},
renderRow: function renderRow(props) {
var row = props.row;
if (row.__metaData && row.__metaData.isGroup) {
return React.createElement(_RowGroup2['default'], _extends({
key: props.key,
name: row.name
}, row.__metaData, {
row: props.row,
idx: props.idx,
height: props.height,
cellMetaData: this.props.cellMetaData,
renderer: this.props.rowGroupRenderer
}));
}
var RowsRenderer = this.props.rowRenderer;
if (typeof RowsRenderer === 'function') {
return React.createElement(RowsRenderer, props);
}
if (React.isValidElement(this.props.rowRenderer)) {
return React.cloneElement(this.props.rowRenderer, props);
}
},
renderPlaceholder: function renderPlaceholder(key, height) {
// just renders empty cells
// if we wanted to show gridlines, we'd need classes and position as with renderScrollingPlaceholder
return React.createElement(
'div',
{ key: key, style: { height: height } },
this.props.columns.map(function (column, idx) {
return React.createElement('div', { style: { width: column.width }, key: idx });
})
);
},
render: function render() {
var _this3 = this;
var _state = this.state,
displayStart = _state.displayStart,
displayEnd = _state.displayEnd;
var _props = this.props,
rowHeight = _props.rowHeight,
rowsCount = _props.rowsCount;
var rows = this.getRows(displayStart, displayEnd).map(function (r, idx) {
return _this3.renderRow({
key: 'row-' + (displayStart + idx),
ref: idx,
idx: displayStart + idx,
visibleStart: _this3.props.visibleStart,
visibleEnd: _this3.props.visibleEnd,
row: r.row,
height: rowHeight,
onMouseOver: _this3.onMouseOver,
columns: _this3.props.columns,
isSelected: _this3.isRowSelected(displayStart + idx, r.row, displayStart, displayEnd),
expandedRows: _this3.props.expandedRows,
cellMetaData: _this3.props.cellMetaData,
subRowDetails: r.subRowDetails,
colVisibleStart: _this3.props.colVisibleStart,
colVisibleEnd: _this3.props.colVisibleEnd,
colDisplayStart: _this3.props.colDisplayStart,
colDisplayEnd: _this3.props.colDisplayEnd,
isScrolling: _this3.props.isScrolling
});
});
this._currentRowsLength = rows.length;
if (displayStart > 0) {
rows.unshift(this.renderPlaceholder('top', displayStart * rowHeight));
}
if (rowsCount - displayEnd > 0) {
rows.push(this.renderPlaceholder('bottom', (rowsCount - displayEnd) * rowHeight));
}
var style = {
position: 'absolute',
top: 0,
left: 0,
overflowX: 'auto',
overflowY: 'scroll',
width: this.props.totalWidth,
height: this.props.height
};
return React.createElement(
'div',
{
style: style,
onScroll: this.onScroll,
className: joinClasses('react-grid-Canvas', this.props.className, { opaque: this.props.cellMetaData.selected && this.props.cellMetaData.selected.active }) },
React.createElement(_RowsContainer2['default'], {
width: this.props.width,
rows: rows,
contextMenu: this.props.contextMenu,
rowIdx: this.props.cellMetaData.selected.rowIdx,
idx: this.props.cellMetaData.selected.idx })
);
}
});
module.exports = Canvas;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var isValidElement = __webpack_require__(1).isValidElement;
module.exports = function sameColumn(a, b) {
var k = void 0;
for (k in a) {
if (a.hasOwnProperty(k)) {
if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) {
continue;
}
if (!b.hasOwnProperty(k) || a[k] !== b[k]) {
return false;
}
}
}
for (k in b) {
if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) {
return false;
}
}
return true;
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ColumnMetrics = __webpack_require__(17);
var DOMMetrics = __webpack_require__(10);
Object.assign = __webpack_require__(39);
var PropTypes = __webpack_require__(1).PropTypes;
var ColumnUtils = __webpack_require__(4);
var Column = function Column() {
_classCallCheck(this, Column);
};
module.exports = {
mixins: [DOMMetrics.MetricsMixin],
propTypes: {
columns: PropTypes.arrayOf(Column),
minColumnWidth: PropTypes.number,
columnEquality: PropTypes.func,
onColumnResize: PropTypes.func
},
DOMMetrics: {
gridWidth: function gridWidth() {
return _reactDom2['default'].findDOMNode(this).parentElement.offsetWidth;
}
},
getDefaultProps: function getDefaultProps() {
return {
minColumnWidth: 80,
columnEquality: ColumnMetrics.sameColumn
};
},
componentWillMount: function componentWillMount() {
this._mounted = true;
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.columns) {
if (!ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, this.props.columnEquality) || nextProps.minWidth !== this.props.minWidth) {
var columnMetrics = this.createColumnMetrics(nextProps);
this.setState({ columnMetrics: columnMetrics });
}
}
},
getTotalWidth: function getTotalWidth() {
var totalWidth = 0;
if (this._mounted) {
totalWidth = this.DOMMetrics.gridWidth();
} else {
totalWidth = ColumnUtils.getSize(this.props.columns) * this.props.minColumnWidth;
}
return totalWidth;
},
getColumnMetricsType: function getColumnMetricsType(metrics) {
var totalWidth = metrics.totalWidth || this.getTotalWidth();
var currentMetrics = {
columns: metrics.columns,
totalWidth: totalWidth,
minColumnWidth: metrics.minColumnWidth
};
var updatedMetrics = ColumnMetrics.recalculate(currentMetrics);
return updatedMetrics;
},
getColumn: function getColumn(idx) {
var columns = this.state.columnMetrics.columns;
if (Array.isArray(columns)) {
return columns[idx];
} else if (typeof Immutable !== 'undefined') {
return columns.get(idx);
}
},
getSize: function getSize() {
var columns = this.state.columnMetrics.columns;
if (Array.isArray(columns)) {
return columns.length;
} else if (typeof Immutable !== 'undefined') {
return columns.size;
}
},
metricsUpdated: function metricsUpdated() {
var columnMetrics = this.createColumnMetrics();
this.setState({ columnMetrics: columnMetrics });
},
createColumnMetrics: function createColumnMetrics() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
var gridColumns = this.setupGridColumns(props);
return this.getColumnMetricsType({
columns: gridColumns,
minColumnWidth: this.props.minColumnWidth,
totalWidth: props.minWidth
});
},
onColumnResize: function onColumnResize(index, width) {
var columnMetrics = ColumnMetrics.resizeColumn(this.state.columnMetrics, index, width);
this.setState({ columnMetrics: columnMetrics });
if (this.props.onColumnResize) {
this.props.onColumnResize(index, width);
}
}
};
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var PropTypes = React.PropTypes;
var createObjectWithProperties = __webpack_require__(9);
// The list of the propTypes that we want to include in the Draggable div
var knownDivPropertyKeys = ['onDragStart', 'onDragEnd', 'onDrag', 'style'];
var Draggable = React.createClass({
displayName: 'Draggable',
propTypes: {
onDragStart: PropTypes.func,
onDragEnd: PropTypes.func,
onDrag: PropTypes.func,
component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor]),
style: PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
onDragStart: function onDragStart() {
return true;
},
onDragEnd: function onDragEnd() {},
onDrag: function onDrag() {}
};
},
getInitialState: function getInitialState() {
return {
drag: null
};
},
componentWillUnmount: function componentWillUnmount() {
this.cleanUp();
},
onMouseDown: function onMouseDown(e) {
var drag = this.props.onDragStart(e);
if (drag === null && e.button !== 0) {
return;
}
window.addEventListener('mouseup', this.onMouseUp);
window.addEventListener('mousemove', this.onMouseMove);
window.addEventListener('touchend', this.onMouseUp);
window.addEventListener('touchmove', this.onMouseMove);
this.setState({ drag: drag });
},
onMouseMove: function onMouseMove(e) {
if (this.state.drag === null) {
return;
}
if (e.preventDefault) {
e.preventDefault();
}
this.props.onDrag(e);
},
onMouseUp: function onMouseUp(e) {
this.cleanUp();
this.props.onDragEnd(e, this.state.drag);
this.setState({ drag: null });
},
cleanUp: function cleanUp() {
window.removeEventListener('mouseup', this.onMouseUp);
window.removeEventListener('mousemove', this.onMouseMove);
window.removeEventListener('touchend', this.onMouseUp);
window.removeEventListener('touchmove', this.onMouseMove);
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
render: function render() {
return React.createElement('div', _extends({}, this.getKnownDivProps(), {
onMouseDown: this.onMouseDown,
onTouchStart: this.onMouseDown,
className: 'react-grid-HeaderCell__draggable' }));
}
});
module.exports = Draggable;
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var PropTypes = React.PropTypes;
var Header = __webpack_require__(48);
var Viewport = __webpack_require__(60);
var GridScrollMixin = __webpack_require__(47);
var DOMMetrics = __webpack_require__(10);
var cellMetaDataShape = __webpack_require__(8);
var Grid = React.createClass({
displayName: 'Grid',
propTypes: {
rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired,
columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
columnMetrics: PropTypes.object,
minHeight: PropTypes.number,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
headerRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
rowHeight: PropTypes.number,
rowRenderer: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
emptyRowsView: PropTypes.func,
expandedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
selectedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
rowSelection: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]),
rowsCount: PropTypes.number,
onRows: PropTypes.func,
sortColumn: React.PropTypes.string,
sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']),
rowOffsetHeight: PropTypes.number.isRequired,
onViewportKeydown: PropTypes.func.isRequired,
onViewportKeyup: PropTypes.func,
onViewportDragStart: PropTypes.func.isRequired,
onViewportDragEnd: PropTypes.func.isRequired,
onViewportDoubleClick: PropTypes.func.isRequired,
onColumnResize: PropTypes.func,
onSort: PropTypes.func,
cellMetaData: PropTypes.shape(cellMetaDataShape),
rowKey: PropTypes.string.isRequired,
rowScrollTimeout: PropTypes.number,
contextMenu: PropTypes.element,
getSubRowDetails: PropTypes.func,
draggableHeaderCell: PropTypes.func,
getValidFilterValues: PropTypes.func,
rowGroupRenderer: PropTypes.func,
overScan: PropTypes.object
},
mixins: [GridScrollMixin, DOMMetrics.MetricsComputatorMixin],
getDefaultProps: function getDefaultProps() {
return {
rowHeight: 35,
minHeight: 350
};
},
getStyle: function getStyle() {
return {
overflow: 'hidden',
outline: 0,
position: 'relative',
minHeight: this.props.minHeight
};
},
render: function render() {
var headerRows = this.props.headerRows || [{ ref: 'row' }];
var EmptyRowsView = this.props.emptyRowsView;
return React.createElement(
'div',
{ style: this.getStyle(), className: 'react-grid-Grid' },
React.createElement(Header, {
ref: 'header',
columnMetrics: this.props.columnMetrics,
onColumnResize: this.props.onColumnResize,
height: this.props.rowHeight,
totalWidth: this.props.totalWidth,
headerRows: headerRows,
sortColumn: this.props.sortColumn,
sortDirection: this.props.sortDirection,
draggableHeaderCell: this.props.draggableHeaderCell,
onSort: this.props.onSort,
onScroll: this.onHeaderScroll,
getValidFilterValues: this.props.getValidFilterValues
}),
this.props.rowsCount >= 1 || this.props.rowsCount === 0 && !this.props.emptyRowsView ? React.createElement(
'div',
{ ref: 'viewPortContainer', tabIndex: '0', onKeyDown: this.props.onViewportKeydown, onKeyUp: this.props.onViewportKeyup, onDoubleClick: this.props.onViewportDoubleClick, onDragStart: this.props.onViewportDragStart, onDragEnd: this.props.onViewportDragEnd },
React.createElement(Viewport, {
ref: 'viewport',
rowKey: this.props.rowKey,
width: this.props.columnMetrics.width,
rowHeight: this.props.rowHeight,
rowRenderer: this.props.rowRenderer,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
selectedRows: this.props.selectedRows,
expandedRows: this.props.expandedRows,
columnMetrics: this.props.columnMetrics,
totalWidth: this.props.totalWidth,
onScroll: this.onScroll,
onRows: this.props.onRows,
cellMetaData: this.props.cellMetaData,
rowOffsetHeight: this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length,
minHeight: this.props.minHeight,
rowScrollTimeout: this.props.rowScrollTimeout,
contextMenu: this.props.contextMenu,
rowSelection: this.props.rowSelection,
getSubRowDetails: this.props.getSubRowDetails,
rowGroupRenderer: this.props.rowGroupRenderer,
overScan: this.props.overScan
})
) : React.createElement(
'div',
{ ref: 'emptyView', className: 'react-grid-Empty' },
React.createElement(EmptyRowsView, null)
)
);
}
});
module.exports = Grid;
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ReactDOM = __webpack_require__(2);
module.exports = {
componentDidMount: function componentDidMount() {
this._scrollLeft = this.refs.viewport ? this.refs.viewport.getScroll().scrollLeft : 0;
this._onScroll();
},
componentDidUpdate: function componentDidUpdate() {
this._onScroll();
},
componentWillMount: function componentWillMount() {
this._scrollLeft = undefined;
},
componentWillUnmount: function componentWillUnmount() {
this._scrollLeft = undefined;
},
onScroll: function onScroll(props) {
if (this._scrollLeft !== props.scrollLeft) {
this._scrollLeft = props.scrollLeft;
this._onScroll();
}
},
onHeaderScroll: function onHeaderScroll(e) {
var scrollLeft = e.target.scrollLeft;
if (this._scrollLeft !== scrollLeft) {
this._scrollLeft = scrollLeft;
this.refs.header.setScrollLeft(scrollLeft);
var canvas = ReactDOM.findDOMNode(this.refs.viewport.refs.canvas);
canvas.scrollLeft = scrollLeft;
this.refs.viewport.refs.canvas.setScrollLeft(scrollLeft);
}
},
_onScroll: function _onScroll() {
if (this._scrollLeft !== undefined) {
this.refs.header.setScrollLeft(this._scrollLeft);
if (this.refs.viewport) {
this.refs.viewport.setScrollLeft(this._scrollLeft);
}
}
}
};
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(5);
var shallowCloneObject = __webpack_require__(20);
var ColumnMetrics = __webpack_require__(17);
var ColumnUtils = __webpack_require__(4);
var HeaderRow = __webpack_require__(51);
var getScrollbarSize = __webpack_require__(19);
var PropTypes = React.PropTypes;
var createObjectWithProperties = __webpack_require__(9);
// The list of the propTypes that we want to include in the Header div
var knownDivPropertyKeys = ['height', 'onScroll'];
var Header = React.createClass({
displayName: 'Header',
propTypes: {
columnMetrics: PropTypes.shape({ width: PropTypes.number.isRequired, columns: PropTypes.any }).isRequired,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.number.isRequired,
headerRows: PropTypes.array.isRequired,
sortColumn: PropTypes.string,
sortDirection: PropTypes.oneOf(['ASC', 'DESC', 'NONE']),
onSort: PropTypes.func,
onColumnResize: PropTypes.func,
onScroll: PropTypes.func,
draggableHeaderCell: PropTypes.func,
getValidFilterValues: PropTypes.func
},
getInitialState: function getInitialState() {
return { resizing: null };
},
componentWillReceiveProps: function componentWillReceiveProps() {
this.setState({ resizing: null });
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
var update = !ColumnMetrics.sameColumns(this.props.columnMetrics.columns, nextProps.columnMetrics.columns, ColumnMetrics.sameColumn) || this.props.totalWidth !== nextProps.totalWidth || this.props.headerRows.length !== nextProps.headerRows.length || this.state.resizing !== nextState.resizing || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection;
return update;
},
onColumnResize: function onColumnResize(column, width) {
var state = this.state.resizing || this.props;
var pos = this.getColumnPosition(column);
if (pos != null) {
var _resizing = {
columnMetrics: shallowCloneObject(state.columnMetrics)
};
_resizing.columnMetrics = ColumnMetrics.resizeColumn(_resizing.columnMetrics, pos, width);
// we don't want to influence scrollLeft while resizing
if (_resizing.columnMetrics.totalWidth < state.columnMetrics.totalWidth) {
_resizing.columnMetrics.totalWidth = state.columnMetrics.totalWidth;
}
_resizing.column = ColumnUtils.getColumn(_resizing.columnMetrics.columns, pos);
this.setState({ resizing: _resizing });
}
},
onColumnResizeEnd: function onColumnResizeEnd(column, width) {
var pos = this.getColumnPosition(column);
if (pos !== null && this.props.onColumnResize) {
this.props.onColumnResize(pos, width || column.width);
}
},
getHeaderRows: function getHeaderRows() {
var _this = this;
var columnMetrics = this.getColumnMetrics();
var resizeColumn = void 0;
if (this.state.resizing) {
resizeColumn = this.state.resizing.column;
}
var headerRows = [];
this.props.headerRows.forEach(function (row, index) {
// To allow header filters to be visible
var rowHeight = 'auto';
if (row.rowType === 'filter') {
rowHeight = '500px';
}
var scrollbarSize = getScrollbarSize() > 0 ? getScrollbarSize() : 0;
var updatedWidth = isNaN(_this.props.totalWidth - scrollbarSize) ? _this.props.totalWidth : _this.props.totalWidth - scrollbarSize;
var headerRowStyle = {
position: 'absolute',
top: _this.getCombinedHeaderHeights(index),
left: 0,
width: updatedWidth,
overflowX: 'hidden',
minHeight: rowHeight
};
headerRows.push(React.createElement(HeaderRow, {
key: row.ref,
ref: row.ref,
rowType: row.rowType,
style: headerRowStyle,
onColumnResize: _this.onColumnResize,
onColumnResizeEnd: _this.onColumnResizeEnd,
width: columnMetrics.width,
height: row.height || _this.props.height,
columns: columnMetrics.columns,
resizing: resizeColumn,
draggableHeaderCell: _this.props.draggableHeaderCell,
filterable: row.filterable,
onFilterChange: row.onFilterChange,
sortColumn: _this.props.sortColumn,
sortDirection: _this.props.sortDirection,
onSort: _this.props.onSort,
onScroll: _this.props.onScroll,
getValidFilterValues: _this.props.getValidFilterValues
}));
});
return headerRows;
},
getColumnMetrics: function getColumnMetrics() {
var columnMetrics = void 0;
if (this.state.resizing) {
columnMetrics = this.state.resizing.columnMetrics;
} else {
columnMetrics = this.props.columnMetrics;
}
return columnMetrics;
},
getColumnPosition: function getColumnPosition(column) {
var columnMetrics = this.getColumnMetrics();
var pos = -1;
columnMetrics.columns.forEach(function (c, idx) {
if (c.key === column.key) {
pos = idx;
}
});
return pos === -1 ? null : pos;
},
getCombinedHeaderHeights: function getCombinedHeaderHeights(until) {
var stopAt = this.props.headerRows.length;
if (typeof until !== 'undefined') {
stopAt = until;
}
var height = 0;
for (var index = 0; index < stopAt; index++) {
height += this.props.headerRows[index].height || this.props.height;
}
return height;
},
getStyle: function getStyle() {
return {
position: 'relative',
height: this.getCombinedHeaderHeights()
};
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var node = ReactDOM.findDOMNode(this.refs.row);
node.scrollLeft = scrollLeft;
this.refs.row.setScrollLeft(scrollLeft);
if (this.refs.filterRow) {
var nodeFilters = ReactDOM.findDOMNode(this.refs.filterRow);
nodeFilters.scrollLeft = scrollLeft;
this.refs.filterRow.setScrollLeft(scrollLeft);
}
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
render: function render() {
var className = joinClasses({
'react-grid-Header': true,
'react-grid-Header--resizing': !!this.state.resizing
});
var headerRows = this.getHeaderRows();
return React.createElement(
'div',
_extends({}, this.getKnownDivProps(), { style: this.getStyle(), className: className }),
headerRows
);
}
});
module.exports = Header;
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(5);
var ExcelColumn = __webpack_require__(6);
var ResizeHandle = __webpack_require__(55);
var PropTypes = React.PropTypes;
function simpleCellRenderer(objArgs) {
return React.createElement(
'div',
{ className: 'widget-HeaderCell__value' },
objArgs.column.name
);
}
var HeaderCell = React.createClass({
displayName: 'HeaderCell',
propTypes: {
renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired,
column: PropTypes.shape(ExcelColumn).isRequired,
onResize: PropTypes.func.isRequired,
height: PropTypes.number.isRequired,
onResizeEnd: PropTypes.func.isRequired,
className: PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
renderer: simpleCellRenderer
};
},
getInitialState: function getInitialState() {
return { resizing: false };
},
onDragStart: function onDragStart(e) {
this.setState({ resizing: true });
// need to set dummy data for FF
if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy');
},
onDrag: function onDrag(e) {
var resize = this.props.onResize || null; // for flows sake, doesnt recognise a null check direct
if (resize) {
var _width = this.getWidthFromMouseEvent(e);
if (_width > 0) {
resize(this.props.column, _width);
}
}
},
onDragEnd: function onDragEnd(e) {
var width = this.getWidthFromMouseEvent(e);
this.props.onResizeEnd(this.props.column, width);
this.setState({ resizing: false });
},
getWidthFromMouseEvent: function getWidthFromMouseEvent(e) {
var right = e.pageX || e.touches && e.touches[0] && e.touches[0].pageX || e.changedTouches && e.changedTouches[e.changedTouches.length - 1].pageX;
var left = ReactDOM.findDOMNode(this).getBoundingClientRect().left;
return right - left;
},
getCell: function getCell() {
if (React.isValidElement(this.props.renderer)) {
// if it is a string, it's an HTML element, and column is not a valid property, so only pass height
if (typeof this.props.renderer.type === 'string') {
return React.cloneElement(this.props.renderer, { height: this.props.height });
}
return React.cloneElement(this.props.renderer, { column: this.props.column, height: this.props.height });
}
return this.props.renderer({ column: this.props.column });
},
getStyle: function getStyle() {
return {
width: this.props.column.width,
left: this.props.column.left,
display: 'inline-block',
position: 'absolute',
height: this.props.height,
margin: 0,
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
};
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var node = ReactDOM.findDOMNode(this);
node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
},
render: function render() {
var resizeHandle = void 0;
if (this.props.column.resizable) {
resizeHandle = React.createElement(ResizeHandle, {
onDrag: this.onDrag,
onDragStart: this.onDragStart,
onDragEnd: this.onDragEnd
});
}
var className = joinClasses({
'react-grid-HeaderCell': true,
'react-grid-HeaderCell--resizing': this.state.resizing,
'react-grid-HeaderCell--locked': this.props.column.locked
});
className = joinClasses(className, this.props.className, this.props.column.cellClass);
var cell = this.getCell();
return React.createElement(
'div',
{ className: className, style: this.getStyle() },
cell,
resizeHandle
);
}
});
module.exports = HeaderCell;
/***/ },
/* 50 */
/***/ function(module, exports) {
"use strict";
var HeaderCellType = {
SORTABLE: 0,
FILTERABLE: 1,
NONE: 2,
CHECKBOX: 3
};
module.exports = HeaderCellType;
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var shallowEqual = __webpack_require__(28);
var BaseHeaderCell = __webpack_require__(49);
var getScrollbarSize = __webpack_require__(19);
var ExcelColumn = __webpack_require__(6);
var ColumnUtilsMixin = __webpack_require__(4);
var SortableHeaderCell = __webpack_require__(63);
var FilterableHeaderCell = __webpack_require__(62);
var HeaderCellType = __webpack_require__(50);
var createObjectWithProperties = __webpack_require__(9);
var PropTypes = React.PropTypes;
var HeaderRowStyle = {
overflow: React.PropTypes.string,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: React.PropTypes.number,
position: React.PropTypes.string
};
// The list of the propTypes that we want to include in the HeaderRow div
var knownDivPropertyKeys = ['width', 'height', 'style', 'onScroll'];
var HeaderRow = React.createClass({
displayName: 'HeaderRow',
propTypes: {
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.number.isRequired,
columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired,
onColumnResize: PropTypes.func,
onSort: PropTypes.func.isRequired,
onColumnResizeEnd: PropTypes.func,
style: PropTypes.shape(HeaderRowStyle),
sortColumn: PropTypes.string,
sortDirection: React.PropTypes.oneOf(SortableHeaderCell.DEFINE_SORT),
cellRenderer: PropTypes.func,
headerCellRenderer: PropTypes.func,
filterable: PropTypes.bool,
onFilterChange: PropTypes.func,
resizing: PropTypes.object,
onScroll: PropTypes.func,
rowType: PropTypes.string,
draggableHeaderCell: PropTypes.func
},
mixins: [ColumnUtilsMixin],
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return nextProps.width !== this.props.width || nextProps.height !== this.props.height || nextProps.columns !== this.props.columns || !shallowEqual(nextProps.style, this.props.style) || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection;
},
getHeaderCellType: function getHeaderCellType(column) {
if (column.filterable) {
if (this.props.filterable) return HeaderCellType.FILTERABLE;
}
if (column.sortable) return HeaderCellType.SORTABLE;
return HeaderCellType.NONE;
},
getFilterableHeaderCell: function getFilterableHeaderCell(column) {
var FilterRenderer = FilterableHeaderCell;
if (column.filterRenderer !== undefined) {
FilterRenderer = column.filterRenderer;
}
return React.createElement(FilterRenderer, _extends({}, this.props, { onChange: this.props.onFilterChange }));
},
getSortableHeaderCell: function getSortableHeaderCell(column) {
var sortDirection = this.props.sortColumn === column.key ? this.props.sortDirection : SortableHeaderCell.DEFINE_SORT.NONE;
return React.createElement(SortableHeaderCell, { columnKey: column.key, onSort: this.props.onSort, sortDirection: sortDirection });
},
getHeaderRenderer: function getHeaderRenderer(column) {
var renderer = void 0;
if (column.headerRenderer) {
renderer = column.headerRenderer;
} else {
var headerCellType = this.getHeaderCellType(column);
switch (headerCellType) {
case HeaderCellType.SORTABLE:
renderer = this.getSortableHeaderCell(column);
break;
case HeaderCellType.FILTERABLE:
renderer = this.getFilterableHeaderCell(column);
break;
default:
break;
}
}
return renderer;
},
getStyle: function getStyle() {
return {
overflow: 'hidden',
width: '100%',
height: this.props.height,
position: 'absolute'
};
},
getCells: function getCells() {
var cells = [];
var lockedCells = [];
for (var i = 0, len = this.getSize(this.props.columns); i < len; i++) {
var column = this.getColumn(this.props.columns, i);
var _renderer = this.getHeaderRenderer(column);
if (column.key === 'select-row' && this.props.rowType === 'filter') {
_renderer = React.createElement('div', null);
}
var _HeaderCell = column.draggable ? this.props.draggableHeaderCell : BaseHeaderCell;
var cell = React.createElement(_HeaderCell, {
ref: i,
key: i,
height: this.props.height,
column: column,
renderer: _renderer,
resizing: this.props.resizing === column,
onResize: this.props.onColumnResize,
onResizeEnd: this.props.onColumnResizeEnd
});
if (column.locked) {
lockedCells.push(cell);
} else {
cells.push(cell);
}
}
return cells.concat(lockedCells);
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var _this = this;
this.props.columns.forEach(function (column, i) {
if (column.locked) {
_this.refs[i].setScrollLeft(scrollLeft);
}
});
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
render: function render() {
var cellsStyle = {
width: this.props.width ? this.props.width + getScrollbarSize() : '100%',
height: this.props.height,
whiteSpace: 'nowrap',
overflowX: 'hidden',
overflowY: 'hidden'
};
var cells = this.getCells();
return React.createElement(
'div',
_extends({}, this.getKnownDivProps(), { className: 'react-grid-HeaderRow' }),
React.createElement(
'div',
{ style: cellsStyle },
cells
)
);
}
});
module.exports = HeaderRow;
/***/ },
/* 52 */
/***/ function(module, exports) {
"use strict";
module.exports = {
Backspace: 8,
Tab: 9,
Enter: 13,
Shift: 16,
Ctrl: 17,
Alt: 18,
PauseBreak: 19,
CapsLock: 20,
Escape: 27,
PageUp: 33,
PageDown: 34,
End: 35,
Home: 36,
LeftArrow: 37,
UpArrow: 38,
RightArrow: 39,
DownArrow: 40,
Insert: 45,
Delete: 46,
0: 48,
1: 49,
2: 50,
3: 51,
4: 52,
5: 53,
6: 54,
7: 55,
8: 56,
9: 57,
a: 65,
b: 66,
c: 67,
d: 68,
e: 69,
f: 70,
g: 71,
h: 72,
i: 73,
j: 74,
k: 75,
l: 76,
m: 77,
n: 78,
o: 79,
p: 80,
q: 81,
r: 82,
s: 83,
t: 84,
u: 85,
v: 86,
w: 87,
x: 88,
y: 89,
z: 90,
LeftWindowKey: 91,
RightWindowKey: 92,
SelectKey: 93,
NumPad0: 96,
NumPad1: 97,
NumPad2: 98,
NumPad3: 99,
NumPad4: 100,
NumPad5: 101,
NumPad6: 102,
NumPad7: 103,
NumPad8: 104,
NumPad9: 105,
Multiply: 106,
Add: 107,
Subtract: 109,
DecimalPoint: 110,
Divide: 111,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F12: 123,
NumLock: 144,
ScrollLock: 145,
SemiColon: 186,
EqualSign: 187,
Comma: 188,
Dash: 189,
Period: 190,
ForwardSlash: 191,
GraveAccent: 192,
OpenBracket: 219,
BackSlash: 220,
CloseBracket: 221,
SingleQuote: 222
};
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.OverflowCellComponent = undefined;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _focusableComponentWrapper = __webpack_require__(69);
var _focusableComponentWrapper2 = _interopRequireDefault(_focusableComponentWrapper);
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 OverflowCell = function (_React$Component) {
_inherits(OverflowCell, _React$Component);
function OverflowCell() {
_classCallCheck(this, OverflowCell);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
OverflowCell.prototype.getStyle = function getStyle() {
var style = {
position: 'absolute',
width: this.props.column.width,
height: this.props.height,
left: this.props.column.left,
border: '1px solid #eee'
};
return style;
};
OverflowCell.prototype.render = function render() {
return _react2['default'].createElement('div', { tabIndex: '-1', style: this.getStyle(), width: '100%', className: 'react-grid-Cell' });
};
return OverflowCell;
}(_react2['default'].Component);
OverflowCell.isSelected = function (props) {
var cellMetaData = props.cellMetaData,
rowIdx = props.rowIdx,
idx = props.idx;
if (cellMetaData == null) {
return false;
}
var selected = cellMetaData.selected;
return selected && selected.rowIdx === rowIdx && selected.idx === idx;
};
OverflowCell.isScrolling = function (props) {
return props.cellMetaData.isScrollingHorizontallyWithKeyboard;
};
OverflowCell.propTypes = {
rowIdx: _react2['default'].PropTypes.number,
idx: _react2['default'].PropTypes.number,
height: _react2['default'].PropTypes.number,
column: _react2['default'].PropTypes.object,
cellMetaData: _react2['default'].PropTypes.object
};
OverflowCell.displayName = 'Cell';
var OverflowCellComponent = OverflowCell;
exports['default'] = (0, _focusableComponentWrapper2['default'])(OverflowCell);
exports.OverflowCellComponent = OverflowCellComponent;
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _AppConstants = __webpack_require__(41);
var _AppConstants2 = _interopRequireDefault(_AppConstants);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var BaseGrid = __webpack_require__(46);
var Row = __webpack_require__(18);
var ExcelColumn = __webpack_require__(6);
var KeyboardHandlerMixin = __webpack_require__(25);
var CheckboxEditor = __webpack_require__(64);
var DOMMetrics = __webpack_require__(10);
var ColumnMetricsMixin = __webpack_require__(44);
var RowUtils = __webpack_require__(26);
var ColumnUtils = __webpack_require__(4);
var KeyCodes = __webpack_require__(52);
if (!Object.assign) {
Object.assign = __webpack_require__(39);
}
var ReactDataGrid = React.createClass({
displayName: 'ReactDataGrid',
mixins: [ColumnMetricsMixin, DOMMetrics.MetricsComputatorMixin, KeyboardHandlerMixin],
propTypes: {
rowHeight: React.PropTypes.number.isRequired,
headerRowHeight: React.PropTypes.number,
minHeight: React.PropTypes.number.isRequired,
minWidth: React.PropTypes.number,
enableRowSelect: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.string]),
onRowUpdated: React.PropTypes.func,
rowGetter: React.PropTypes.func.isRequired,
rowsCount: React.PropTypes.number.isRequired,
toolbar: React.PropTypes.element,
enableCellSelect: React.PropTypes.bool,
columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired,
onFilter: React.PropTypes.func,
onCellCopyPaste: React.PropTypes.func,
onCellsDragged: React.PropTypes.func,
onAddFilter: React.PropTypes.func,
onGridSort: React.PropTypes.func,
onDragHandleDoubleClick: React.PropTypes.func,
onGridRowsUpdated: React.PropTypes.func,
onRowSelect: React.PropTypes.func,
rowKey: React.PropTypes.string,
rowScrollTimeout: React.PropTypes.number,
onClearFilters: React.PropTypes.func,
contextMenu: React.PropTypes.element,
cellNavigationMode: React.PropTypes.oneOf(['none', 'loopOverRow', 'changeRow']),
onCellSelected: React.PropTypes.func,
onCellDeSelected: React.PropTypes.func,
onCellExpand: React.PropTypes.func,
enableDragAndDrop: React.PropTypes.bool,
onRowExpandToggle: React.PropTypes.func,
draggableHeaderCell: React.PropTypes.func,
getValidFilterValues: React.PropTypes.func,
rowSelection: React.PropTypes.shape({
enableShiftSelect: React.PropTypes.bool,
onRowsSelected: React.PropTypes.func,
onRowsDeselected: React.PropTypes.func,
showCheckbox: React.PropTypes.bool,
selectBy: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]).isRequired
}),
onRowClick: React.PropTypes.func,
onGridKeyUp: React.PropTypes.func,
onGridKeyDown: React.PropTypes.func,
rowGroupRenderer: React.PropTypes.func,
rowActionsCell: React.PropTypes.func,
onCheckCellIsEditable: React.PropTypes.func,
/* called before cell is set active, returns a boolean to determine whether cell is editable */
overScan: React.PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
enableCellSelect: false,
tabIndex: -1,
rowHeight: 35,
enableRowSelect: false,
minHeight: 350,
rowKey: 'id',
rowScrollTimeout: 0,
cellNavigationMode: 'none',
overScan: {
colsStart: 5,
colsEnd: 5,
rowsStart: 5,
rowsEnd: 5
}
};
},
getInitialState: function getInitialState() {
var columnMetrics = this.createColumnMetrics();
var initialState = { columnMetrics: columnMetrics, selectedRows: [], copied: null, expandedRows: [], canFilter: false, columnFilters: {}, sortDirection: null, sortColumn: null, dragged: null, scrollOffset: 0, lastRowIdxUiSelected: -1 };
if (this.props.enableCellSelect) {
initialState.selected = { rowIdx: 0, idx: 0 };
} else {
initialState.selected = { rowIdx: -1, idx: -1 };
}
return initialState;
},
hasSelectedCellChanged: function hasSelectedCellChanged(selected) {
var previouslySelected = Object.assign({}, this.state.selected);
return previouslySelected.rowIdx !== selected.rowIdx || previouslySelected.idx !== selected.idx || previouslySelected.active === false;
},
onContextMenuHide: function onContextMenuHide() {
document.removeEventListener('click', this.onContextMenuHide);
var newSelected = Object.assign({}, this.state.selected, { contextMenuDisplayed: false });
this.setState({ selected: newSelected });
},
onColumnEvent: function onColumnEvent(ev, columnEvent) {
var idx = columnEvent.idx,
name = columnEvent.name;
if (name && typeof idx !== 'undefined') {
var column = this.getColumn(idx);
if (column && column.events && column.events[name] && typeof column.events[name] === 'function') {
var eventArgs = {
rowIdx: columnEvent.rowIdx,
idx: idx,
column: column
};
column.events[name](ev, eventArgs);
}
}
},
onSelect: function onSelect(selected) {
var _this = this;
if (this.state.selected.rowIdx !== selected.rowIdx || this.state.selected.idx !== selected.idx || this.state.selected.active === false) {
var _idx = selected.idx;
var _rowIdx = selected.rowIdx;
if (_idx >= 0 && _rowIdx >= 0 && _idx < ColumnUtils.getSize(this.state.columnMetrics.columns) && _rowIdx < this.props.rowsCount) {
(function () {
var oldSelection = _this.state.selected;
_this.setState({ selected: selected }, function () {
if (typeof _this.props.onCellDeSelected === 'function') {
_this.props.onCellDeSelected(oldSelection);
}
if (typeof _this.props.onCellSelected === 'function') {
_this.props.onCellSelected(selected);
}
});
})();
}
}
},
onCellClick: function onCellClick(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx });
if (this.props.onRowClick && typeof this.props.onRowClick === 'function') {
this.props.onRowClick(cell.rowIdx, this.props.rowGetter(cell.rowIdx));
}
},
onCellContextMenu: function onCellContextMenu(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx, contextMenuDisplayed: this.props.contextMenu });
if (this.props.contextMenu) {
document.addEventListener('click', this.onContextMenuHide);
}
},
onCellDoubleClick: function onCellDoubleClick(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx });
this.setActive('Enter');
},
onViewportDoubleClick: function onViewportDoubleClick() {
this.setActive();
},
onPressArrowUp: function onPressArrowUp(e) {
this.moveSelectedCell(e, -1, 0);
},
onPressArrowDown: function onPressArrowDown(e) {
this.moveSelectedCell(e, 1, 0);
},
onPressArrowLeft: function onPressArrowLeft(e) {
this.moveSelectedCell(e, 0, -1);
},
onPressArrowRight: function onPressArrowRight(e) {
this.moveSelectedCell(e, 0, 1);
},
onPressTab: function onPressTab(e) {
this.moveSelectedCell(e, 0, e.shiftKey ? -1 : 1);
},
onPressEnter: function onPressEnter(e) {
this.setActive(e.key);
},
onPressDelete: function onPressDelete(e) {
this.setActive(e.key);
},
onPressEscape: function onPressEscape(e) {
this.setInactive(e.key);
this.handleCancelCopy();
},
onPressBackspace: function onPressBackspace(e) {
this.setActive(e.key);
},
onPressChar: function onPressChar(e) {
if (this.isKeyPrintable(e.keyCode)) {
this.setActive(e.keyCode);
}
},
onPressKeyWithCtrl: function onPressKeyWithCtrl(e) {
var keys = {
KeyCode_c: 99,
KeyCode_C: 67,
KeyCode_V: 86,
KeyCode_v: 118
};
var rowIdx = this.state.selected.rowIdx;
var row = this.props.rowGetter(rowIdx);
var idx = this.state.selected.idx;
var col = this.getColumn(idx);
if (ColumnUtils.canEdit(col, row, this.props.enableCellSelect)) {
if (e.keyCode === keys.KeyCode_c || e.keyCode === keys.KeyCode_C) {
var _value = this.getSelectedValue();
this.handleCopy({ value: _value });
} else if (e.keyCode === keys.KeyCode_v || e.keyCode === keys.KeyCode_V) {
this.handlePaste();
}
}
},
onGridRowsUpdated: function onGridRowsUpdated(cellKey, fromRow, toRow, updated, action) {
var rowIds = [];
for (var i = fromRow; i <= toRow; i++) {
rowIds.push(this.props.rowGetter(i)[this.props.rowKey]);
}
this.props.onGridRowsUpdated({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, rowIds: rowIds, updated: updated, action: action });
},
onCellCommit: function onCellCommit(commit) {
var selected = Object.assign({}, this.state.selected);
selected.active = false;
if (commit.key === 'Tab') {
selected.idx += 1;
}
var expandedRows = this.state.expandedRows;
// if(commit.changed && commit.changed.expandedHeight){
// expandedRows = this.expandRow(commit.rowIdx, commit.changed.expandedHeight);
// }
this.setState({ selected: selected, expandedRows: expandedRows });
if (this.props.onRowUpdated) {
this.props.onRowUpdated(commit);
}
var targetRow = commit.rowIdx;
if (this.props.onGridRowsUpdated) {
this.onGridRowsUpdated(commit.cellKey, targetRow, targetRow, commit.updated, _AppConstants2['default'].UpdateActions.CELL_UPDATE);
}
},
onDragStart: function onDragStart(e) {
var idx = this.state.selected.idx;
if (idx > -1) {
var _value2 = this.getSelectedValue();
this.handleDragStart({ idx: this.state.selected.idx, rowIdx: this.state.selected.rowIdx, value: _value2 });
// need to set dummy data for FF
if (e && e.dataTransfer) {
if (e.dataTransfer.setData) {
e.dataTransfer.dropEffect = 'move';
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', 'dummy');
}
}
}
},
onToggleFilter: function onToggleFilter() {
var _this2 = this;
// setState() does not immediately mutate this.state but creates a pending state transition.
// Therefore if you want to do something after the state change occurs, pass it in as a callback function.
this.setState({ canFilter: !this.state.canFilter }, function () {
if (_this2.state.canFilter === false && _this2.props.onClearFilters) {
_this2.props.onClearFilters();
}
});
},
onDragHandleDoubleClick: function onDragHandleDoubleClick(e) {
if (this.props.onDragHandleDoubleClick) {
this.props.onDragHandleDoubleClick(e);
}
if (this.props.onGridRowsUpdated) {
var _onGridRowsUpdated;
var cellKey = this.getColumn(e.idx).key;
this.onGridRowsUpdated(cellKey, e.rowIdx, this.props.rowsCount - 1, (_onGridRowsUpdated = {}, _onGridRowsUpdated[cellKey] = e.rowData[cellKey], _onGridRowsUpdated), _AppConstants2['default'].UpdateActions.COLUMN_FILL);
}
},
onCellExpand: function onCellExpand(args) {
if (this.props.onCellExpand) {
this.props.onCellExpand(args);
}
},
onRowExpandToggle: function onRowExpandToggle(args) {
if (typeof this.props.onRowExpandToggle === 'function') {
this.props.onRowExpandToggle(args);
}
},
handleDragStart: function handleDragStart(dragged) {
if (!this.dragEnabled()) {
return;
}
var idx = dragged.idx;
var rowIdx = dragged.rowIdx;
if (idx >= 0 && rowIdx >= 0 && idx < this.getSize() && rowIdx < this.props.rowsCount) {
this.setState({ dragged: dragged });
}
},
handleDragEnd: function handleDragEnd() {
if (!this.dragEnabled()) {
return;
}
var selected = this.state.selected;
var dragged = this.state.dragged;
var cellKey = this.getColumn(this.state.selected.idx).key;
var fromRow = selected.rowIdx < dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx;
var toRow = selected.rowIdx > dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx;
if (this.props.onCellsDragged) {
this.props.onCellsDragged({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, value: dragged.value });
}
if (this.props.onGridRowsUpdated) {
var _onGridRowsUpdated2;
this.onGridRowsUpdated(cellKey, fromRow, toRow, (_onGridRowsUpdated2 = {}, _onGridRowsUpdated2[cellKey] = dragged.value, _onGridRowsUpdated2), _AppConstants2['default'].UpdateActions.CELL_DRAG);
}
this.setState({ dragged: { complete: true } });
},
handleDragEnter: function handleDragEnter(row) {
if (!this.dragEnabled() || this.state.dragged == null) {
return;
}
var dragged = this.state.dragged;
dragged.overRowIdx = row;
this.setState({ dragged: dragged });
},
handleTerminateDrag: function handleTerminateDrag() {
if (!this.dragEnabled()) {
return;
}
this.setState({ dragged: null });
},
handlePaste: function handlePaste() {
if (!this.copyPasteEnabled() || !this.state.copied) {
return;
}
var selected = this.state.selected;
var cellKey = this.getColumn(this.state.selected.idx).key;
var textToCopy = this.state.textToCopy;
var fromRow = this.state.copied.rowIdx;
var toRow = selected.rowIdx;
if (this.props.onCellCopyPaste) {
this.props.onCellCopyPaste({ cellKey: cellKey, rowIdx: toRow, value: textToCopy, fromRow: fromRow, toRow: toRow });
}
if (this.props.onGridRowsUpdated) {
var _onGridRowsUpdated3;
this.onGridRowsUpdated(cellKey, toRow, toRow, (_onGridRowsUpdated3 = {}, _onGridRowsUpdated3[cellKey] = textToCopy, _onGridRowsUpdated3), _AppConstants2['default'].UpdateActions.COPY_PASTE);
}
},
handleCancelCopy: function handleCancelCopy() {
this.setState({ copied: null });
},
handleCopy: function handleCopy(args) {
if (!this.copyPasteEnabled()) {
return;
}
var textToCopy = args.value;
var selected = this.state.selected;
var copied = { idx: selected.idx, rowIdx: selected.rowIdx };
this.setState({ textToCopy: textToCopy, copied: copied });
},
handleSort: function handleSort(columnKey, direction) {
this.setState({ sortDirection: direction, sortColumn: columnKey }, function () {
this.props.onGridSort(columnKey, direction);
});
},
getSelectedRow: function getSelectedRow(rows, key) {
var _this3 = this;
var selectedRow = rows.filter(function (r) {
if (r[_this3.props.rowKey] === key) {
return true;
}
return false;
});
if (selectedRow.length > 0) {
return selectedRow[0];
}
},
useNewRowSelection: function useNewRowSelection() {
return this.props.rowSelection && this.props.rowSelection.selectBy;
},
// return false if not a shift select so can be handled as normal row selection
handleShiftSelect: function handleShiftSelect(rowIdx) {
if (this.state.lastRowIdxUiSelected > -1 && this.isSingleKeyDown(KeyCodes.Shift)) {
var _props$rowSelection$s = this.props.rowSelection.selectBy,
keys = _props$rowSelection$s.keys,
indexes = _props$rowSelection$s.indexes,
isSelectedKey = _props$rowSelection$s.isSelectedKey;
var isPreviouslySelected = RowUtils.isRowSelected(keys, indexes, isSelectedKey, this.props.rowGetter(rowIdx), rowIdx);
if (isPreviouslySelected) return false;
var handled = false;
if (rowIdx > this.state.lastRowIdxUiSelected) {
var rowsSelected = [];
for (var i = this.state.lastRowIdxUiSelected + 1; i <= rowIdx; i++) {
rowsSelected.push({ rowIdx: i, row: this.props.rowGetter(i) });
}
if (typeof this.props.rowSelection.onRowsSelected === 'function') {
this.props.rowSelection.onRowsSelected(rowsSelected);
}
handled = true;
} else if (rowIdx < this.state.lastRowIdxUiSelected) {
var _rowsSelected = [];
for (var _i = rowIdx; _i <= this.state.lastRowIdxUiSelected - 1; _i++) {
_rowsSelected.push({ rowIdx: _i, row: this.props.rowGetter(_i) });
}
if (typeof this.props.rowSelection.onRowsSelected === 'function') {
this.props.rowSelection.onRowsSelected(_rowsSelected);
}
handled = true;
}
if (handled) {
this.setState({ lastRowIdxUiSelected: rowIdx });
}
return handled;
}
return false;
},
handleNewRowSelect: function handleNewRowSelect(rowIdx, rowData) {
var _props$rowSelection$s2 = this.props.rowSelection.selectBy,
keys = _props$rowSelection$s2.keys,
indexes = _props$rowSelection$s2.indexes,
isSelectedKey = _props$rowSelection$s2.isSelectedKey;
var isPreviouslySelected = RowUtils.isRowSelected(keys, indexes, isSelectedKey, rowData, rowIdx);
this.setState({ lastRowIdxUiSelected: isPreviouslySelected ? -1 : rowIdx, selected: { rowIdx: rowIdx, idx: 0 } });
if (isPreviouslySelected && typeof this.props.rowSelection.onRowsDeselected === 'function') {
this.props.rowSelection.onRowsDeselected([{ rowIdx: rowIdx, row: rowData }]);
} else if (!isPreviouslySelected && typeof this.props.rowSelection.onRowsSelected === 'function') {
this.props.rowSelection.onRowsSelected([{ rowIdx: rowIdx, row: rowData }]);
}
},
// columnKey not used here as this function will select the whole row,
// but needed to match the function signature in the CheckboxEditor
handleRowSelect: function handleRowSelect(rowIdx, columnKey, rowData, e) {
e.stopPropagation();
if (this.useNewRowSelection()) {
if (this.props.rowSelection.enableShiftSelect === true) {
if (!this.handleShiftSelect(rowIdx)) {
this.handleNewRowSelect(rowIdx, rowData);
}
} else {
this.handleNewRowSelect(rowIdx, rowData);
}
} else {
// Fallback to old onRowSelect handler
var _selectedRows = this.props.enableRowSelect === 'single' ? [] : this.state.selectedRows.slice(0);
var selectedRow = this.getSelectedRow(_selectedRows, rowData[this.props.rowKey]);
if (selectedRow) {
selectedRow.isSelected = !selectedRow.isSelected;
} else {
rowData.isSelected = true;
_selectedRows.push(rowData);
}
this.setState({ selectedRows: _selectedRows, selected: { rowIdx: rowIdx, idx: 0 } });
if (this.props.onRowSelect) {
this.props.onRowSelect(_selectedRows.filter(function (r) {
return r.isSelected === true;
}));
}
}
},
handleCheckboxChange: function handleCheckboxChange(e) {
var allRowsSelected = void 0;
if (e.currentTarget instanceof HTMLInputElement && e.currentTarget.checked === true) {
allRowsSelected = true;
} else {
allRowsSelected = false;
}
if (this.useNewRowSelection()) {
var _props$rowSelection$s3 = this.props.rowSelection.selectBy,
keys = _props$rowSelection$s3.keys,
indexes = _props$rowSelection$s3.indexes,
isSelectedKey = _props$rowSelection$s3.isSelectedKey;
if (allRowsSelected && typeof this.props.rowSelection.onRowsSelected === 'function') {
var _selectedRows2 = [];
for (var i = 0; i < this.props.rowsCount; i++) {
var rowData = this.props.rowGetter(i);
if (!RowUtils.isRowSelected(keys, indexes, isSelectedKey, rowData, i)) {
_selectedRows2.push({ rowIdx: i, row: rowData });
}
}
if (_selectedRows2.length > 0) {
this.props.rowSelection.onRowsSelected(_selectedRows2);
}
} else if (!allRowsSelected && typeof this.props.rowSelection.onRowsDeselected === 'function') {
var deselectedRows = [];
for (var _i2 = 0; _i2 < this.props.rowsCount; _i2++) {
var _rowData = this.props.rowGetter(_i2);
if (RowUtils.isRowSelected(keys, indexes, isSelectedKey, _rowData, _i2)) {
deselectedRows.push({ rowIdx: _i2, row: _rowData });
}
}
if (deselectedRows.length > 0) {
this.props.rowSelection.onRowsDeselected(deselectedRows);
}
}
} else {
var _selectedRows3 = [];
for (var _i3 = 0; _i3 < this.props.rowsCount; _i3++) {
var row = Object.assign({}, this.props.rowGetter(_i3), { isSelected: allRowsSelected });
_selectedRows3.push(row);
}
this.setState({ selectedRows: _selectedRows3 });
if (typeof this.props.onRowSelect === 'function') {
this.props.onRowSelect(_selectedRows3.filter(function (r) {
return r.isSelected === true;
}));
}
}
},
getScrollOffSet: function getScrollOffSet() {
var scrollOffset = 0;
var canvas = ReactDOM.findDOMNode(this).querySelector('.react-grid-Canvas');
if (canvas) {
scrollOffset = canvas.offsetWidth - canvas.clientWidth;
}
this.setState({ scrollOffset: scrollOffset });
},
getRowOffsetHeight: function getRowOffsetHeight() {
var offsetHeight = 0;
this.getHeaderRows().forEach(function (row) {
return offsetHeight += parseFloat(row.height, 10);
});
return offsetHeight;
},
getHeaderRows: function getHeaderRows() {
var rows = [{ ref: 'row', height: this.props.headerRowHeight || this.props.rowHeight, rowType: 'header' }];
if (this.state.canFilter === true) {
rows.push({
ref: 'filterRow',
filterable: true,
onFilterChange: this.props.onAddFilter,
height: 45,
rowType: 'filter'
});
}
return rows;
},
getInitialSelectedRows: function getInitialSelectedRows() {
var selectedRows = [];
for (var i = 0; i < this.props.rowsCount; i++) {
selectedRows.push(false);
}
return selectedRows;
},
getRowSelectionProps: function getRowSelectionProps() {
if (this.props.rowSelection) {
return this.props.rowSelection.selectBy;
}
return null;
},
getSelectedRows: function getSelectedRows() {
if (this.props.rowSelection) {
return null;
}
return this.state.selectedRows.filter(function (r) {
return r.isSelected === true;
});
},
getSelectedValue: function getSelectedValue() {
var rowIdx = this.state.selected.rowIdx;
var idx = this.state.selected.idx;
var cellKey = this.getColumn(idx).key;
var row = this.props.rowGetter(rowIdx);
return RowUtils.get(row, cellKey);
},
moveSelectedCell: function moveSelectedCell(e, rowDelta, cellDelta) {
// we need to prevent default as we control grid scroll
// otherwise it moves every time you left/right which is janky
e.preventDefault();
var rowIdx = void 0;
var idx = void 0;
var cellNavigationMode = this.props.cellNavigationMode;
if (cellNavigationMode !== 'none') {
var _calculateNextSelecti = this.calculateNextSelectionPosition(cellNavigationMode, cellDelta, rowDelta);
idx = _calculateNextSelecti.idx;
rowIdx = _calculateNextSelecti.rowIdx;
} else {
rowIdx = this.state.selected.rowIdx + rowDelta;
idx = this.state.selected.idx + cellDelta;
}
this.onSelect({ idx: idx, rowIdx: rowIdx });
},
getNbrColumns: function getNbrColumns() {
var _props = this.props,
columns = _props.columns,
enableRowSelect = _props.enableRowSelect;
return enableRowSelect ? columns.length + 1 : columns.length;
},
getDataGridDOMNode: function getDataGridDOMNode() {
if (!this._gridNode) {
this._gridNode = ReactDOM.findDOMNode(this);
}
return this._gridNode;
},
calculateNextSelectionPosition: function calculateNextSelectionPosition(cellNavigationMode, cellDelta, rowDelta) {
var _rowDelta = rowDelta;
var idx = this.state.selected.idx + cellDelta;
var nbrColumns = this.getNbrColumns();
if (cellDelta > 0) {
if (this.isAtLastCellInRow(nbrColumns)) {
if (cellNavigationMode === 'changeRow') {
_rowDelta = this.isAtLastRow() ? rowDelta : rowDelta + 1;
idx = this.isAtLastRow() ? idx : 0;
} else {
idx = 0;
}
}
} else if (cellDelta < 0) {
if (this.isAtFirstCellInRow()) {
if (cellNavigationMode === 'changeRow') {
_rowDelta = this.isAtFirstRow() ? rowDelta : rowDelta - 1;
idx = this.isAtFirstRow() ? 0 : nbrColumns - 1;
} else {
idx = nbrColumns - 1;
}
}
}
var rowIdx = this.state.selected.rowIdx + _rowDelta;
return { idx: idx, rowIdx: rowIdx };
},
isAtLastCellInRow: function isAtLastCellInRow(nbrColumns) {
return this.state.selected.idx === nbrColumns - 1;
},
isAtLastRow: function isAtLastRow() {
return this.state.selected.rowIdx === this.props.rowsCount - 1;
},
isAtFirstCellInRow: function isAtFirstCellInRow() {
return this.state.selected.idx === 0;
},
isAtFirstRow: function isAtFirstRow() {
return this.state.selected.rowIdx === 0;
},
openCellEditor: function openCellEditor(rowIdx, idx) {
var _this4 = this;
var row = this.props.rowGetter(rowIdx);
var col = this.getColumn(idx);
if (!ColumnUtils.canEdit(col, row, this.props.enableCellSelect)) {
return;
}
var selected = { rowIdx: rowIdx, idx: idx };
if (this.hasSelectedCellChanged(selected)) {
this.setState({ selected: selected }, function () {
_this4.setActive('Enter');
});
} else {
this.setActive('Enter');
}
},
scrollToColumn: function scrollToColumn(colIdx) {
var canvas = ReactDOM.findDOMNode(this).querySelector('.react-grid-Canvas');
if (canvas) {
var left = 0;
var locked = 0;
for (var i = 0; i < colIdx; i++) {
var column = this.getColumn(i);
if (column) {
if (column.width) {
left += column.width;
}
if (column.locked) {
locked += column.width;
}
}
}
var selectedColumn = this.getColumn(colIdx);
if (selectedColumn) {
var scrollLeft = left - locked - canvas.scrollLeft;
var scrollRight = left + selectedColumn.width - canvas.scrollLeft;
if (scrollLeft < 0) {
canvas.scrollLeft += scrollLeft;
} else if (scrollRight > canvas.clientWidth) {
var scrollAmount = scrollRight - canvas.clientWidth;
canvas.scrollLeft += scrollAmount;
}
}
}
},
setActive: function setActive(keyPressed) {
var rowIdx = this.state.selected.rowIdx;
var row = this.props.rowGetter(rowIdx);
var idx = this.state.selected.idx;
var column = this.getColumn(idx);
if (ColumnUtils.canEdit(column, row, this.props.enableCellSelect) && !this.isActive()) {
var _selected = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: true, initialKeyCode: keyPressed });
var showEditor = true;
if (typeof this.props.onCheckCellIsEditable === 'function') {
var args = Object.assign({}, { row: row, column: column }, _selected);
showEditor = this.props.onCheckCellIsEditable(args);
}
if (showEditor !== false) {
this.setState({ selected: _selected }, this.scrollToColumn(idx));
this.handleCancelCopy();
}
}
},
setInactive: function setInactive() {
var rowIdx = this.state.selected.rowIdx;
var row = this.props.rowGetter(rowIdx);
var idx = this.state.selected.idx;
var col = this.getColumn(idx);
if (ColumnUtils.canEdit(col, row, this.props.enableCellSelect) && this.isActive()) {
var _selected2 = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: false });
this.setState({ selected: _selected2 });
}
},
isActive: function isActive() {
return this.state.selected.active === true;
},
setupGridColumns: function setupGridColumns() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
var columns = props.columns;
if (this._cachedColumns === columns) {
return this._cachedComputedColumns;
}
this._cachedColumns = columns;
var cols = columns.slice(0);
var unshiftedCols = {};
if (this.props.rowActionsCell || props.enableRowSelect && !this.props.rowSelection || props.rowSelection && props.rowSelection.showCheckbox !== false) {
var headerRenderer = props.enableRowSelect === 'single' ? null : React.createElement(
'div',
{ className: 'react-grid-checkbox-container' },
React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: 'select-all-checkbox', id: 'select-all-checkbox', onChange: this.handleCheckboxChange }),
React.createElement('label', { htmlFor: 'select-all-checkbox', className: 'react-grid-checkbox-label' })
);
var Formatter = this.props.rowActionsCell ? this.props.rowActionsCell : CheckboxEditor;
var selectColumn = {
key: 'select-row',
name: '',
formatter: React.createElement(Formatter, { rowSelection: this.props.rowSelection }),
onCellChange: this.handleRowSelect,
filterable: false,
headerRenderer: headerRenderer,
width: 60,
locked: true,
getRowMetaData: function getRowMetaData(rowData) {
return rowData;
},
cellClass: this.props.rowActionsCell ? 'rdg-row-actions-cell' : ''
};
unshiftedCols = cols.unshift(selectColumn);
cols = unshiftedCols > 0 ? cols : unshiftedCols;
}
this._cachedComputedColumns = cols;
return this._cachedComputedColumns;
},
copyPasteEnabled: function copyPasteEnabled() {
return this.props.onCellCopyPaste !== null;
},
dragEnabled: function dragEnabled() {
return this.props.onGridRowsUpdated !== undefined || this.props.onCellsDragged !== undefined;
},
renderToolbar: function renderToolbar() {
var Toolbar = this.props.toolbar;
if (React.isValidElement(Toolbar)) {
return React.cloneElement(Toolbar, { columns: this.props.columns, onToggleFilter: this.onToggleFilter, numberOfRows: this.props.rowsCount });
}
},
render: function render() {
var cellMetaData = {
selected: this.state.selected,
dragged: this.state.dragged,
hoveredRowIdx: this.state.hoveredRowIdx,
onCellClick: this.onCellClick,
onCellContextMenu: this.onCellContextMenu,
onCellDoubleClick: this.onCellDoubleClick,
onCommit: this.onCellCommit,
onCommitCancel: this.setInactive,
copied: this.state.copied,
handleDragEnterRow: this.handleDragEnter,
handleTerminateDrag: this.handleTerminateDrag,
enableCellSelect: this.props.enableCellSelect,
onColumnEvent: this.onColumnEvent,
openCellEditor: this.openCellEditor,
onDragHandleDoubleClick: this.onDragHandleDoubleClick,
onCellExpand: this.onCellExpand,
onRowExpandToggle: this.onRowExpandToggle,
onRowHover: this.onRowHover,
getDataGridDOMNode: this.getDataGridDOMNode,
isScrollingVerticallyWithKeyboard: this.isKeyDown(40) || this.isKeyDown(38), // up or down
isScrollingHorizontallyWithKeyboard: this.isKeyDown(37) || this.isKeyDown(39) // left or right
};
var toolbar = this.renderToolbar();
var containerWidth = this.props.minWidth || this.DOMMetrics.gridWidth();
var gridWidth = containerWidth - this.state.scrollOffset;
// depending on the current lifecycle stage, gridWidth() may not initialize correctly
// this also handles cases where it always returns undefined -- such as when inside a div with display:none
// eg Bootstrap tabs and collapses
if (typeof containerWidth === 'undefined' || isNaN(containerWidth) || containerWidth === 0) {
containerWidth = '100%';
}
if (typeof gridWidth === 'undefined' || isNaN(gridWidth) || gridWidth === 0) {
gridWidth = '100%';
}
return React.createElement(
'div',
{ className: 'react-grid-Container', style: { width: containerWidth } },
toolbar,
React.createElement(
'div',
{ className: 'react-grid-Main' },
React.createElement(BaseGrid, _extends({
ref: 'base'
}, this.props, {
rowKey: this.props.rowKey,
headerRows: this.getHeaderRows(),
columnMetrics: this.state.columnMetrics,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
rowHeight: this.props.rowHeight,
cellMetaData: cellMetaData,
selectedRows: this.getSelectedRows(),
rowSelection: this.getRowSelectionProps(),
expandedRows: this.state.expandedRows,
rowOffsetHeight: this.getRowOffsetHeight(),
sortColumn: this.state.sortColumn,
sortDirection: this.state.sortDirection,
onSort: this.handleSort,
minHeight: this.props.minHeight,
totalWidth: gridWidth,
onViewportKeydown: this.onKeyDown,
onViewportKeyup: this.onKeyUp,
onViewportDragStart: this.onDragStart,
onViewportDragEnd: this.handleDragEnd,
onViewportDoubleClick: this.onViewportDoubleClick,
onColumnResize: this.onColumnResize,
rowScrollTimeout: this.props.rowScrollTimeout,
contextMenu: this.props.contextMenu,
overScan: this.props.overScan }))
)
);
}
});
module.exports = ReactDataGrid;
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var Draggable = __webpack_require__(45);
var ResizeHandle = React.createClass({
displayName: 'ResizeHandle',
style: {
position: 'absolute',
top: 0,
right: 0,
width: 6,
height: '100%'
},
render: function render() {
return React.createElement(Draggable, _extends({}, this.props, {
className: 'react-grid-HeaderCell__resizeHandle',
style: this.style
}));
}
});
module.exports = ResizeHandle;
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.shouldRowUpdate = undefined;
var _ColumnMetrics = __webpack_require__(17);
var _ColumnMetrics2 = _interopRequireDefault(_ColumnMetrics);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function doesRowContainSelectedCell(props) {
var selected = props.cellMetaData.selected;
if (selected && selected.rowIdx === props.idx) {
return true;
}
return false;
}
function willRowBeDraggedOver(props) {
var dragged = props.cellMetaData.dragged;
return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true);
}
function hasRowBeenCopied(props) {
var copied = props.cellMetaData.copied;
return copied != null && copied.rowIdx === props.idx;
}
var shouldRowUpdate = exports.shouldRowUpdate = function shouldRowUpdate(nextProps, currentProps) {
return !_ColumnMetrics2['default'].sameColumns(currentProps.columns, nextProps.columns, _ColumnMetrics2['default'].sameColumn) || doesRowContainSelectedCell(currentProps) || doesRowContainSelectedCell(nextProps) || willRowBeDraggedOver(nextProps) || nextProps.row !== currentProps.row || currentProps.colDisplayStart !== nextProps.colDisplayStart || currentProps.colDisplayEnd !== nextProps.colDisplayEnd || currentProps.colVisibleStart !== nextProps.colVisibleStart || currentProps.colVisibleEnd !== nextProps.colVisibleEnd || hasRowBeenCopied(currentProps) || currentProps.isSelected !== nextProps.isSelected || nextProps.height !== currentProps.height || currentProps.isOver !== nextProps.isOver || currentProps.canDrop !== nextProps.canDrop || currentProps.forceUpdate === true;
};
exports['default'] = shouldRowUpdate;
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var RowGroup = function (_Component) {
_inherits(RowGroup, _Component);
function RowGroup() {
_classCallCheck(this, RowGroup);
var _this = _possibleConstructorReturn(this, _Component.call(this));
_this.checkFocus = _this.checkFocus.bind(_this);
_this.isSelected = _this.isSelected.bind(_this);
_this.onClick = _this.onClick.bind(_this);
_this.onRowExpandToggle = _this.onRowExpandToggle.bind(_this);
_this.onKeyDown = _this.onKeyDown.bind(_this);
_this.onRowExpandClick = _this.onRowExpandClick.bind(_this);
return _this;
}
RowGroup.prototype.componentDidMount = function componentDidMount() {
this.checkFocus();
};
RowGroup.prototype.componentDidUpdate = function componentDidUpdate() {
this.checkFocus();
};
RowGroup.prototype.isSelected = function isSelected() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.selected && meta.selected.rowIdx === this.props.idx;
};
RowGroup.prototype.onClick = function onClick(e) {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellClick && typeof meta.onCellClick === 'function') {
meta.onCellClick({ rowIdx: this.props.idx, idx: 0 }, e);
}
};
RowGroup.prototype.onKeyDown = function onKeyDown(e) {
if (e.key === 'ArrowLeft') {
this.onRowExpandToggle(false);
}
if (e.key === 'ArrowRight') {
this.onRowExpandToggle(true);
}
if (e.key === 'Enter') {
this.onRowExpandToggle(!this.props.isExpanded);
}
};
RowGroup.prototype.onRowExpandClick = function onRowExpandClick() {
this.onRowExpandToggle(!this.props.isExpanded);
};
RowGroup.prototype.onRowExpandToggle = function onRowExpandToggle(expand) {
var shouldExpand = expand == null ? !this.props.isExpanded : expand;
var meta = this.props.cellMetaData;
if (meta != null && meta.onRowExpandToggle && typeof meta.onRowExpandToggle === 'function') {
meta.onRowExpandToggle({ rowIdx: this.props.idx, shouldExpand: shouldExpand, columnGroupName: this.props.columnGroupName, name: this.props.name });
}
};
RowGroup.prototype.getClassName = function getClassName() {
return (0, _classnames2['default'])('react-grid-row-group', 'react-grid-Row', { 'row-selected': this.isSelected() });
};
RowGroup.prototype.checkFocus = function checkFocus() {
if (this.isSelected()) {
_reactDom2['default'].findDOMNode(this).focus();
}
};
RowGroup.prototype.render = function render() {
var style = {
height: '50px',
overflow: 'hidden',
border: '1px solid #dddddd',
paddingTop: '15px',
paddingLeft: '5px'
};
var rowGroupRendererProps = Object.assign({ onRowExpandClick: this.onRowExpandClick }, this.props);
return _react2['default'].createElement(
'div',
{ style: style, className: this.getClassName(), onClick: this.onClick, onKeyDown: this.onKeyDown, tabIndex: -1 },
_react2['default'].createElement(this.props.renderer, rowGroupRendererProps)
);
};
return RowGroup;
}(_react.Component);
RowGroup.propTypes = {
name: _react.PropTypes.string.isRequired,
columnGroupName: _react.PropTypes.string.isRequired,
isExpanded: _react.PropTypes.bool.isRequired,
treeDepth: _react.PropTypes.number.isRequired,
height: _react.PropTypes.number.isRequired,
cellMetaData: _react.PropTypes.object,
idx: _react.PropTypes.number.isRequired,
renderer: _react.PropTypes.func
};
var DefaultRowGroupRenderer = function DefaultRowGroupRenderer(props) {
var treeDepth = props.treeDepth || 0;
var marginLeft = treeDepth * 20;
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'span',
{ className: 'row-expand-icon', style: { float: 'left', marginLeft: marginLeft, cursor: 'pointer' }, onClick: props.onRowExpandClick },
props.isExpanded ? String.fromCharCode('9660') : String.fromCharCode('9658')
),
_react2['default'].createElement(
'strong',
null,
props.columnGroupName,
' : ',
props.name
)
);
};
DefaultRowGroupRenderer.propTypes = {
onRowExpandClick: _react.PropTypes.func.isRequired,
isExpanded: _react.PropTypes.bool.isRequired,
treeDepth: _react.PropTypes.number.isRequired,
name: _react.PropTypes.string.isRequired,
columnGroupName: _react.PropTypes.string.isRequired
};
RowGroup.defaultProps = {
renderer: DefaultRowGroupRenderer
};
exports['default'] = RowGroup;
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.SimpleRowsContainer = undefined;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var SimpleRowsContainer = function SimpleRowsContainer(props) {
return _react2['default'].createElement(
'div',
{ key: 'rows-container', style: { overflow: 'hidden' } },
props.rows
);
};
SimpleRowsContainer.propTypes = {
width: _react.PropTypes.number,
rows: _react.PropTypes.array
};
var RowsContainer = function (_React$Component) {
_inherits(RowsContainer, _React$Component);
function RowsContainer(props) {
_classCallCheck(this, RowsContainer);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.plugins = props.window ? props.window.ReactDataGridPlugins : window.ReactDataGridPlugins;
_this.hasContextMenu = _this.hasContextMenu.bind(_this);
_this.renderRowsWithContextMenu = _this.renderRowsWithContextMenu.bind(_this);
_this.getContextMenuContainer = _this.getContextMenuContainer.bind(_this);
_this.state = { ContextMenuContainer: _this.getContextMenuContainer(props) };
return _this;
}
RowsContainer.prototype.getContextMenuContainer = function getContextMenuContainer() {
if (this.hasContextMenu()) {
if (!this.plugins) {
throw new Error('You need to include ReactDataGrid UiPlugins in order to initialise context menu');
}
return this.plugins.Menu.ContextMenuLayer('reactDataGridContextMenu')(SimpleRowsContainer);
}
};
RowsContainer.prototype.hasContextMenu = function hasContextMenu() {
return this.props.contextMenu && _react2['default'].isValidElement(this.props.contextMenu);
};
RowsContainer.prototype.renderRowsWithContextMenu = function renderRowsWithContextMenu() {
var ContextMenuRowsContainer = this.state.ContextMenuContainer;
var newProps = { rowIdx: this.props.rowIdx, idx: this.props.idx };
var contextMenu = _react2['default'].cloneElement(this.props.contextMenu, newProps);
// Initialise the context menu if it is available
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(ContextMenuRowsContainer, this.props),
contextMenu
);
};
RowsContainer.prototype.render = function render() {
return this.hasContextMenu() ? this.renderRowsWithContextMenu() : _react2['default'].createElement(SimpleRowsContainer, this.props);
};
return RowsContainer;
}(_react2['default'].Component);
RowsContainer.propTypes = {
contextMenu: _react.PropTypes.element,
rowIdx: _react.PropTypes.number,
idx: _react.PropTypes.number,
window: _react.PropTypes.object
};
exports['default'] = RowsContainer;
exports.SimpleRowsContainer = SimpleRowsContainer;
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var ScrollShim = {
appendScrollShim: function appendScrollShim() {
if (!this._scrollShim) {
var size = this._scrollShimSize();
var shim = document.createElement('div');
if (shim.classList) {
shim.classList.add('react-grid-ScrollShim'); // flow - not compatible with HTMLElement
} else {
shim.className += ' react-grid-ScrollShim';
}
shim.style.position = 'absolute';
shim.style.top = 0;
shim.style.left = 0;
shim.style.width = size.width + 'px';
shim.style.height = size.height + 'px';
_reactDom2['default'].findDOMNode(this).appendChild(shim);
this._scrollShim = shim;
}
this._scheduleRemoveScrollShim();
},
_scrollShimSize: function _scrollShimSize() {
return {
width: this.props.width,
height: this.props.length * this.props.rowHeight
};
},
_scheduleRemoveScrollShim: function _scheduleRemoveScrollShim() {
if (this._scheduleRemoveScrollShimTimer) {
clearTimeout(this._scheduleRemoveScrollShimTimer);
}
this._scheduleRemoveScrollShimTimer = setTimeout(this._removeScrollShim, 200);
},
_removeScrollShim: function _removeScrollShim() {
if (this._scrollShim) {
this._scrollShim.parentNode.removeChild(this._scrollShim);
this._scrollShim = undefined;
}
}
};
module.exports = ScrollShim;
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var Canvas = __webpack_require__(42);
var ViewportScroll = __webpack_require__(61);
var cellMetaDataShape = __webpack_require__(8);
var PropTypes = React.PropTypes;
var Viewport = React.createClass({
displayName: 'Viewport',
mixins: [ViewportScroll],
propTypes: {
rowOffsetHeight: PropTypes.number.isRequired,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
columnMetrics: PropTypes.object.isRequired,
rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired,
selectedRows: PropTypes.array,
rowSelection: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]),
expandedRows: PropTypes.array,
rowRenderer: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
rowsCount: PropTypes.number.isRequired,
rowHeight: PropTypes.number.isRequired,
onRows: PropTypes.func,
onScroll: PropTypes.func,
minHeight: PropTypes.number,
cellMetaData: PropTypes.shape(cellMetaDataShape),
rowKey: PropTypes.string.isRequired,
rowScrollTimeout: PropTypes.number,
contextMenu: PropTypes.element,
getSubRowDetails: PropTypes.func,
rowGroupRenderer: PropTypes.func
},
onScroll: function onScroll(scroll) {
this.updateScroll(scroll.scrollTop, scroll.scrollLeft, this.state.height, this.props.rowHeight, this.props.rowsCount);
if (this.props.onScroll) {
this.props.onScroll({ scrollTop: scroll.scrollTop, scrollLeft: scroll.scrollLeft });
}
},
getScroll: function getScroll() {
return this.refs.canvas.getScroll();
},
setScrollLeft: function setScrollLeft(scrollLeft) {
this.refs.canvas.setScrollLeft(scrollLeft);
},
render: function render() {
var style = {
padding: 0,
bottom: 0,
left: 0,
right: 0,
overflow: 'hidden',
position: 'absolute',
top: this.props.rowOffsetHeight
};
return React.createElement(
'div',
{
className: 'react-grid-Viewport',
style: style },
React.createElement(Canvas, {
ref: 'canvas',
rowKey: this.props.rowKey,
totalWidth: this.props.totalWidth,
width: this.props.columnMetrics.width,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
selectedRows: this.props.selectedRows,
expandedRows: this.props.expandedRows,
columns: this.props.columnMetrics.columns,
rowRenderer: this.props.rowRenderer,
displayStart: this.state.displayStart,
displayEnd: this.state.displayEnd,
visibleStart: this.state.visibleStart,
visibleEnd: this.state.visibleEnd,
colVisibleStart: this.state.colVisibleStart,
colVisibleEnd: this.state.colVisibleEnd,
colDisplayStart: this.state.colDisplayStart,
colDisplayEnd: this.state.colDisplayEnd,
cellMetaData: this.props.cellMetaData,
height: this.state.height,
rowHeight: this.props.rowHeight,
onScroll: this.onScroll,
onRows: this.props.onRows,
rowScrollTimeout: this.props.rowScrollTimeout,
contextMenu: this.props.contextMenu,
rowSelection: this.props.rowSelection,
getSubRowDetails: this.props.getSubRowDetails,
rowGroupRenderer: this.props.rowGroupRenderer,
isScrolling: this.state.isScrolling
})
);
}
});
module.exports = Viewport;
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _ColumnUtils = __webpack_require__(4);
var _ColumnUtils2 = _interopRequireDefault(_ColumnUtils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var DOMMetrics = __webpack_require__(10);
var min = Math.min;
var max = Math.max;
var floor = Math.floor;
var ceil = Math.ceil;
module.exports = {
mixins: [DOMMetrics.MetricsMixin],
DOMMetrics: {
viewportHeight: function viewportHeight() {
return ReactDOM.findDOMNode(this).offsetHeight;
},
viewportWidth: function viewportWidth() {
return ReactDOM.findDOMNode(this).offsetWidth;
}
},
propTypes: {
rowHeight: React.PropTypes.number,
rowsCount: React.PropTypes.number.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
rowHeight: 30
};
},
getInitialState: function getInitialState() {
return this.getGridState(this.props);
},
getGridState: function getGridState(props) {
var totalNumberColumns = _ColumnUtils2['default'].getSize(props.columnMetrics.columns);
var canvasHeight = props.minHeight - props.rowOffsetHeight;
var renderedRowsCount = ceil((props.minHeight - props.rowHeight) / props.rowHeight);
var totalRowCount = min(renderedRowsCount * 4, props.rowsCount);
return {
displayStart: 0,
displayEnd: totalRowCount,
visibleStart: 0,
visibleEnd: totalRowCount,
height: canvasHeight,
scrollTop: 0,
scrollLeft: 0,
colVisibleStart: 0,
colVisibleEnd: totalNumberColumns,
colDisplayStart: 0,
colDisplayEnd: totalNumberColumns
};
},
getRenderedColumnCount: function getRenderedColumnCount(displayStart, width) {
var remainingWidth = width > 0 ? width : this.props.columnMetrics.totalWidth;
if (remainingWidth === 0) {
remainingWidth = ReactDOM.findDOMNode(this).offsetWidth;
}
var columnIndex = displayStart;
var columnCount = 0;
while (remainingWidth > 0) {
var column = _ColumnUtils2['default'].getColumn(this.props.columnMetrics.columns, columnIndex);
if (!column) {
break;
}
columnCount++;
columnIndex++;
remainingWidth -= column.width;
}
return columnCount;
},
getVisibleColStart: function getVisibleColStart(scrollLeft) {
var remainingScroll = scrollLeft;
var columnIndex = -1;
while (remainingScroll >= 0) {
columnIndex++;
remainingScroll -= _ColumnUtils2['default'].getColumn(this.props.columnMetrics.columns, columnIndex).width;
}
return columnIndex;
},
resetScrollStateAfterDelay: function resetScrollStateAfterDelay() {
if (this.resetScrollStateTimeoutId) {
clearTimeout(this.resetScrollStateTimeoutId);
}
this.resetScrollStateTimeoutId = setTimeout(this.resetScrollStateAfterDelayCallback, 500);
},
resetScrollStateAfterDelayCallback: function resetScrollStateAfterDelayCallback() {
this.resetScrollStateTimeoutId = null;
this.setState({
isScrolling: false
});
},
updateScroll: function updateScroll(scrollTop, scrollLeft, height, rowHeight, length, width) {
var isScrolling = true;
this.resetScrollStateAfterDelay();
var renderedRowsCount = ceil(height / rowHeight);
var visibleStart = max(0, floor(scrollTop / rowHeight));
var visibleEnd = min(visibleStart + renderedRowsCount, length);
var displayStart = max(0, visibleStart - this.props.overScan.rowsStart);
var displayEnd = min(visibleEnd + this.props.overScan.rowsEnd, length);
var totalNumberColumns = _ColumnUtils2['default'].getSize(this.props.columnMetrics.columns);
var colVisibleStart = max(0, this.getVisibleColStart(scrollLeft));
var renderedColumnCount = this.getRenderedColumnCount(colVisibleStart, width);
var colVisibleEnd = colVisibleStart + renderedColumnCount;
var colDisplayStart = max(0, colVisibleStart - this.props.overScan.colsStart);
var colDisplayEnd = min(colVisibleEnd + this.props.overScan.colsEnd, totalNumberColumns);
var nextScrollState = {
visibleStart: visibleStart,
visibleEnd: visibleEnd,
displayStart: displayStart,
displayEnd: displayEnd,
height: height,
scrollTop: scrollTop,
scrollLeft: scrollLeft,
colVisibleStart: colVisibleStart,
colVisibleEnd: colVisibleEnd,
colDisplayStart: colDisplayStart,
colDisplayEnd: colDisplayEnd,
isScrolling: isScrolling
};
this.setState(nextScrollState);
},
metricsUpdated: function metricsUpdated() {
var height = this.DOMMetrics.viewportHeight();
var width = this.DOMMetrics.viewportWidth();
if (height) {
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, height, this.props.rowHeight, this.props.rowsCount, width);
}
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (this.props.rowHeight !== nextProps.rowHeight || this.props.minHeight !== nextProps.minHeight || _ColumnUtils2['default'].getSize(this.props.columnMetrics.columns) !== _ColumnUtils2['default'].getSize(nextProps.columnMetrics.columns)) {
this.setState(this.getGridState(nextProps));
} else if (this.props.rowsCount !== nextProps.rowsCount) {
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height, nextProps.rowHeight, nextProps.rowsCount);
// Added to fix the hiding of the bottom scrollbar when showing the filters.
} else if (this.props.rowOffsetHeight !== nextProps.rowOffsetHeight) {
// The value of height can be positive or negative and will be added to the current height to cater for changes in the header height (due to the filer)
var _height = this.props.rowOffsetHeight - nextProps.rowOffsetHeight;
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height + _height, nextProps.rowHeight, nextProps.rowsCount);
}
}
};
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ExcelColumn = __webpack_require__(6);
var FilterableHeaderCell = React.createClass({
displayName: 'FilterableHeaderCell',
propTypes: {
onChange: React.PropTypes.func.isRequired,
column: React.PropTypes.shape(ExcelColumn)
},
getInitialState: function getInitialState() {
return { filterTerm: '' };
},
handleChange: function handleChange(e) {
var val = e.target.value;
this.setState({ filterTerm: val });
this.props.onChange({ filterTerm: val, column: this.props.column });
},
renderInput: function renderInput() {
if (this.props.column.filterable === false) {
return React.createElement('span', null);
}
var inputKey = 'header-filter-' + this.props.column.key;
return React.createElement('input', { key: inputKey, type: 'text', className: 'form-control input-sm', placeholder: 'Search', value: this.state.filterTerm, onChange: this.handleChange });
},
render: function render() {
return React.createElement(
'div',
null,
React.createElement(
'div',
{ className: 'form-group' },
this.renderInput()
)
);
}
});
module.exports = FilterableHeaderCell;
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(5);
var DEFINE_SORT = {
ASC: 'ASC',
DESC: 'DESC',
NONE: 'NONE'
};
var SortableHeaderCell = React.createClass({
displayName: 'SortableHeaderCell',
propTypes: {
columnKey: React.PropTypes.string.isRequired,
column: React.PropTypes.shape({ name: React.PropTypes.node }),
onSort: React.PropTypes.func.isRequired,
sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE'])
},
onClick: function onClick() {
var direction = void 0;
switch (this.props.sortDirection) {
default:
case null:
case undefined:
case DEFINE_SORT.NONE:
direction = DEFINE_SORT.ASC;
break;
case DEFINE_SORT.ASC:
direction = DEFINE_SORT.DESC;
break;
case DEFINE_SORT.DESC:
direction = DEFINE_SORT.NONE;
break;
}
this.props.onSort(this.props.columnKey, direction);
},
getSortByText: function getSortByText() {
var unicodeKeys = {
ASC: '9650',
DESC: '9660',
NONE: ''
};
return String.fromCharCode(unicodeKeys[this.props.sortDirection]);
},
render: function render() {
var className = joinClasses({
'react-grid-HeaderCell-sortable': true,
'react-grid-HeaderCell-sortable--ascending': this.props.sortDirection === 'ASC',
'react-grid-HeaderCell-sortable--descending': this.props.sortDirection === 'DESC'
});
return React.createElement(
'div',
{ className: className,
onClick: this.onClick,
style: { cursor: 'pointer' } },
this.props.column.name,
React.createElement(
'span',
{ className: 'pull-right' },
this.getSortByText()
)
);
}
});
module.exports = SortableHeaderCell;
module.exports.DEFINE_SORT = DEFINE_SORT;
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var CheckboxEditor = React.createClass({
displayName: 'CheckboxEditor',
propTypes: {
value: React.PropTypes.bool,
rowIdx: React.PropTypes.number,
column: React.PropTypes.shape({
key: React.PropTypes.string,
onCellChange: React.PropTypes.func
}),
dependentValues: React.PropTypes.object
},
handleChange: function handleChange(e) {
this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, this.props.dependentValues, e);
},
render: function render() {
var checked = this.props.value != null ? this.props.value : false;
var checkboxName = 'checkbox' + this.props.rowIdx;
return React.createElement(
'div',
{ className: 'react-grid-checkbox-container', onClick: this.handleChange },
React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: checkboxName, checked: checked }),
React.createElement('label', { htmlFor: checkboxName, className: 'react-grid-checkbox-label' })
);
}
});
module.exports = CheckboxEditor;
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var ExcelColumn = __webpack_require__(6);
var EditorBase = function (_React$Component) {
_inherits(EditorBase, _React$Component);
function EditorBase() {
_classCallCheck(this, EditorBase);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
EditorBase.prototype.getStyle = function getStyle() {
return {
width: '100%'
};
};
EditorBase.prototype.getValue = function getValue() {
var updated = {};
updated[this.props.column.key] = this.getInputNode().value;
return updated;
};
EditorBase.prototype.getInputNode = function getInputNode() {
var domNode = ReactDOM.findDOMNode(this);
if (domNode.tagName === 'INPUT') {
return domNode;
}
return domNode.querySelector('input:not([type=hidden])');
};
EditorBase.prototype.inheritContainerStyles = function inheritContainerStyles() {
return true;
};
return EditorBase;
}(React.Component);
EditorBase.propTypes = {
onKeyDown: React.PropTypes.func.isRequired,
value: React.PropTypes.any.isRequired,
onBlur: React.PropTypes.func.isRequired,
column: React.PropTypes.shape(ExcelColumn).isRequired,
commit: React.PropTypes.func.isRequired
};
module.exports = EditorBase;
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(5);
var keyboardHandlerMixin = __webpack_require__(25);
var SimpleTextEditor = __webpack_require__(67);
var isFunction = __webpack_require__(27);
var EditorContainer = React.createClass({
displayName: 'EditorContainer',
mixins: [keyboardHandlerMixin],
propTypes: {
rowIdx: React.PropTypes.number,
rowData: React.PropTypes.object.isRequired,
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired,
cellMetaData: React.PropTypes.shape({
selected: React.PropTypes.object.isRequired,
copied: React.PropTypes.object,
dragged: React.PropTypes.object,
onCellClick: React.PropTypes.func,
onCellDoubleClick: React.PropTypes.func,
onCommitCancel: React.PropTypes.func,
onCommit: React.PropTypes.func
}).isRequired,
column: React.PropTypes.object.isRequired,
height: React.PropTypes.number.isRequired
},
changeCommitted: false,
getInitialState: function getInitialState() {
return { isInvalid: false };
},
componentDidMount: function componentDidMount() {
var inputNode = this.getInputNode();
if (inputNode !== undefined) {
this.setTextInputFocus();
if (!this.getEditor().disableContainerStyles) {
inputNode.className += ' editor-main';
inputNode.style.height = this.props.height - 1 + 'px';
}
}
},
componentWillUnmount: function componentWillUnmount() {
if (!this.changeCommitted && !this.hasEscapeBeenPressed()) {
this.commit({ key: 'Enter' });
}
},
createEditor: function createEditor() {
var _this = this;
var editorRef = function editorRef(c) {
return _this.editor = c;
};
var editorProps = {
ref: editorRef,
column: this.props.column,
value: this.getInitialValue(),
onCommit: this.commit,
rowMetaData: this.getRowMetaData(),
rowData: this.props.rowData,
height: this.props.height,
onBlur: this.commit,
onOverrideKeyDown: this.onKeyDown
};
var CustomEditor = this.props.column.editor;
// return custom column editor or SimpleEditor if none specified
if (React.isValidElement(CustomEditor)) {
return React.cloneElement(CustomEditor, editorProps);
}
if (isFunction(CustomEditor)) {
return React.createElement(CustomEditor, _extends({ ref: editorRef }, editorProps));
}
return React.createElement(SimpleTextEditor, { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onBlur: this.commit, rowMetaData: this.getRowMetaData(), onKeyDown: function onKeyDown() {}, commit: function commit() {} });
},
onPressEnter: function onPressEnter() {
this.commit({ key: 'Enter' });
},
onPressTab: function onPressTab() {
this.commit({ key: 'Tab' });
},
onPressEscape: function onPressEscape(e) {
if (!this.editorIsSelectOpen()) {
this.props.cellMetaData.onCommitCancel();
} else {
// prevent event from bubbling if editor has results to select
e.stopPropagation();
}
},
onPressArrowDown: function onPressArrowDown(e) {
if (this.editorHasResults()) {
// dont want to propogate as that then moves us round the grid
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowUp: function onPressArrowUp(e) {
if (this.editorHasResults()) {
// dont want to propogate as that then moves us round the grid
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowLeft: function onPressArrowLeft(e) {
// prevent event propogation. this disables left cell navigation
if (!this.isCaretAtBeginningOfInput()) {
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowRight: function onPressArrowRight(e) {
// prevent event propogation. this disables right cell navigation
if (!this.isCaretAtEndOfInput()) {
e.stopPropagation();
} else {
this.commit(e);
}
},
editorHasResults: function editorHasResults() {
if (isFunction(this.getEditor().hasResults)) {
return this.getEditor().hasResults();
}
return false;
},
editorIsSelectOpen: function editorIsSelectOpen() {
if (isFunction(this.getEditor().isSelectOpen)) {
return this.getEditor().isSelectOpen();
}
return false;
},
getRowMetaData: function getRowMetaData() {
// clone row data so editor cannot actually change this
// convention based method to get corresponding Id or Name of any Name or Id property
if (typeof this.props.column.getRowMetaData === 'function') {
return this.props.column.getRowMetaData(this.props.rowData, this.props.column);
}
},
getEditor: function getEditor() {
return this.editor;
},
getInputNode: function getInputNode() {
return this.getEditor().getInputNode();
},
getInitialValue: function getInitialValue() {
var selected = this.props.cellMetaData.selected;
var keyCode = selected.initialKeyCode;
if (keyCode === 'Delete' || keyCode === 'Backspace') {
return '';
} else if (keyCode === 'Enter') {
return this.props.value;
}
var text = keyCode ? String.fromCharCode(keyCode) : this.props.value;
return text;
},
getContainerClass: function getContainerClass() {
return joinClasses({
'has-error': this.state.isInvalid === true
});
},
commit: function commit(args) {
var opts = args || {};
var updated = this.getEditor().getValue();
if (this.isNewValueValid(updated)) {
this.changeCommitted = true;
var cellKey = this.props.column.key;
this.props.cellMetaData.onCommit({ cellKey: cellKey, rowIdx: this.props.rowIdx, updated: updated, key: opts.key });
}
},
isNewValueValid: function isNewValueValid(value) {
if (isFunction(this.getEditor().validate)) {
var isValid = this.getEditor().validate(value);
this.setState({ isInvalid: !isValid });
return isValid;
}
return true;
},
setCaretAtEndOfInput: function setCaretAtEndOfInput() {
var input = this.getInputNode();
// taken from http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element
var txtLength = input.value.length;
if (input.setSelectionRange) {
input.setSelectionRange(txtLength, txtLength);
} else if (input.createTextRange) {
var fieldRange = input.createTextRange();
fieldRange.moveStart('character', txtLength);
fieldRange.collapse();
fieldRange.select();
}
},
isCaretAtBeginningOfInput: function isCaretAtBeginningOfInput() {
var inputNode = this.getInputNode();
return inputNode.selectionStart === inputNode.selectionEnd && inputNode.selectionStart === 0;
},
isCaretAtEndOfInput: function isCaretAtEndOfInput() {
var inputNode = this.getInputNode();
return inputNode.selectionStart === inputNode.value.length;
},
isBodyClicked: function isBodyClicked(e) {
return e.relatedTarget === null;
},
isViewportClicked: function isViewportClicked(e) {
return e.relatedTarget.classList.contains('react-grid-Viewport');
},
isClickInisdeEditor: function isClickInisdeEditor(e) {
return e.currentTarget.contains(e.relatedTarget) || e.relatedTarget.classList.contains('editing') || e.relatedTarget.classList.contains('react-grid-Cell');
},
handleBlur: function handleBlur(e) {
e.stopPropagation();
if (this.isBodyClicked(e)) {
this.commit(e);
}
if (!this.isBodyClicked(e)) {
// prevent null reference
if (this.isViewportClicked(e) || !this.isClickInisdeEditor(e)) {
this.commit(e);
}
}
},
setTextInputFocus: function setTextInputFocus() {
var selected = this.props.cellMetaData.selected;
var keyCode = selected.initialKeyCode;
var inputNode = this.getInputNode();
inputNode.focus();
if (inputNode.tagName === 'INPUT') {
if (!this.isKeyPrintable(keyCode)) {
inputNode.focus();
inputNode.select();
} else {
inputNode.select();
}
}
},
hasEscapeBeenPressed: function hasEscapeBeenPressed() {
var pressed = false;
var escapeKey = 27;
if (window.event) {
if (window.event.keyCode === escapeKey) {
pressed = true;
} else if (window.event.which === escapeKey) {
pressed = true;
}
}
return pressed;
},
renderStatusIcon: function renderStatusIcon() {
if (this.state.isInvalid === true) {
return React.createElement('span', { className: 'glyphicon glyphicon-remove form-control-feedback' });
}
},
render: function render() {
return React.createElement(
'div',
{ className: this.getContainerClass(), onBlur: this.handleBlur, onKeyDown: this.onKeyDown },
this.createEditor(),
this.renderStatusIcon()
);
}
});
module.exports = EditorContainer;
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = __webpack_require__(1);
var EditorBase = __webpack_require__(65);
var SimpleTextEditor = function (_EditorBase) {
_inherits(SimpleTextEditor, _EditorBase);
function SimpleTextEditor() {
_classCallCheck(this, SimpleTextEditor);
return _possibleConstructorReturn(this, _EditorBase.apply(this, arguments));
}
SimpleTextEditor.prototype.render = function render() {
return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value });
};
return SimpleTextEditor;
}(EditorBase);
module.exports = SimpleTextEditor;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var SimpleCellFormatter = React.createClass({
displayName: 'SimpleCellFormatter',
propTypes: {
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return nextProps.value !== this.props.value;
},
render: function render() {
return React.createElement(
'div',
{ title: this.props.value },
this.props.value
);
}
});
module.exports = SimpleCellFormatter;
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-disable react/prop-types */
var focusableComponentWrapper = function focusableComponentWrapper(WrappedComponent) {
return function (_Component) {
_inherits(ComponentWrapper, _Component);
function ComponentWrapper() {
_classCallCheck(this, ComponentWrapper);
var _this = _possibleConstructorReturn(this, _Component.call(this));
_this.checkFocus = _this.checkFocus.bind(_this);
return _this;
}
ComponentWrapper.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return WrappedComponent.isSelected(this.props) !== WrappedComponent.isSelected(nextProps);
};
ComponentWrapper.prototype.componentDidMount = function componentDidMount() {
this.checkFocus();
};
ComponentWrapper.prototype.componentDidUpdate = function componentDidUpdate() {
this.checkFocus();
};
ComponentWrapper.prototype.checkFocus = function checkFocus() {
if (WrappedComponent.isSelected(this.props) && WrappedComponent.isScrolling(this.props)) {
this.focus();
}
};
ComponentWrapper.prototype.focus = function focus() {
_reactDom2['default'].findDOMNode(this).focus();
};
ComponentWrapper.prototype.render = function render() {
return _react2['default'].createElement(WrappedComponent, _extends({}, this.props, this.state));
};
return ComponentWrapper;
}(_react.Component);
};
exports['default'] = focusableComponentWrapper;
/***/ },
/* 70 */
/***/ function(module, exports) {
'use strict';
module.exports = function isColumnsImmutable(columns) {
return typeof Immutable !== 'undefined' && columns instanceof Immutable.List;
};
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (false) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule keyMirror
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(71);
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function (obj) {
var ret = {};
var key;
!(obj instanceof Object && !Array.isArray(obj)) ? false ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(98),
hashDelete = __webpack_require__(99),
hashGet = __webpack_require__(100),
hashHas = __webpack_require__(101),
hashSet = __webpack_require__(102);
/**
* 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;
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(29),
setCacheAdd = __webpack_require__(122),
setCacheHas = __webpack_require__(123);
/**
*
* 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;
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(11),
stackClear = __webpack_require__(125),
stackDelete = __webpack_require__(126),
stackGet = __webpack_require__(127),
stackHas = __webpack_require__(128),
stackSet = __webpack_require__(129);
/**
* 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;
/***/ },
/* 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__(7),
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, __webpack_require__) {
var baseTimes = __webpack_require__(89),
isArguments = __webpack_require__(130),
isArray = __webpack_require__(34),
isBuffer = __webpack_require__(35),
isIndex = __webpack_require__(103),
isTypedArray = __webpack_require__(38);
/** 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;
/***/ },
/* 82 */
/***/ 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;
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(13),
isObjectLike = __webpack_require__(16);
/** `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;
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
var baseIsEqualDeep = __webpack_require__(85),
isObject = __webpack_require__(23),
isObjectLike = __webpack_require__(16);
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
module.exports = baseIsEqual;
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(78),
equalArrays = __webpack_require__(30),
equalByTag = __webpack_require__(93),
equalObjects = __webpack_require__(94),
getTag = __webpack_require__(96),
isArray = __webpack_require__(34),
isBuffer = __webpack_require__(35),
isTypedArray = __webpack_require__(38);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = getTag(object);
objTag = objTag == argsTag ? objectTag : objTag;
}
if (!othIsArr) {
othTag = getTag(other);
othTag = othTag == argsTag ? objectTag : othTag;
}
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
module.exports = baseIsEqualDeep;
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(36),
isMasked = __webpack_require__(105),
isObject = __webpack_require__(23),
toSource = __webpack_require__(32);
/**
* 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;
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(13),
isLength = __webpack_require__(37),
isObjectLike = __webpack_require__(16);
/** `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;
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(106),
nativeKeys = __webpack_require__(118);
/** 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 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;
/***/ },
/* 90 */
/***/ 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;
/***/ },
/* 91 */
/***/ 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;
/***/ },
/* 92 */
/***/ 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;
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(22),
Uint8Array = __webpack_require__(79),
eq = __webpack_require__(33),
equalArrays = __webpack_require__(30),
mapToArray = __webpack_require__(117),
setToArray = __webpack_require__(124);
/** 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;
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
var keys = __webpack_require__(133);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(22);
/** 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;
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(73),
Map = __webpack_require__(21),
Promise = __webpack_require__(75),
Set = __webpack_require__(76),
WeakMap = __webpack_require__(80),
baseGetTag = __webpack_require__(13),
toSource = __webpack_require__(32);
/** `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;
/***/ },
/* 97 */
/***/ 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;
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(15);
/**
* 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;
/***/ },
/* 99 */
/***/ 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;
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(15);
/** 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;
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(15);
/** 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;
/***/ },
/* 102 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(15);
/** 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;
/***/ },
/* 103 */
/***/ 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;
/***/ },
/* 104 */
/***/ 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;
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(92);
/** 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;
/***/ },
/* 106 */
/***/ 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;
/***/ },
/* 107 */
/***/ 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;
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(12);
/** 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;
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(12);
/**
* 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;
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(12);
/**
* 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;
/***/ },
/* 111 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(12);
/**
* 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;
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(74),
ListCache = __webpack_require__(11),
Map = __webpack_require__(21);
/**
* 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;
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(14);
/**
* 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;
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(14);
/**
* 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;
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(14);
/**
* 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;
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(14);
/**
* 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;
/***/ },
/* 117 */
/***/ 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;
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(121);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ },
/* 119 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(31);
/** 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__(40)(module)))
/***/ },
/* 120 */
/***/ 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;
/***/ },
/* 121 */
/***/ 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;
/***/ },
/* 122 */
/***/ 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;
/***/ },
/* 123 */
/***/ 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;
/***/ },
/* 124 */
/***/ 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;
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(11);
/**
* 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;
/***/ },
/* 126 */
/***/ 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;
/***/ },
/* 127 */
/***/ 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;
/***/ },
/* 128 */
/***/ 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;
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(11),
Map = __webpack_require__(21),
MapCache = __webpack_require__(29);
/** 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;
/***/ },
/* 130 */
/***/ function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(83),
isObjectLike = __webpack_require__(16);
/** 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;
/***/ },
/* 131 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(36),
isLength = __webpack_require__(37);
/**
* 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;
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(84);
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are **not** supported.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual;
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(81),
baseKeys = __webpack_require__(88),
isArrayLike = __webpack_require__(131);
/**
* 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;
/***/ },
/* 134 */
/***/ 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;
/***/ }
/******/ ])
});
;
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalPizza = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.43 2 5.23 3.54 3.01 6L12 22l8.99-16C18.78 3.55 15.57 2 12 2zM7 7c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2zm5 8c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</SvgIcon>
);
MapsLocalPizza = pure(MapsLocalPizza);
MapsLocalPizza.displayName = 'MapsLocalPizza';
MapsLocalPizza.muiName = 'SvgIcon';
export default MapsLocalPizza;
|
/*! selectize.js - v0.6.7 | https://github.com/brianreavis/selectize.js | Apache License (v2) */
(function(factory) {
if (typeof exports === 'object') {
factory(require('jquery'));
} else if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function ($) {
"use strict";
/* --- file: "src/contrib/highlight.js" --- */
/**
* highlight v3 | MIT license | Johann Burkard <jb@eaio.com>
* Highlights arbitrary terms in a node.
*
* - Modified by Marshal <beatgates@gmail.com> 2011-6-24 (added regex)
* - Modified by Brian Reavis <brian@thirdroute.com> 2012-8-27 (cleanup)
*/
var highlight = function($element, pattern) {
if (typeof pattern === 'string' && !pattern.length) return;
var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern;
var highlight = function(node) {
var skip = 0;
if (node.nodeType === 3) {
var pos = node.data.search(regex);
if (pos >= 0 && node.data.length > 0) {
var match = node.data.match(regex);
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(match[0].length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += highlight(node.childNodes[i]);
}
}
return skip;
};
return $element.each(function() {
highlight(this);
});
};
var unhighlight = function($element) {
return $element.find('span.highlight').each(function() {
var parent = this.parentNode;
parent.replaceChild(parent.firstChild, parent);
parent.normalize();
}).end();
};
/* --- file: "src/contrib/microevent.js" --- */
/**
* MicroEvent - to make any js object an event emitter
*
* - pure javascript - server compatible, browser compatible
* - dont rely on the browser doms
* - super simple - you get it immediatly, no mistery, no magic involved
*
* @author Jerome Etienne (https://github.com/jeromeetienne)
*/
var MicroEvent = function() {};
MicroEvent.prototype = {
on: function(event, fct){
this._events = this._events || {};
this._events[event] = this._events[event] || [];
this._events[event].push(fct);
},
off: function(event, fct){
this._events = this._events || {};
if (event in this._events === false) return;
this._events[event].splice(this._events[event].indexOf(fct), 1);
},
trigger: function(event /* , args... */){
this._events = this._events || {};
if (event in this._events === false) return;
for (var i = 0; i < this._events[event].length; i++){
this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
};
/**
* Mixin will delegate all MicroEvent.js function in the destination object.
*
* - MicroEvent.mixin(Foobar) will make Foobar able to use MicroEvent
*
* @param {object} the object which will support MicroEvent
*/
MicroEvent.mixin = function(destObject){
var props = ['on', 'off', 'trigger'];
for (var i = 0; i < props.length; i++){
destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
}
};
/* --- file: "src/constants.js" --- */
/**
* selectize - A highly customizable select control with autocomplete.
* Copyright (c) 2013 Brian Reavis & contributors
*
* 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.
*
* @author Brian Reavis <brian@thirdroute.com>
*/
var IS_MAC = /Mac/.test(navigator.userAgent);
var KEY_A = 65;
var KEY_COMMA = 188;
var KEY_RETURN = 13;
var KEY_ESC = 27;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_BACKSPACE = 8;
var KEY_DELETE = 46;
var KEY_SHIFT = 16;
var KEY_CMD = IS_MAC ? 91 : 17;
var KEY_CTRL = IS_MAC ? 18 : 17;
var KEY_TAB = 9;
var TAG_SELECT = 1;
var TAG_INPUT = 2;
var DIACRITICS = {
'a': '[aÀÁÂÃÄÅàáâãäå]',
'c': '[cÇç]',
'e': '[eÈÉÊËèéêë]',
'i': '[iÌÍÎÏìíîï]',
'n': '[nÑñ]',
'o': '[oÒÓÔÕÕÖØòóôõöø]',
's': '[sŠš]',
'u': '[uÙÚÛÜùúûü]',
'y': '[yŸÿý]',
'z': '[zŽž]'
};
/* --- file: "src/plugins.js" --- */
var Plugins = {};
Plugins.mixin = function(Interface, interfaceName) {
Interface.plugins = {};
/**
* Initializes the provided functions.
* Acceptable formats:
*
* List (without options):
* ['a', 'b', 'c']
*
* List (with options)
* {'a': { ... }, 'b': { ... }, 'c': { ... }}
*
* @param {mixed} plugins
*/
Interface.prototype.loadPlugins = function(plugins) {
var i, n, key;
this.plugins = [];
this.pluginSettings = {};
if ($.isArray(plugins)) {
for (i = 0, n = plugins.length; i < n; i++) {
this.loadPlugin(plugins[i]);
}
} else if (plugins) {
this.pluginSettings = $.extend({}, plugins);
for (key in plugins) {
if (plugins.hasOwnProperty(key)) {
this.loadPlugin(key);
}
}
}
};
/**
* Initializes a plugin.
*
* @param {string} name
*/
Interface.prototype.loadPlugin = function(name) {
var plugin, i, n;
if (this.plugins.indexOf(name) !== -1) return;
if (!Interface.plugins.hasOwnProperty(name)) {
throw new Error(interfaceName + ' unable to find "' + name + '" plugin');
}
plugin = Interface.plugins[name];
// initialize plugin and dependencies
this.plugins.push(name);
for (i = 0, n = plugin.dependencies.length; i < n; i++) {
this.loadPlugin(plugin.dependencies[i]);
}
plugin.fn.apply(this, [this.pluginSettings[name] || {}]);
};
/**
* Registers a plugin.
*
* @param {string} name
* @param {array} dependencies (optional)
* @param {function} fn
*/
Interface.registerPlugin = function(name) {
var args = arguments;
Interface.plugins[name] = {
'name' : name,
'fn' : args[args.length - 1],
'dependencies' : args.length === 3 ? args[1] : []
};
};
};
/* --- file: "src/utils.js" --- */
/**
* Determines if the provided value has been defined.
*
* @param {mixed} object
* @returns {boolean}
*/
var isset = function(object) {
return typeof object !== 'undefined';
};
/**
* Escapes a string for use within HTML.
*
* @param {string} str
* @returns {string}
*/
var escape_html = function(str) {
return (str + '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
/**
* Escapes a string for use within regular expressions.
*
* @param {string} str
* @returns {string}
*/
var escape_regex = function(str) {
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
};
var hook = {};
/**
* Wraps `method` on `self` so that `fn`
* is invoked before the original method.
*
* @param {object} self
* @param {string} method
* @param {function} fn
*/
hook.before = function(self, method, fn) {
var original = self[method];
self[method] = function() {
fn.apply(self, arguments);
return original.apply(self, arguments);
};
};
/**
* Wraps `method` on `self` so that `fn`
* is invoked after the original method.
*
* @param {object} self
* @param {string} method
* @param {function} fn
*/
hook.after = function(self, method, fn) {
var original = self[method];
self[method] = function() {
var result = original.apply(self, arguments);
fn.apply(self, arguments);
return result;
};
};
/**
* Builds a hash table out of an array of
* objects, using the specified `key` within
* each object.
*
* @param {string} key
* @param {mixed} objects
*/
var build_hash_table = function(key, objects) {
if (!$.isArray(objects)) return objects;
var i, n, table = {};
for (i = 0, n = objects.length; i < n; i++) {
if (objects[i].hasOwnProperty(key)) {
table[objects[i][key]] = objects[i];
}
}
return table;
};
/**
* Wraps `fn` so that it can only be invoked once.
*
* @param {function} fn
* @returns {function}
*/
var once = function(fn) {
var called = false;
return function() {
if (called) return;
called = true;
fn.apply(this, arguments);
};
};
/**
* Wraps `fn` so that it can only be called once
* every `delay` milliseconds (invoked on the falling edge).
*
* @param {function} fn
* @param {int} delay
* @returns {function}
*/
var debounce = function(fn, delay) {
var timeout;
return function() {
var self = this;
var args = arguments;
window.clearTimeout(timeout);
timeout = window.setTimeout(function() {
fn.apply(self, args);
}, delay);
};
};
/**
* Debounce all fired events types listed in `types`
* while executing the provided `fn`.
*
* @param {object} self
* @param {array} types
* @param {function} fn
*/
var debounce_events = function(self, types, fn) {
var type;
var trigger = self.trigger;
var event_args = {};
// override trigger method
self.trigger = function() {
var type = arguments[0];
if (types.indexOf(type) !== -1) {
event_args[type] = arguments;
} else {
return trigger.apply(self, arguments);
}
};
// invoke provided function
fn.apply(self, []);
self.trigger = trigger;
// trigger queued events
for (type in event_args) {
if (event_args.hasOwnProperty(type)) {
trigger.apply(self, event_args[type]);
}
}
};
/**
* A workaround for http://bugs.jquery.com/ticket/6696
*
* @param {object} $parent - Parent element to listen on.
* @param {string} event - Event name.
* @param {string} selector - Descendant selector to filter by.
* @param {function} fn - Event handler.
*/
var watchChildEvent = function($parent, event, selector, fn) {
$parent.on(event, selector, function(e) {
var child = e.target;
while (child && child.parentNode !== $parent[0]) {
child = child.parentNode;
}
e.currentTarget = child;
return fn.apply(this, [e]);
});
};
/**
* Determines the current selection within a text input control.
* Returns an object containing:
* - start
* - length
*
* @param {object} input
* @returns {object}
*/
var getSelection = function(input) {
var result = {};
if ('selectionStart' in input) {
result.start = input.selectionStart;
result.length = input.selectionEnd - result.start;
} else if (document.selection) {
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
result.start = sel.text.length - selLen;
result.length = selLen;
}
return result;
};
/**
* Copies CSS properties from one element to another.
*
* @param {object} $from
* @param {object} $to
* @param {array} properties
*/
var transferStyles = function($from, $to, properties) {
var i, n, styles = {};
if (properties) {
for (i = 0, n = properties.length; i < n; i++) {
styles[properties[i]] = $from.css(properties[i]);
}
} else {
styles = $from.css();
}
$to.css(styles);
};
/**
* Measures the width of a string within a
* parent element (in pixels).
*
* @param {string} str
* @param {object} $parent
* @returns {int}
*/
var measureString = function(str, $parent) {
var $test = $('<test>').css({
position: 'absolute',
top: -99999,
left: -99999,
width: 'auto',
padding: 0,
whiteSpace: 'nowrap'
}).text(str).appendTo('body');
transferStyles($parent, $test, [
'letterSpacing',
'fontSize',
'fontFamily',
'fontWeight',
'textTransform'
]);
var width = $test.width();
$test.remove();
return width;
};
/**
* Sets up an input to grow horizontally as the user
* types. If the value is changed manually, you can
* trigger the "update" handler to resize:
*
* $input.trigger('update');
*
* @param {object} $input
*/
var autoGrow = function($input) {
var update = function(e) {
var value, keyCode, printable, placeholder, width;
var shift, character, selection;
e = e || window.event || {};
if (e.metaKey || e.altKey) return;
if ($input.data('grow') === false) return;
value = $input.val();
if (e.type && e.type.toLowerCase() === 'keydown') {
keyCode = e.keyCode;
printable = (
(keyCode >= 97 && keyCode <= 122) || // a-z
(keyCode >= 65 && keyCode <= 90) || // A-Z
(keyCode >= 48 && keyCode <= 57) || // 0-9
keyCode == 32 // space
);
if (keyCode === KEY_DELETE || keyCode === KEY_BACKSPACE) {
selection = getSelection($input[0]);
if (selection.length) {
value = value.substring(0, selection.start) + value.substring(selection.start + selection.length);
} else if (keyCode === KEY_BACKSPACE && selection.start) {
value = value.substring(0, selection.start - 1) + value.substring(selection.start + 1);
} else if (keyCode === KEY_DELETE && typeof selection.start !== 'undefined') {
value = value.substring(0, selection.start) + value.substring(selection.start + 1);
}
} else if (printable) {
shift = e.shiftKey;
character = String.fromCharCode(e.keyCode);
if (shift) character = character.toUpperCase();
else character = character.toLowerCase();
value += character;
}
}
placeholder = $input.attr('placeholder') || '';
if (!value.length && placeholder.length) {
value = placeholder;
}
width = measureString(value, $input) + 4;
if (width !== $input.width()) {
$input.width(width);
$input.triggerHandler('resize');
}
};
$input.on('keydown keyup update blur', update);
update();
};
/* --- file: "src/selectize.js" --- */
/**
* selectize.js
* Copyright (c) 2013 Brian Reavis & contributors
*
* 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.
*
* @author Brian Reavis <brian@thirdroute.com>
*/
var Selectize = function($input, settings) {
var key, i, n, self = this;
$input[0].selectize = self;
// setup default state
$.extend(self, {
settings : settings,
$input : $input,
tagType : $input[0].tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT,
highlightedValue : null,
isOpen : false,
isDisabled : false,
isLocked : false,
isFocused : false,
isInputFocused : false,
isInputHidden : false,
isSetup : false,
isShiftDown : false,
isCmdDown : false,
isCtrlDown : false,
ignoreFocus : false,
ignoreHover : false,
hasOptions : false,
currentResults : null,
lastValue : '',
caretPos : 0,
loading : 0,
loadedSearches : {},
$activeOption : null,
$activeItems : [],
optgroups : {},
options : {},
userOptions : {},
items : [],
renderCache : {},
onSearchChange : debounce(self.onSearchChange, settings.loadThrottle)
});
// build options table
$.extend(self.options, build_hash_table(settings.valueField, settings.options));
delete self.settings.options;
// build optgroup table
$.extend(self.optgroups, build_hash_table(settings.optgroupValueField, settings.optgroups));
delete self.settings.optgroups;
// option-dependent defaults
self.settings.mode = self.settings.mode || (self.settings.maxItems === 1 ? 'single' : 'multi');
if (typeof self.settings.hideSelected !== 'boolean') {
self.settings.hideSelected = self.settings.mode === 'multi';
}
self.loadPlugins(self.settings.plugins);
self.setupCallbacks();
self.setup();
};
// mixins
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MicroEvent.mixin(Selectize);
Plugins.mixin(Selectize, 'Selectize');
// methods
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
$.extend(Selectize.prototype, {
/**
* Creates all elements and sets up event bindings.
*/
setup: function() {
var self = this;
var settings = self.settings;
var $wrapper;
var $control;
var $control_input;
var $dropdown;
var $dropdown_content;
var $dropdown_parent;
var inputMode;
var timeout_blur;
var timeout_focus;
var tab_index;
var classes;
tab_index = self.$input.attr('tabindex') || '';
classes = self.$input.attr('class') || '';
$wrapper = $('<div>').addClass(settings.theme).addClass(settings.wrapperClass).addClass(classes);
$control = $('<div>').addClass(settings.inputClass).addClass('items').toggleClass('has-options', !$.isEmptyObject(self.options)).appendTo($wrapper);
$control_input = $('<input type="text">').appendTo($control).attr('tabindex',tab_index);
$dropdown_parent = $(settings.dropdownParent || $wrapper);
$dropdown = $('<div>').addClass(settings.dropdownClass).hide().appendTo($dropdown_parent);
$dropdown_content = $('<div>').addClass(settings.dropdownContentClass).appendTo($dropdown);
$wrapper.css({
width: self.$input[0].style.width,
display: self.$input.css('display')
});
if (self.plugins.length) {
$wrapper.addClass('plugin-' + self.plugins.join(' plugin-'));
}
inputMode = self.settings.mode;
$wrapper.toggleClass('single', inputMode === 'single');
$wrapper.toggleClass('multi', inputMode === 'multi');
if ((settings.maxItems === null || settings.maxItems > 1) && self.tagType === TAG_SELECT) {
self.$input.attr('multiple', 'multiple');
}
if (self.settings.placeholder) {
$control_input.attr('placeholder', settings.placeholder);
}
self.$wrapper = $wrapper;
self.$control = $control;
self.$control_input = $control_input;
self.$dropdown = $dropdown;
self.$dropdown_content = $dropdown_content;
$control.on('mousedown', function(e) {
if (!e.isDefaultPrevented()) {
window.setTimeout(function() {
self.focus(true);
}, 0);
}
});
// necessary for mobile webkit devices (manual focus triggering
// is ignored unless invoked within a click event)
$control.on('click', function(e) {
if (!self.isInputFocused) {
self.focus(true);
}
});
$dropdown.on('mouseenter', '[data-selectable]', function() { return self.onOptionHover.apply(self, arguments); });
$dropdown.on('mousedown', '[data-selectable]', function() { return self.onOptionSelect.apply(self, arguments); });
watchChildEvent($control, 'mousedown', '*:not(input)', function() { return self.onItemSelect.apply(self, arguments); });
autoGrow($control_input);
$control_input.on({
mousedown : function(e) { e.stopPropagation(); },
keydown : function() { return self.onKeyDown.apply(self, arguments); },
keyup : function() { return self.onKeyUp.apply(self, arguments); },
keypress : function() { return self.onKeyPress.apply(self, arguments); },
resize : function() { self.positionDropdown.apply(self, []); },
blur : function() { return self.onBlur.apply(self, arguments); },
focus : function() { return self.onFocus.apply(self, arguments); }
});
$(document).on({
keydown: function(e) {
self.isCmdDown = e[IS_MAC ? 'metaKey' : 'ctrlKey'];
self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey'];
self.isShiftDown = e.shiftKey;
},
keyup: function(e) {
if (e.keyCode === KEY_CTRL) self.isCtrlDown = false;
if (e.keyCode === KEY_SHIFT) self.isShiftDown = false;
if (e.keyCode === KEY_CMD) self.isCmdDown = false;
},
mousedown: function(e) {
if (self.isFocused) {
// prevent events on the dropdown scrollbar from causing the control to blur
if (e.target === self.$dropdown[0]) {
var ignoreFocus = self.ignoreFocus;
self.ignoreFocus = true;
window.setTimeout(function() {
self.ignoreFocus = ignoreFocus;
self.focus(false);
}, 0);
return;
}
// blur on click outside
if (!self.$control.has(e.target).length && e.target !== self.$control[0]) {
self.blur();
}
}
}
});
$(window).on({
resize: function() {
if (self.isOpen) {
self.positionDropdown.apply(self, arguments);
}
},
mousemove: function() {
self.ignoreHover = false;
}
});
self.$input.attr('tabindex',-1).hide().after(self.$wrapper);
if ($.isArray(settings.items)) {
self.setValue(settings.items);
delete settings.items;
}
self.updateOriginalInput();
self.refreshItems();
self.updatePlaceholder();
self.isSetup = true;
if (self.$input.is(':disabled')) {
self.disable();
}
self.trigger('initialize');
// preload options
if (settings.preload) {
self.onSearchChange('');
}
},
/**
* Maps fired events to callbacks provided
* in the settings used when creating the control.
*/
setupCallbacks: function() {
var key, fn, callbacks = {
'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'
};
for (key in callbacks) {
if (callbacks.hasOwnProperty(key)) {
fn = this.settings[callbacks[key]];
if (fn) this.on(key, fn);
}
}
},
/**
* Triggers a callback defined in the user-provided settings.
* Events: onItemAdd, onOptionAdd, etc
*
* @param {string} event
*/
triggerCallback: function(event) {
var args;
if (typeof this.settings[event] === 'function') {
args = Array.prototype.slice.apply(arguments, [1]);
this.settings[event].apply(this, args);
}
},
/**
* Triggered on <input> keypress.
*
* @param {object} e
* @returns {boolean}
*/
onKeyPress: function(e) {
if (this.isLocked) return e && e.preventDefault();
var character = String.fromCharCode(e.keyCode || e.which);
if (this.settings.create && character === this.settings.delimiter) {
this.createItem();
e.preventDefault();
return false;
}
},
/**
* Triggered on <input> keydown.
*
* @param {object} e
* @returns {boolean}
*/
onKeyDown: function(e) {
var isInput = e.target === this.$control_input[0];
var self = this;
if (self.isLocked) {
if (e.keyCode !== KEY_TAB) {
e.preventDefault();
}
return;
}
switch (e.keyCode) {
case KEY_A:
if (self.isCmdDown) {
self.selectAll();
e.preventDefault();
return;
}
break;
case KEY_ESC:
self.blur();
return;
case KEY_DOWN:
if (!self.isOpen && self.hasOptions) {
self.open();
} else if (self.$activeOption) {
self.ignoreHover = true;
var $next = self.getAdjacentOption(self.$activeOption, 1);
if ($next.length) self.setActiveOption($next, true, true);
}
e.preventDefault();
return;
case KEY_UP:
if (self.$activeOption) {
self.ignoreHover = true;
var $prev = self.getAdjacentOption(self.$activeOption, -1);
if ($prev.length) self.setActiveOption($prev, true, true);
}
e.preventDefault();
return;
case KEY_RETURN:
if (self.$activeOption) {
self.onOptionSelect({currentTarget: self.$activeOption});
}
e.preventDefault();
return;
case KEY_LEFT:
self.advanceSelection(-1, e);
return;
case KEY_RIGHT:
self.advanceSelection(1, e);
return;
case KEY_TAB:
if (self.settings.create && $.trim(self.$control_input.val()).length) {
self.createItem();
e.preventDefault();
}
return;
case KEY_BACKSPACE:
case KEY_DELETE:
self.deleteSelection(e);
return;
}
if (self.isFull() || self.isInputHidden) {
e.preventDefault();
return;
}
},
/**
* Triggered on <input> keyup.
*
* @param {object} e
* @returns {boolean}
*/
onKeyUp: function(e) {
var self = this;
if (self.isLocked) return e && e.preventDefault();
var value = self.$control_input.val() || '';
if (self.lastValue !== value) {
self.lastValue = value;
self.onSearchChange(value);
self.refreshOptions();
self.trigger('type', value);
}
},
/**
* Invokes the user-provide option provider / loader.
*
* Note: this function is debounced in the Selectize
* constructor (by `settings.loadDelay` milliseconds)
*
* @param {string} value
*/
onSearchChange: function(value) {
var self = this;
var fn = self.settings.load;
if (!fn) return;
if (self.loadedSearches.hasOwnProperty(value)) return;
self.loadedSearches[value] = true;
self.load(function(callback) {
fn.apply(self, [value, callback]);
});
},
/**
* Triggered on <input> focus.
*
* @param {object} e (optional)
* @returns {boolean}
*/
onFocus: function(e) {
var self = this;
self.isInputFocused = true;
self.isFocused = true;
if (self.isDisabled) {
self.blur();
e.preventDefault();
return false;
}
if (self.ignoreFocus) return;
if (self.settings.preload === 'focus') self.onSearchChange('');
self.showInput();
self.setActiveItem(null);
self.refreshOptions(!!self.settings.openOnFocus);
self.refreshClasses();
},
/**
* Triggered on <input> blur.
*
* @param {object} e
* @returns {boolean}
*/
onBlur: function(e) {
var self = this;
self.isInputFocused = false;
if (self.ignoreFocus) return;
self.close();
self.setTextboxValue('');
self.setActiveItem(null);
self.setActiveOption(null);
self.setCaret(self.items.length);
self.isFocused = false;
self.refreshClasses();
},
/**
* Triggered when the user rolls over
* an option in the autocomplete dropdown menu.
*
* @param {object} e
* @returns {boolean}
*/
onOptionHover: function(e) {
if (this.ignoreHover) return;
this.setActiveOption(e.currentTarget, false);
},
/**
* Triggered when the user clicks on an option
* in the autocomplete dropdown menu.
*
* @param {object} e
* @returns {boolean}
*/
onOptionSelect: function(e) {
var value, $target, $option, self = this;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
self.focus(false);
$target = $(e.currentTarget);
if ($target.hasClass('create')) {
self.createItem();
} else {
value = $target.attr('data-value');
if (value) {
self.setTextboxValue('');
self.addItem(value);
if (!self.settings.hideSelected && e.type && /mouse/.test(e.type)) {
self.setActiveOption(self.getOption(value));
}
}
}
},
/**
* Triggered when the user clicks on an item
* that has been selected.
*
* @param {object} e
* @returns {boolean}
*/
onItemSelect: function(e) {
var self = this;
if (self.settings.mode === 'multi') {
e.preventDefault();
self.setActiveItem(e.currentTarget, e);
self.focus(false);
self.hideInput();
}
},
/**
* Invokes the provided method that provides
* results to a callback---which are then added
* as options to the control.
*
* @param {function} fn
*/
load: function(fn) {
var self = this;
var $wrapper = self.$wrapper.addClass('loading');
self.loading++;
fn.apply(self, [function(results) {
self.loading = Math.max(self.loading - 1, 0);
if (results && results.length) {
self.addOption(results);
self.refreshOptions(false);
if (self.isInputFocused) self.open();
}
if (!self.loading) {
$wrapper.removeClass('loading');
}
self.trigger('load', results);
}]);
},
/**
* Sets the input field of the control to the specified value.
*
* @param {string} value
*/
setTextboxValue: function(value) {
this.$control_input.val(value).triggerHandler('update');
this.lastValue = value;
},
/**
* Returns the value of the control. If multiple items
* can be selected (e.g. <select multiple>), this returns
* an array. If only one item can be selected, this
* returns a string.
*
* @returns {mixed}
*/
getValue: function() {
if (this.tagType === TAG_SELECT && this.$input.attr('multiple')) {
return this.items;
} else {
return this.items.join(this.settings.delimiter);
}
},
/**
* Resets the selected items to the given value.
*
* @param {mixed} value
*/
setValue: function(value) {
debounce_events(this, ['change'], function() {
this.clear();
var items = $.isArray(value) ? value : [value];
for (var i = 0, n = items.length; i < n; i++) {
this.addItem(items[i]);
}
});
},
/**
* Sets the selected item.
*
* @param {object} $item
* @param {object} e (optional)
*/
setActiveItem: function($item, e) {
var self = this;
var eventName;
var i, idx, begin, end, item, swap;
var $last;
$item = $($item);
// clear the active selection
if (!$item.length) {
$(self.$activeItems).removeClass('active');
self.$activeItems = [];
self.isFocused = self.isInputFocused;
return;
}
// modify selection
eventName = e && e.type.toLowerCase();
if (eventName === 'mousedown' && self.isShiftDown && self.$activeItems.length) {
$last = self.$control.children('.active:last');
begin = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$last[0]]);
end = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$item[0]]);
if (begin > end) {
swap = begin;
begin = end;
end = swap;
}
for (i = begin; i <= end; i++) {
item = self.$control[0].childNodes[i];
if (self.$activeItems.indexOf(item) === -1) {
$(item).addClass('active');
self.$activeItems.push(item);
}
}
e.preventDefault();
} else if ((eventName === 'mousedown' && self.isCtrlDown) || (eventName === 'keydown' && this.isShiftDown)) {
if ($item.hasClass('active')) {
idx = self.$activeItems.indexOf($item[0]);
self.$activeItems.splice(idx, 1);
$item.removeClass('active');
} else {
self.$activeItems.push($item.addClass('active')[0]);
}
} else {
$(self.$activeItems).removeClass('active');
self.$activeItems = [$item.addClass('active')[0]];
}
self.isFocused = !!self.$activeItems.length || self.isInputFocused;
},
/**
* Sets the selected item in the dropdown menu
* of available options.
*
* @param {object} $object
* @param {boolean} scroll
* @param {boolean} animate
*/
setActiveOption: function($option, scroll, animate) {
var height_menu, height_item, y;
var scroll_top, scroll_bottom;
var self = this;
if (self.$activeOption) self.$activeOption.removeClass('active');
self.$activeOption = null;
$option = $($option);
if (!$option.length) return;
self.$activeOption = $option.addClass('active');
if (scroll || !isset(scroll)) {
height_menu = self.$dropdown_content.height();
height_item = self.$activeOption.outerHeight(true);
scroll = self.$dropdown_content.scrollTop() || 0;
y = self.$activeOption.offset().top - self.$dropdown_content.offset().top + scroll;
scroll_top = y;
scroll_bottom = y - height_menu + height_item;
if (y + height_item > height_menu - scroll) {
self.$dropdown_content.stop().animate({scrollTop: scroll_bottom}, animate ? self.settings.scrollDuration : 0);
} else if (y < scroll) {
self.$dropdown_content.stop().animate({scrollTop: scroll_top}, animate ? self.settings.scrollDuration : 0);
}
}
},
/**
* Selects all items (CTRL + A).
*/
selectAll: function() {
this.$activeItems = Array.prototype.slice.apply(this.$control.children(':not(input)').addClass('active'));
this.isFocused = true;
if (this.$activeItems.length) this.hideInput();
},
/**
* Hides the input element out of view, while
* retaining its focus.
*/
hideInput: function() {
var self = this;
self.close();
self.setTextboxValue('');
self.$control_input.css({opacity: 0, position: 'absolute', left: -10000});
self.isInputHidden = true;
},
/**
* Restores input visibility.
*/
showInput: function() {
this.$control_input.css({opacity: 1, position: 'relative', left: 0});
this.isInputHidden = false;
},
/**
* Gives the control focus. If "trigger" is falsy,
* focus handlers won't be fired--causing the focus
* to happen silently in the background.
*
* @param {boolean} trigger
*/
focus: function(trigger) {
var self = this;
if (self.isDisabled) return;
self.ignoreFocus = true;
self.$control_input[0].focus();
self.isInputFocused = true;
window.setTimeout(function() {
self.ignoreFocus = false;
if (trigger) self.onFocus();
}, 0);
},
/**
* Forces the control out of focus.
*/
blur: function() {
this.$control_input.trigger('blur');
},
/**
* Splits a search string into an array of
* individual regexps to be used to match results.
*
* @param {string} query
* @returns {array}
*/
parseSearchTokens: function(query) {
query = $.trim(String(query || '').toLowerCase());
if (!query || !query.length) return [];
var i, n, regex, letter;
var tokens = [];
var words = query.split(/ +/);
for (i = 0, n = words.length; i < n; i++) {
regex = escape_regex(words[i]);
if (this.settings.diacritics) {
for (letter in DIACRITICS) {
if (DIACRITICS.hasOwnProperty(letter)) {
regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]);
}
}
}
tokens.push({
string : words[i],
regex : new RegExp(regex, 'i')
});
}
return tokens;
},
/**
* Returns a function to be used to score individual results.
* Results will be sorted by the score (descending). Scores less
* than or equal to zero (no match) will not be included in the results.
*
* @param {object} data
* @param {object} search
* @returns {function}
*/
getScoreFunction: function(search) {
var self = this;
var tokens = search.tokens;
var calculateFieldScore = (function() {
if (!tokens.length) {
return function() { return 0; };
} else if (tokens.length === 1) {
return function(value) {
var score, pos;
value = String(value || '').toLowerCase();
pos = value.search(tokens[0].regex);
if (pos === -1) return 0;
score = tokens[0].string.length / value.length;
if (pos === 0) score += 0.5;
return score;
};
} else {
return function(value) {
var score, pos, i, j;
value = String(value || '').toLowerCase();
score = 0;
for (i = 0, j = tokens.length; i < j; i++) {
pos = value.search(tokens[i].regex);
if (pos === -1) return 0;
if (pos === 0) score += 0.5;
score += tokens[i].string.length / value.length;
}
return score / tokens.length;
};
}
})();
var calculateScore = (function() {
var fields = self.settings.searchField;
if (typeof fields === 'string') {
fields = [fields];
}
if (!fields || !fields.length) {
return function() { return 0; };
} else if (fields.length === 1) {
var field = fields[0];
return function(data) {
if (!data.hasOwnProperty(field)) return 0;
return calculateFieldScore(data[field]);
};
} else {
return function(data) {
var n = 0;
var score = 0;
for (var i = 0, j = fields.length; i < j; i++) {
if (data.hasOwnProperty(fields[i])) {
score += calculateFieldScore(data[fields[i]]);
n++;
}
}
return score / n;
};
}
})();
return calculateScore;
},
/**
* Searches through available options and returns
* a sorted array of matches. Includes options that
* have already been selected.
*
* The `settings` parameter can contain:
*
* - searchField
* - sortField
* - sortDirection
*
* Returns an object containing:
*
* - query {string}
* - tokens {array}
* - total {int}
* - items {array}
*
* @param {string} query
* @param {object} settings
* @returns {object}
*/
search: function(query, settings) {
var self = this;
var value, score, search, calculateScore;
settings = settings || {};
query = $.trim(String(query || '').toLowerCase());
if (query !== self.lastQuery) {
self.lastQuery = query;
search = {
query : query,
tokens : self.parseSearchTokens(query),
total : 0,
items : []
};
// generate result scoring function
if (self.settings.score) {
calculateScore = self.settings.score.apply(this, [search]);
if (typeof calculateScore !== 'function') {
throw new Error('Selectize "score" setting must be a function that returns a function');
}
} else {
calculateScore = self.getScoreFunction(search);
}
// perform search and sort
if (query.length) {
for (value in self.options) {
if (self.options.hasOwnProperty(value)) {
score = calculateScore(self.options[value]);
if (score > 0) {
search.items.push({
score: score,
value: value
});
}
}
}
search.items.sort(function(a, b) {
return b.score - a.score;
});
} else {
for (value in self.options) {
if (self.options.hasOwnProperty(value)) {
search.items.push({
score: 1,
value: value
});
}
}
if (self.settings.sortField) {
search.items.sort((function() {
var field = self.settings.sortField;
var multiplier = self.settings.sortDirection === 'desc' ? -1 : 1;
return function(a, b) {
a = a && String(self.options[a.value][field] || '').toLowerCase();
b = b && String(self.options[b.value][field] || '').toLowerCase();
if (a > b) return 1 * multiplier;
if (b > a) return -1 * multiplier;
return 0;
};
})());
}
}
self.currentResults = search;
} else {
search = $.extend(true, {}, self.currentResults);
}
// apply limits and return
return self.prepareResults(search, settings);
},
/**
* Filters out any items that have already been selected
* and applies search limits.
*
* @param {object} results
* @param {object} settings
* @returns {object}
*/
prepareResults: function(search, settings) {
if (this.settings.hideSelected) {
for (var i = search.items.length - 1; i >= 0; i--) {
if (this.items.indexOf(String(search.items[i].value)) !== -1) {
search.items.splice(i, 1);
}
}
}
search.total = search.items.length;
if (typeof settings.limit === 'number') {
search.items = search.items.slice(0, settings.limit);
}
return search;
},
/**
* Refreshes the list of available options shown
* in the autocomplete dropdown menu.
*
* @param {boolean} triggerDropdown
*/
refreshOptions: function(triggerDropdown) {
if (typeof triggerDropdown === 'undefined') {
triggerDropdown = true;
}
var self = this;
var i, n, groups, groups_order, option, optgroup, html, html_children;
var hasCreateOption;
var query = self.$control_input.val();
var results = self.search(query, {});
var $active, $create;
var $dropdown_content = self.$dropdown_content;
// build markup
n = results.items.length;
if (typeof self.settings.maxOptions === 'number') {
n = Math.min(n, self.settings.maxOptions);
}
// render and group available options individually
groups = {};
if (self.settings.optgroupOrder) {
groups_order = self.settings.optgroupOrder;
for (i = 0; i < groups_order.length; i++) {
groups[groups_order[i]] = [];
}
} else {
groups_order = [];
}
for (i = 0; i < n; i++) {
option = self.options[results.items[i].value];
optgroup = option[self.settings.optgroupField] || '';
if (!self.optgroups.hasOwnProperty(optgroup)) {
optgroup = '';
}
if (!groups.hasOwnProperty(optgroup)) {
groups[optgroup] = [];
groups_order.push(optgroup);
}
groups[optgroup].push(self.render('option', option));
}
// render optgroup headers & join groups
html = [];
for (i = 0, n = groups_order.length; i < n; i++) {
optgroup = groups_order[i];
if (self.optgroups.hasOwnProperty(optgroup) && groups[optgroup].length) {
// render the optgroup header and options within it,
// then pass it to the wrapper template
html_children = self.render('optgroup_header', self.optgroups[optgroup]) || '';
html_children += groups[optgroup].join('');
html.push(self.render('optgroup', $.extend({}, self.optgroups[optgroup], {
html: html_children
})));
} else {
html.push(groups[optgroup].join(''));
}
}
$dropdown_content.html(html.join(''));
// highlight matching terms inline
if (self.settings.highlight && results.query.length && results.tokens.length) {
for (i = 0, n = results.tokens.length; i < n; i++) {
highlight($dropdown_content, results.tokens[i].regex);
}
}
// add "selected" class to selected options
if (!self.settings.hideSelected) {
for (i = 0, n = self.items.length; i < n; i++) {
self.getOption(self.items[i]).addClass('selected');
}
}
// add create option
hasCreateOption = self.settings.create && results.query.length;
if (hasCreateOption) {
$dropdown_content.prepend(self.render('option_create', {input: query}));
$create = $($dropdown_content[0].childNodes[0]);
}
// activate
self.hasOptions = results.items.length > 0 || hasCreateOption;
if (self.hasOptions) {
if (results.items.length > 0) {
if ($create) {
$active = self.getAdjacentOption($create, 1);
} else {
$active = $dropdown_content.find("[data-selectable]").first();
}
} else {
$active = $create;
}
self.setActiveOption($active);
if (triggerDropdown && !self.isOpen) { self.open(); }
} else {
self.setActiveOption(null);
if (triggerDropdown && self.isOpen) { self.close(); }
}
},
/**
* Adds an available option. If it already exists,
* nothing will happen. Note: this does not refresh
* the options list dropdown (use `refreshOptions`
* for that).
*
* Usage:
*
* this.addOption(value, data)
* this.addOption(data)
*
* @param {string} value
* @param {object} data
*/
addOption: function(value, data) {
var i, n, optgroup, self = this;
if ($.isArray(value)) {
for (i = 0, n = value.length; i < n; i++) {
self.addOption(value[i][self.settings.valueField], value[i]);
}
return;
}
value = value || '';
if (self.options.hasOwnProperty(value)) return;
self.userOptions[value] = true;
self.options[value] = data;
self.lastQuery = null;
self.trigger('option_add', value, data);
},
/**
* Registers a new optgroup for options
* to be bucketed into.
*
* @param {string} id
* @param {object} data
*/
addOptionGroup: function(id, data) {
this.optgroups[id] = data;
this.trigger('optgroup_add', value, data);
},
/**
* Updates an option available for selection. If
* it is visible in the selected items or options
* dropdown, it will be re-rendered automatically.
*
* @param {string} value
* @param {object} data
*/
updateOption: function(value, data) {
var self = this;
var $item, $item_new;
value = String(value);
self.options[value] = data;
if (isset(self.renderCache['item'])) delete self.renderCache['item'][value];
if (isset(self.renderCache['option'])) delete self.renderCache['option'][value];
if (self.items.indexOf(value) !== -1) {
$item = self.getItem(value);
$item_new = $(self.render('item', data));
if ($item.hasClass('active')) $item_new.addClass('active');
$item.replaceWith($item_new);
}
if (self.isOpen) {
self.refreshOptions(false);
}
},
/**
* Removes a single option.
*
* @param {string} value
*/
removeOption: function(value) {
var self = this;
value = String(value);
delete self.userOptions[value];
delete self.options[value];
self.lastQuery = null;
self.trigger('option_remove', value);
self.removeItem(value);
},
/**
* Clears all options.
*/
clearOptions: function() {
var self = this;
self.loadedSearches = {};
self.userOptions = {};
self.options = {};
self.lastQuery = null;
self.trigger('option_clear');
self.clear();
},
/**
* Returns the jQuery element of the option
* matching the given value.
*
* @param {string} value
* @returns {object}
*/
getOption: function(value) {
return value ? this.$dropdown_content.find('[data-selectable]').filter('[data-value="' + value.replace(/(['"])/g, '\\$1') + '"]:first') : $();
},
/**
* Returns the jQuery element of the next or
* previous selectable option.
*
* @param {object} $option
* @param {int} direction can be 1 for next or -1 for previous
* @return {object}
*/
getAdjacentOption: function($option, direction) {
var $options = this.$dropdown.find('[data-selectable]');
var index = $options.index($option) + direction;
return index >= 0 && index < $options.length ? $options.eq(index) : $();
},
/**
* Returns the jQuery element of the item
* matching the given value.
*
* @param {string} value
* @returns {object}
*/
getItem: function(value) {
var i = this.items.indexOf(value);
if (i !== -1) {
if (i >= this.caretPos) i++;
var $el = $(this.$control[0].childNodes[i]);
if ($el.attr('data-value') === value) {
return $el;
}
}
return $();
},
/**
* "Selects" an item. Adds it to the list
* at the current caret position.
*
* @param {string} value
*/
addItem: function(value) {
debounce_events(this, ['change'], function() {
var $item, $option;
var self = this;
var inputMode = self.settings.mode;
var i, active, options, value_next;
value = String(value);
if (inputMode === 'single') self.clear();
if (inputMode === 'multi' && self.isFull()) return;
if (self.items.indexOf(value) !== -1) return;
if (!self.options.hasOwnProperty(value)) return;
$item = $(self.render('item', self.options[value]));
self.items.splice(self.caretPos, 0, value);
self.insertAtCaret($item);
self.refreshClasses();
if (self.isSetup) {
options = self.$dropdown_content.find('[data-selectable]');
// update menu / remove the option
$option = self.getOption(value);
value_next = self.getAdjacentOption($option, 1).attr('data-value');
self.refreshOptions(true);
if (value_next) {
self.setActiveOption(self.getOption(value_next));
}
// hide the menu if the maximum number of items have been selected or no options are left
if (!options.length || (self.settings.maxItems !== null && self.items.length >= self.settings.maxItems)) {
self.close();
} else {
self.positionDropdown();
}
// restore focus to input
if (self.isFocused) {
window.setTimeout(function() {
if (inputMode === 'single') {
self.blur();
self.focus(false);
self.hideInput();
} else {
self.focus(false);
}
}, 0);
}
self.updatePlaceholder();
self.trigger('item_add', value, $item);
self.updateOriginalInput();
}
});
},
/**
* Removes the selected item matching
* the provided value.
*
* @param {string} value
*/
removeItem: function(value) {
var self = this;
var $item, i, idx;
$item = (typeof value === 'object') ? value : self.getItem(value);
value = String($item.attr('data-value'));
i = self.items.indexOf(value);
if (i !== -1) {
$item.remove();
if ($item.hasClass('active')) {
idx = self.$activeItems.indexOf($item[0]);
self.$activeItems.splice(idx, 1);
}
self.items.splice(i, 1);
self.lastQuery = null;
if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
self.removeOption(value);
}
if (i < self.caretPos) {
self.setCaret(self.caretPos - 1);
}
self.refreshClasses();
self.updatePlaceholder();
self.updateOriginalInput();
self.positionDropdown();
self.trigger('item_remove', value);
}
},
/**
* Invokes the `create` method provided in the
* selectize options that should provide the data
* for the new item, given the user input.
*
* Once this completes, it will be added
* to the item list.
*/
createItem: function() {
var self = this;
var input = $.trim(self.$control_input.val() || '');
var caret = self.caretPos;
if (!input.length) return;
self.lock();
var setup = (typeof self.settings.create === 'function') ? this.settings.create : function(input) {
var data = {};
data[self.settings.labelField] = input;
data[self.settings.valueField] = input;
return data;
};
var create = once(function(data) {
self.unlock();
self.focus(false);
var value = data && data[self.settings.valueField];
if (!value) return;
self.setTextboxValue('');
self.addOption(value, data);
self.setCaret(caret);
self.addItem(value);
self.refreshOptions(true);
self.focus(false);
});
var output = setup.apply(this, [input, create]);
if (typeof output !== 'undefined') {
create(output);
}
},
/**
* Re-renders the selected item lists.
*/
refreshItems: function() {
this.lastQuery = null;
if (this.isSetup) {
for (var i = 0; i < this.items.length; i++) {
this.addItem(this.items);
}
}
this.refreshClasses();
this.updateOriginalInput();
},
/**
* Updates all state-dependent CSS classes.
*/
refreshClasses: function() {
var isFull = this.isFull();
var isLocked = this.isLocked;
this.$control
.toggleClass('focus', this.isFocused)
.toggleClass('disabled', this.isDisabled)
.toggleClass('locked', isLocked)
.toggleClass('full', isFull).toggleClass('not-full', !isFull)
.toggleClass('has-items', this.items.length > 0);
this.$control_input.data('grow', !isFull && !isLocked);
},
/**
* Determines whether or not more items can be added
* to the control without exceeding the user-defined maximum.
*
* @returns {boolean}
*/
isFull: function() {
return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
},
/**
* Refreshes the original <select> or <input>
* element to reflect the current state.
*/
updateOriginalInput: function() {
var i, n, options, self = this;
if (self.$input[0].tagName.toLowerCase() === 'select') {
options = [];
for (i = 0, n = self.items.length; i < n; i++) {
options.push('<option value="' + escape_html(self.items[i]) + '" selected="selected"></option>');
}
if (!options.length && !this.$input.attr('multiple')) {
options.push('<option value="" selected="selected"></option>');
}
self.$input.html(options.join(''));
} else {
self.$input.val(self.getValue());
}
self.$input.trigger('change');
if (self.isSetup) {
self.trigger('change', self.$input.val());
}
},
/**
* Shows/hide the input placeholder depending
* on if there items in the list already.
*/
updatePlaceholder: function() {
if (!this.settings.placeholder) return;
var $input = this.$control_input;
if (this.items.length) {
$input.removeAttr('placeholder');
} else {
$input.attr('placeholder', this.settings.placeholder);
}
$input.triggerHandler('update');
},
/**
* Shows the autocomplete dropdown containing
* the available options.
*/
open: function() {
var self = this;
if (self.isLocked || self.isOpen || (self.settings.mode === 'multi' && self.isFull())) return;
self.focus();
self.isOpen = true;
self.$dropdown.css({visibility: 'hidden', display: 'block'});
self.$control.addClass('dropdown-active');
self.positionDropdown();
self.$dropdown.css({visibility: 'visible'});
self.trigger('dropdown_open', this.$dropdown);
},
/**
* Closes the autocomplete dropdown menu.
*/
close: function() {
var self = this;
if (!self.isOpen) return;
self.$dropdown.hide();
self.$control.removeClass('dropdown-active');
self.setActiveOption(null);
self.isOpen = false;
self.trigger('dropdown_close', self.$dropdown);
},
/**
* Calculates and applies the appropriate
* position of the dropdown.
*/
positionDropdown: function() {
var $control = this.$control;
var offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position();
offset.top += $control.outerHeight(true);
this.$dropdown.css({
width : $control.outerWidth(),
top : offset.top,
left : offset.left
});
},
/**
* Resets / clears all selected items
* from the control.
*/
clear: function() {
var self = this;
if (!self.items.length) return;
self.$control.children(':not(input)').remove();
self.items = [];
self.setCaret(0);
self.updatePlaceholder();
self.updateOriginalInput();
self.refreshClasses();
self.showInput();
self.trigger('clear');
},
/**
* A helper method for inserting an element
* at the current caret position.
*
* @param {object} $el
*/
insertAtCaret: function($el) {
var caret = Math.min(this.caretPos, this.items.length);
if (caret === 0) {
this.$control.prepend($el);
} else {
$(this.$control[0].childNodes[caret]).before($el);
}
this.setCaret(caret + 1);
},
/**
* Removes the current selected item(s).
*
* @param {object} e (optional)
* @returns {boolean}
*/
deleteSelection: function(e) {
var i, n, direction, selection, values, caret, option_select, $option_select, $tail;
var self = this;
direction = (e && e.keyCode === KEY_BACKSPACE) ? -1 : 1;
selection = getSelection(self.$control_input[0]);
if (self.$activeOption && !self.settings.hideSelected) {
option_select = self.getAdjacentOption(self.$activeOption, -1).attr('data-value');
}
// determine items that will be removed
values = [];
if (self.$activeItems.length) {
$tail = self.$control.children('.active:' + (direction > 0 ? 'last' : 'first'));
caret = self.$control.children(':not(input)').index($tail);
if (direction > 0) { caret++; }
for (i = 0, n = self.$activeItems.length; i < n; i++) {
values.push($(self.$activeItems[i]).attr('data-value'));
}
if (e) {
e.preventDefault();
e.stopPropagation();
}
} else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
if (direction < 0 && selection.start === 0 && selection.length === 0) {
values.push(self.items[self.caretPos - 1]);
} else if (direction > 0 && selection.start === self.$control_input.val().length) {
values.push(self.items[self.caretPos]);
}
}
// allow the callback to abort
if (!values.length || (typeof self.settings.onDelete === 'function' && self.settings.onDelete(values) === false)) {
return false;
}
// perform removal
if (typeof caret !== 'undefined') {
self.setCaret(caret);
}
while (values.length) {
self.removeItem(values.pop());
}
self.showInput();
self.refreshOptions(true);
// select previous option
if (option_select) {
$option_select = self.getOption(option_select);
if ($option_select.length) {
self.setActiveOption($option_select);
}
}
return true;
},
/**
* Selects the previous / next item (depending
* on the `direction` argument).
*
* > 0 - right
* < 0 - left
*
* @param {int} direction
* @param {object} e (optional)
*/
advanceSelection: function(direction, e) {
var tail, selection, idx, valueLength, cursorAtEdge, $tail;
var self = this;
if (direction === 0) return;
tail = direction > 0 ? 'last' : 'first';
selection = getSelection(self.$control_input[0]);
if (self.isInputFocused && !self.isInputHidden) {
valueLength = self.$control_input.val().length;
cursorAtEdge = direction < 0
? selection.start === 0 && selection.length === 0
: selection.start === valueLength;
if (cursorAtEdge && !valueLength) {
self.advanceCaret(direction, e);
}
} else {
$tail = self.$control.children('.active:' + tail);
if ($tail.length) {
idx = self.$control.children(':not(input)').index($tail);
self.setActiveItem(null);
self.setCaret(direction > 0 ? idx + 1 : idx);
self.showInput();
}
}
},
/**
* Moves the caret left / right.
*
* @param {int} direction
* @param {object} e (optional)
*/
advanceCaret: function(direction, e) {
if (direction === 0) return;
var self = this;
var fn = direction > 0 ? 'next' : 'prev';
if (self.isShiftDown) {
var $adj = self.$control_input[fn]();
if ($adj.length) {
self.hideInput();
self.setActiveItem($adj);
e && e.preventDefault();
}
} else {
self.setCaret(self.caretPos + direction);
}
},
/**
* Moves the caret to the specified index.
*
* @param {int} i
*/
setCaret: function(i) {
var self = this;
if (self.settings.mode === 'single') {
i = self.items.length;
} else {
i = Math.max(0, Math.min(self.items.length, i));
}
// the input must be moved by leaving it in place and moving the
// siblings, due to the fact that focus cannot be restored once lost
// on mobile webkit devices
var j, n, fn, $children, $child;
$children = self.$control.children(':not(input)');
for (j = 0, n = $children.length; j < n; j++) {
$child = $($children[j]).detach();
if (j < i) {
self.$control_input.before($child);
} else {
self.$control.append($child);
}
}
self.caretPos = i;
},
/**
* Disables user input on the control. Used while
* items are being asynchronously created.
*/
lock: function() {
this.close();
this.isLocked = true;
this.refreshClasses();
},
/**
* Re-enables user input on the control.
*/
unlock: function() {
this.isLocked = false;
this.refreshClasses();
},
/**
* Disables user input on the control completely.
* While disabled, it cannot receive focus.
*/
disable: function() {
this.isDisabled = true;
this.lock();
},
/**
* Enables the control so that it can respond
* to focus and user input.
*/
enable: function() {
this.isDisabled = false;
this.unlock();
},
/**
* A helper method for rendering "item" and
* "option" templates, given the data.
*
* @param {string} templateName
* @param {object} data
* @returns {string}
*/
render: function(templateName, data) {
var value, id, label;
var html = '';
var cache = false;
var self = this;
var regex_tag = /^[\ ]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;
if (templateName === 'option' || templateName === 'item') {
value = data[self.settings.valueField];
cache = isset(value);
}
// pull markup from cache if it exists
if (cache) {
if (!isset(self.renderCache[templateName])) {
self.renderCache[templateName] = {};
}
if (self.renderCache[templateName].hasOwnProperty(value)) {
return self.renderCache[templateName][value];
}
}
// render markup
if (self.settings.render && typeof self.settings.render[templateName] === 'function') {
html = self.settings.render[templateName].apply(this, [data, escape_html]);
} else {
label = data[self.settings.labelField];
switch (templateName) {
case 'optgroup':
html = '<div class="optgroup">' + data.html + "</div>";
break;
case 'optgroup_header':
label = data[self.settings.optgroupLabelField];
html = '<div class="optgroup-header">' + escape_html(label) + '</div>';
break;
case 'option':
html = '<div class="option">' + escape_html(label) + '</div>';
break;
case 'item':
html = '<div class="item">' + escape_html(label) + '</div>';
break;
case 'option_create':
html = '<div class="create">Add <strong>' + escape_html(data.input) + '</strong>…</div>';
break;
}
}
// add mandatory attributes
if (templateName === 'option' || templateName === 'option_create') {
html = html.replace(regex_tag, '<$1 data-selectable');
}
if (templateName === 'optgroup') {
id = data[self.settings.optgroupValueField] || '';
html = html.replace(regex_tag, '<$1 data-group="' + escape_html(id) + '"');
}
if (templateName === 'option' || templateName === 'item') {
html = html.replace(regex_tag, '<$1 data-value="' + escape_html(value || '') + '"');
}
// update cache
if (cache) {
self.renderCache[templateName][value] = html;
}
return html;
}
});
Selectize.defaults = {
plugins: [],
delimiter: ',',
persist: true,
diacritics: true,
create: false,
highlight: true,
openOnFocus: true,
maxOptions: 1000,
maxItems: null,
hideSelected: null,
preload: false,
scrollDuration: 60,
loadThrottle: 300,
dataAttr: 'data-data',
optgroupField: 'optgroup',
sortField: null,
sortDirection: 'asc',
valueField: 'value',
labelField: 'text',
optgroupLabelField: 'label',
optgroupValueField: 'value',
optgroupOrder: null,
searchField: ['text'],
mode: null,
theme: 'default',
wrapperClass: 'selectize-control',
inputClass: 'selectize-input',
dropdownClass: 'selectize-dropdown',
dropdownContentClass: 'selectize-dropdown-content',
dropdownParent: null,
/*
load : null, // function(query, callback) { ... }
score : null, // function(search) { ... }
onInitialize : null, // function() { ... }
onChange : null, // function(value) { ... }
onItemAdd : null, // function(value, $item) { ... }
onItemRemove : null, // function(value) { ... }
onClear : null, // function() { ... }
onOptionAdd : null, // function(value, data) { ... }
onOptionRemove : null, // function(value) { ... }
onOptionClear : null, // function() { ... }
onDropdownOpen : null, // function($dropdown) { ... }
onDropdownClose : null, // function($dropdown) { ... }
onType : null, // function(str) { ... }
onDelete : null, // function(values) { ... }
*/
render: {
/*
item: null,
optgroup: null,
optgroup_header: null,
option: null,
option_create: null
*/
}
};
/* --- file: "src/selectize.jquery.js" --- */
$.fn.selectize = function(settings) {
settings = settings || {};
var defaults = $.fn.selectize.defaults;
var dataAttr = settings.dataAttr || defaults.dataAttr;
/**
* Initializes selectize from a <input type="text"> element.
*
* @param {object} $input
* @param {object} settings
*/
var init_textbox = function($input, settings_element) {
var i, n, values, value = $.trim($input.val() || '');
if (!value.length) return;
values = value.split(settings.delimiter || defaults.delimiter);
for (i = 0, n = values.length; i < n; i++) {
settings_element.options[values[i]] = {
'text' : values[i],
'value' : values[i]
};
}
settings_element.items = values;
};
/**
* Initializes selectize from a <select> element.
*
* @param {object} $input
* @param {object} settings
*/
var init_select = function($input, settings_element) {
var i, n, tagName;
var $children;
settings_element.maxItems = !!$input.attr('multiple') ? null : 1;
var readData = function($el) {
var data = dataAttr && $el.attr(dataAttr);
if (typeof data === 'string' && data.length) {
return JSON.parse(data);
}
return null;
};
var addOption = function($option, group) {
$option = $($option);
var value = $option.attr('value') || '';
if (!value.length) return;
settings_element.options[value] = readData($option) || {
'text' : $option.html(),
'value' : value,
'optgroup' : group
};
if ($option.is(':selected')) {
settings_element.items.push(value);
}
};
var addGroup = function($optgroup) {
var i, n, $options = $('option', $optgroup);
$optgroup = $($optgroup);
var id = $optgroup.attr('label');
if (id && id.length) {
settings_element.optgroups[id] = readData($optgroup) || {
'label': id
};
}
for (i = 0, n = $options.length; i < n; i++) {
addOption($options[i], id);
}
};
$children = $input.children();
for (i = 0, n = $children.length; i < n; i++) {
tagName = $children[i].tagName.toLowerCase();
if (tagName === 'optgroup') {
addGroup($children[i]);
} else if (tagName === 'option') {
addOption($children[i]);
}
}
};
return this.each(function() {
var instance;
var $input = $(this);
var tag_name = $input[0].tagName.toLowerCase();
var settings_element = {
'placeholder' : $input.attr('placeholder'),
'options' : {},
'optgroups' : {},
'items' : []
};
if (tag_name === 'select') {
init_select($input, settings_element);
} else {
init_textbox($input, settings_element);
}
instance = new Selectize($input, $.extend(true, {}, defaults, settings_element, settings));
$input.data('selectize', instance);
$input.addClass('selectized');
});
};
$.fn.selectize.defaults = Selectize.defaults;
/* --- file: "src/plugins/drag_drop/plugin.js" --- */
/**
* Plugin: "drag_drop" (selectize.js)
* Copyright (c) 2013 Brian Reavis & contributors
*
* 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.
*
* @author Brian Reavis <brian@thirdroute.com>
*/
Selectize.registerPlugin('drag_drop', function(options) {
if (!$.fn.sortable) throw new Error('The "drag_drop" Selectize plugin requires jQuery UI "sortable".');
if (this.settings.mode !== 'multi') return;
var self = this;
this.setup = (function() {
var original = self.setup;
return function() {
original.apply(this, arguments);
var $control = this.$control.sortable({
items: '[data-value]',
forcePlaceholderSize: true,
start: function(e, ui) {
ui.placeholder.css('width', ui.helper.css('width'));
$control.css({overflow: 'visible'});
},
stop: function() {
$control.css({overflow: 'hidden'});
var active = this.$activeItems ? this.$activeItems.slice() : null;
var values = [];
$control.children('[data-value]').each(function() {
values.push($(this).attr('data-value'));
});
self.setValue(values);
self.setActiveItem(active);
}
});
};
})();
});
/* --- file: "src/plugins/dropdown_header/plugin.js" --- */
/**
* Plugin: "dropdown_header" (selectize.js)
* Copyright (c) 2013 Brian Reavis & contributors
*
* 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.
*
* @author Brian Reavis <brian@thirdroute.com>
*/
Selectize.registerPlugin('dropdown_header', function(options) {
var self = this;
options = $.extend({
title : 'Untitled',
headerClass : 'selectize-dropdown-header',
titleRowClass : 'selectize-dropdown-header-title',
labelClass : 'selectize-dropdown-header-label',
closeClass : 'selectize-dropdown-header-close',
html: function(data) {
return (
'<div class="' + data.headerClass + '">' +
'<div class="' + data.titleRowClass + '">' +
'<span class="' + data.labelClass + '">' + data.title + '</span>' +
'<a href="javascript:void(0)" class="' + data.closeClass + '">×</a>' +
'</div>' +
'</div>'
);
}
}, options);
self.setup = (function() {
var original = self.setup;
return function() {
original.apply(self, arguments);
self.$dropdown_header = $(options.html(options));
self.$dropdown.prepend(self.$dropdown_header);
};
})();
});
/* --- file: "src/plugins/optgroup_columns/plugin.js" --- */
/**
* Plugin: "optgroup_columns" (selectize.js)
* Copyright (c) 2013 Simon Hewitt & contributors
*
* 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.
*
* @author Simon Hewitt <si@sjhewitt.co.uk>
*/
Selectize.registerPlugin('optgroup_columns', function(options) {
var self = this;
options = $.extend({
equalizeWidth : true,
equalizeHeight : true
}, options);
this.getAdjacentOption = function($option, direction) {
var $options = $option.closest('[data-group]').find('[data-selectable]');
var index = $options.index($option) + direction;
return index >= 0 && index < $options.length ? $options.eq(index) : $();
};
this.onKeyDown = (function() {
var original = self.onKeyDown;
return function(e) {
var index, $option, $options, $optgroup;
if (this.isOpen && (e.keyCode === KEY_LEFT || e.keyCode === KEY_RIGHT)) {
self.ignoreHover = true;
$optgroup = this.$activeOption.closest('[data-group]');
index = $optgroup.find('[data-selectable]').index(this.$activeOption);
if(e.keyCode === KEY_LEFT) {
$optgroup = $optgroup.prev('[data-group]');
} else {
$optgroup = $optgroup.next('[data-group]');
}
$options = $optgroup.find('[data-selectable]');
$option = $options.eq(Math.min($options.length - 1, index));
if ($option.length) {
this.setActiveOption($option);
}
return;
}
return original.apply(this, arguments);
};
})();
var equalizeSizes = function() {
var i, n, height_max, width, width_last, width_parent, $optgroups;
$optgroups = $('[data-group]', self.$dropdown_content);
n = $optgroups.length;
if (!n || !self.$dropdown_content.width()) return;
if (options.equalizeHeight) {
height_max = 0;
for (i = 0; i < n; i++) {
height_max = Math.max(height_max, $optgroups.eq(i).height());
}
$optgroups.css({height: height_max});
}
if (options.equalizeWidth) {
width_parent = self.$dropdown_content.innerWidth();
width = Math.round(width_parent / n);
$optgroups.css({width: width});
if (n > 1) {
width_last = width_parent - width * (n - 1);
$optgroups.eq(n - 1).css({width: width_last});
}
}
};
if (options.equalizeHeight || options.equalizeWidth) {
hook.after(this, 'positionDropdown', equalizeSizes);
hook.after(this, 'refreshOptions', equalizeSizes);
}
});
/* --- file: "src/plugins/remove_button/plugin.js" --- */
/**
* Plugin: "remove_button" (selectize.js)
* Copyright (c) 2013 Brian Reavis & contributors
*
* 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.
*
* @author Brian Reavis <brian@thirdroute.com>
*/
Selectize.registerPlugin('remove_button', function(options) {
var self = this;
// override the item rendering method to add a "x" to each
this.settings.render.item = function(data) {
var label = data[self.settings.labelField];
return '<div class="item">' + label + ' <a href="javascript:void(0)" class="remove" tabindex="-1" title="Remove">×</a></div>';
};
// override the setup method to add an extra "click" handler
// that listens for mousedown events on the "x"
this.setup = (function() {
var original = self.setup;
return function() {
original.apply(this, arguments);
this.$control.on('click', '.remove', function(e) {
e.preventDefault();
var $item = $(e.target).parent();
self.setActiveItem($item);
if (self.deleteSelection()) {
self.setCaret(self.items.length);
}
});
};
})();
});
/* --- file: "src/plugins/restore_on_backspace/plugin.js" --- */
/**
* Plugin: "restore_on_backspace" (selectize.js)
* Copyright (c) 2013 Brian Reavis & contributors
*
* 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.
*
* @author Brian Reavis <brian@thirdroute.com>
*/
Selectize.registerPlugin('restore_on_backspace', function(options) {
var self = this;
options.text = options.text || function(option) {
return option[this.settings.labelField];
};
this.onKeyDown = (function(e) {
var original = self.onKeyDown;
return function(e) {
var index, option;
if (e.keyCode === KEY_BACKSPACE && this.$control_input.val() === '' && !this.$activeItems.length) {
index = this.caretPos - 1;
if (index >= 0 && index < this.items.length) {
option = this.options[this.items[index]];
if (this.deleteSelection(e)) {
this.setTextboxValue(options.text.apply(this, [option]));
this.refreshOptions(true);
}
e.preventDefault();
return;
}
}
return original.apply(this, arguments);
};
})();
});
return Selectize;
}));
|
/*istanbul ignore next*/"use strict";
var /*istanbul ignore next*/_index = require("../index");
/*istanbul ignore next*/
var t = _interopRequireWildcard(_index);
var /*istanbul ignore next*/_constants = require("../constants");
var /*istanbul ignore next*/_index2 = require("./index");
/*istanbul ignore next*/
var _index3 = _interopRequireDefault(_index2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/*istanbul ignore next*/(0, _index3.default)("ArrayExpression", {
fields: {
elements: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeOrValueType)("null", "Expression", "SpreadElement"))),
default: []
}
},
visitor: ["elements"],
aliases: ["Expression"]
}); /* eslint max-len: 0 */
/*istanbul ignore next*/(0, _index3.default)("AssignmentExpression", {
fields: {
operator: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("string")
},
left: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("LVal")
},
right: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
}
},
builder: ["operator", "left", "right"],
visitor: ["left", "right"],
aliases: ["Expression"]
});
/*istanbul ignore next*/(0, _index3.default)("BinaryExpression", {
builder: ["operator", "left", "right"],
fields: {
operator: {
validate: /*istanbul ignore next*/_index2.assertOneOf.apply( /*istanbul ignore next*/undefined, /*istanbul ignore next*/_constants.BINARY_OPERATORS)
},
left: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
right: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
}
},
visitor: ["left", "right"],
aliases: ["Binary", "Expression"]
});
/*istanbul ignore next*/(0, _index3.default)("Directive", {
visitor: ["value"],
fields: {
value: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("DirectiveLiteral")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("DirectiveLiteral", {
builder: ["value"],
fields: {
value: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("string")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("BlockStatement", {
builder: ["body", "directives"],
visitor: ["directives", "body"],
fields: {
directives: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Directive"))),
default: []
},
body: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Statement")))
}
},
aliases: ["Scopable", "BlockParent", "Block", "Statement"]
});
/*istanbul ignore next*/(0, _index3.default)("BreakStatement", {
visitor: ["label"],
fields: {
label: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Identifier"),
optional: true
}
},
aliases: ["Statement", "Terminatorless", "CompletionStatement"]
});
/*istanbul ignore next*/(0, _index3.default)("CallExpression", {
visitor: ["callee", "arguments"],
fields: {
callee: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
arguments: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression", "SpreadElement")))
}
},
aliases: ["Expression"]
});
/*istanbul ignore next*/(0, _index3.default)("CatchClause", {
visitor: ["param", "body"],
fields: {
param: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Identifier")
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("BlockStatement")
}
},
aliases: ["Scopable"]
});
/*istanbul ignore next*/(0, _index3.default)("ConditionalExpression", {
visitor: ["test", "consequent", "alternate"],
fields: {
test: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
consequent: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
alternate: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
}
},
aliases: ["Expression", "Conditional"]
});
/*istanbul ignore next*/(0, _index3.default)("ContinueStatement", {
visitor: ["label"],
fields: {
label: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Identifier"),
optional: true
}
},
aliases: ["Statement", "Terminatorless", "CompletionStatement"]
});
/*istanbul ignore next*/(0, _index3.default)("DebuggerStatement", {
aliases: ["Statement"]
});
/*istanbul ignore next*/(0, _index3.default)("DoWhileStatement", {
visitor: ["test", "body"],
fields: {
test: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Statement")
}
},
aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"]
});
/*istanbul ignore next*/(0, _index3.default)("EmptyStatement", {
aliases: ["Statement"]
});
/*istanbul ignore next*/(0, _index3.default)("ExpressionStatement", {
visitor: ["expression"],
fields: {
expression: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
}
},
aliases: ["Statement", "ExpressionWrapper"]
});
/*istanbul ignore next*/(0, _index3.default)("File", {
builder: ["program", "comments", "tokens"],
visitor: ["program"],
fields: {
program: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Program")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("ForInStatement", {
visitor: ["left", "right", "body"],
aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"],
fields: {
left: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("VariableDeclaration", "LVal")
},
right: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Statement")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("ForStatement", {
visitor: ["init", "test", "update", "body"],
aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"],
fields: {
init: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("VariableDeclaration", "Expression"),
optional: true
},
test: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression"),
optional: true
},
update: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression"),
optional: true
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Statement")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("FunctionDeclaration", {
builder: ["id", "params", "body", "generator", "async"],
visitor: ["id", "params", "body", "returnType", "typeParameters"],
fields: {
id: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Identifier")
},
params: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("LVal")))
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("BlockStatement")
},
generator: {
default: false,
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean")
},
async: {
default: false,
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean")
}
},
aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"]
});
/*istanbul ignore next*/(0, _index3.default)("FunctionExpression", {
inherits: "FunctionDeclaration",
aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"],
fields: {
id: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Identifier"),
optional: true
},
params: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("LVal")))
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("BlockStatement")
},
generator: {
default: false,
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean")
},
async: {
default: false,
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("Identifier", {
builder: ["name"],
visitor: ["typeAnnotation"],
aliases: ["Expression", "LVal"],
fields: {
name: { /*istanbul ignore next*/
validate: function validate(node, key, val) {
if (!t.isValidIdentifier(val)) {
// todo
}
}
}
}
});
/*istanbul ignore next*/(0, _index3.default)("IfStatement", {
visitor: ["test", "consequent", "alternate"],
aliases: ["Statement", "Conditional"],
fields: {
test: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
consequent: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Statement")
},
alternate: {
optional: true,
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Statement")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("LabeledStatement", {
visitor: ["label", "body"],
aliases: ["Statement"],
fields: {
label: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Identifier")
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Statement")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("StringLiteral", {
builder: ["value"],
fields: {
value: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("string")
}
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
});
/*istanbul ignore next*/(0, _index3.default)("NumericLiteral", {
builder: ["value"],
deprecatedAlias: "NumberLiteral",
fields: {
value: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("number")
}
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
});
/*istanbul ignore next*/(0, _index3.default)("NullLiteral", {
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
});
/*istanbul ignore next*/(0, _index3.default)("BooleanLiteral", {
builder: ["value"],
fields: {
value: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean")
}
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
});
/*istanbul ignore next*/(0, _index3.default)("RegExpLiteral", {
builder: ["pattern", "flags"],
deprecatedAlias: "RegexLiteral",
aliases: ["Expression", "Literal"],
fields: {
pattern: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("string")
},
flags: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("string"),
default: ""
}
}
});
/*istanbul ignore next*/(0, _index3.default)("LogicalExpression", {
builder: ["operator", "left", "right"],
visitor: ["left", "right"],
aliases: ["Binary", "Expression"],
fields: {
operator: {
validate: /*istanbul ignore next*/_index2.assertOneOf.apply( /*istanbul ignore next*/undefined, /*istanbul ignore next*/_constants.LOGICAL_OPERATORS)
},
left: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
right: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("MemberExpression", {
builder: ["object", "property", "computed"],
visitor: ["object", "property"],
aliases: ["Expression", "LVal"],
fields: {
object: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
property: { /*istanbul ignore next*/
validate: function validate(node, key, val) {
var expectedType = node.computed ? "Expression" : "Identifier";
/*istanbul ignore next*/(0, _index2.assertNodeType)(expectedType)(node, key, val);
}
},
computed: {
default: false
}
}
});
/*istanbul ignore next*/(0, _index3.default)("NewExpression", {
visitor: ["callee", "arguments"],
aliases: ["Expression"],
fields: {
callee: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
arguments: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression", "SpreadElement")))
}
}
});
/*istanbul ignore next*/(0, _index3.default)("Program", {
visitor: ["directives", "body"],
builder: ["body", "directives"],
fields: {
directives: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Directive"))),
default: []
},
body: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Statement")))
}
},
aliases: ["Scopable", "BlockParent", "Block", "FunctionParent"]
});
/*istanbul ignore next*/(0, _index3.default)("ObjectExpression", {
visitor: ["properties"],
aliases: ["Expression"],
fields: {
properties: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadProperty")))
}
}
});
/*istanbul ignore next*/(0, _index3.default)("ObjectMethod", {
builder: ["kind", "key", "params", "body", "computed"],
fields: {
kind: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("string"), /*istanbul ignore next*/(0, _index2.assertOneOf)("method", "get", "set")),
default: "method"
},
computed: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean"),
default: false
},
key: { /*istanbul ignore next*/
validate: function validate(node, key, val) {
var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"];
/*istanbul ignore next*/_index2.assertNodeType.apply( /*istanbul ignore next*/undefined, expectedTypes)(node, key, val);
}
},
decorators: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Decorator")))
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("BlockStatement")
},
generator: {
default: false,
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean")
},
async: {
default: false,
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean")
}
},
visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"],
aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"]
});
/*istanbul ignore next*/(0, _index3.default)("ObjectProperty", {
builder: ["key", "value", "computed", "shorthand", "decorators"],
fields: {
computed: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean"),
default: false
},
key: { /*istanbul ignore next*/
validate: function validate(node, key, val) {
var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"];
/*istanbul ignore next*/_index2.assertNodeType.apply( /*istanbul ignore next*/undefined, expectedTypes)(node, key, val);
}
},
value: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
shorthand: {
validate: /*istanbul ignore next*/(0, _index2.assertValueType)("boolean"),
default: false
},
decorators: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Decorator"))),
optional: true
}
},
visitor: ["key", "value", "decorators"],
aliases: ["UserWhitespacable", "Property", "ObjectMember"]
});
/*istanbul ignore next*/(0, _index3.default)("RestElement", {
visitor: ["argument", "typeAnnotation"],
aliases: ["LVal"],
fields: {
argument: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("LVal")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("ReturnStatement", {
visitor: ["argument"],
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
fields: {
argument: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression"),
optional: true
}
}
});
/*istanbul ignore next*/(0, _index3.default)("SequenceExpression", {
visitor: ["expressions"],
fields: {
expressions: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")))
}
},
aliases: ["Expression"]
});
/*istanbul ignore next*/(0, _index3.default)("SwitchCase", {
visitor: ["test", "consequent"],
fields: {
test: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression"),
optional: true
},
consequent: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("Statement")))
}
}
});
/*istanbul ignore next*/(0, _index3.default)("SwitchStatement", {
visitor: ["discriminant", "cases"],
aliases: ["Statement", "BlockParent", "Scopable"],
fields: {
discriminant: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
cases: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("SwitchCase")))
}
}
});
/*istanbul ignore next*/(0, _index3.default)("ThisExpression", {
aliases: ["Expression"]
});
/*istanbul ignore next*/(0, _index3.default)("ThrowStatement", {
visitor: ["argument"],
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
fields: {
argument: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
}
}
});
// todo: at least handler or finalizer should be set to be valid
/*istanbul ignore next*/(0, _index3.default)("TryStatement", {
visitor: ["block", "handler", "finalizer"],
aliases: ["Statement"],
fields: {
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("BlockStatement")
},
handler: {
optional: true,
handler: /*istanbul ignore next*/(0, _index2.assertNodeType)("BlockStatement")
},
finalizer: {
optional: true,
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("BlockStatement")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("UnaryExpression", {
builder: ["operator", "argument", "prefix"],
fields: {
prefix: {
default: true
},
argument: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
operator: {
validate: /*istanbul ignore next*/_index2.assertOneOf.apply( /*istanbul ignore next*/undefined, /*istanbul ignore next*/_constants.UNARY_OPERATORS)
}
},
visitor: ["argument"],
aliases: ["UnaryLike", "Expression"]
});
/*istanbul ignore next*/(0, _index3.default)("UpdateExpression", {
builder: ["operator", "argument", "prefix"],
fields: {
prefix: {
default: false
},
argument: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
operator: {
validate: /*istanbul ignore next*/_index2.assertOneOf.apply( /*istanbul ignore next*/undefined, /*istanbul ignore next*/_constants.UPDATE_OPERATORS)
}
},
visitor: ["argument"],
aliases: ["Expression"]
});
/*istanbul ignore next*/(0, _index3.default)("VariableDeclaration", {
builder: ["kind", "declarations"],
visitor: ["declarations"],
aliases: ["Statement", "Declaration"],
fields: {
kind: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("string"), /*istanbul ignore next*/(0, _index2.assertOneOf)("var", "let", "const"))
},
declarations: {
validate: /*istanbul ignore next*/(0, _index2.chain)( /*istanbul ignore next*/(0, _index2.assertValueType)("array"), /*istanbul ignore next*/(0, _index2.assertEach)( /*istanbul ignore next*/(0, _index2.assertNodeType)("VariableDeclarator")))
}
}
});
/*istanbul ignore next*/(0, _index3.default)("VariableDeclarator", {
visitor: ["id", "init"],
fields: {
id: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("LVal")
},
init: {
optional: true,
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("WhileStatement", {
visitor: ["test", "body"],
aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"],
fields: {
test: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("BlockStatement", "Statement")
}
}
});
/*istanbul ignore next*/(0, _index3.default)("WithStatement", {
visitor: ["object", "body"],
aliases: ["Statement"],
fields: {
object: {
object: /*istanbul ignore next*/(0, _index2.assertNodeType)("Expression")
},
body: {
validate: /*istanbul ignore next*/(0, _index2.assertNodeType)("BlockStatement", "Statement")
}
}
});
|
/*!
Copyright (C) 2014-2015 by WebReflection
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function(window, document, Object, REGISTER_ELEMENT){'use strict';
var htmlClass = (function (info) {
// (C) Andrea Giammarchi - @WebReflection - MIT Style
var
catchClass = /^[A-Z]+[a-z]/,
filterBy = function (re) {
var arr = [], tag;
for (tag in register) {
if (re.test(tag)) arr.push(tag);
}
return arr;
},
add = function (Class, tag) {
tag = tag.toLowerCase();
if (!(tag in register)) {
register[Class] = (register[Class] || []).concat(tag);
register[tag] = (register[tag.toUpperCase()] = Class);
}
},
register = (Object.create || Object)(null),
htmlClass = {},
i, section, tags, Class
;
for (section in info) {
for (Class in info[section]) {
tags = info[section][Class];
register[Class] = tags;
for (i = 0; i < tags.length; i++) {
register[tags[i].toLowerCase()] =
register[tags[i].toUpperCase()] = Class;
}
}
}
htmlClass.get = function get(tagOrClass) {
return typeof tagOrClass === 'string' ?
(register[tagOrClass] || (catchClass.test(tagOrClass) ? [] : '')) :
filterBy(tagOrClass);
};
htmlClass.set = function set(tag, Class) {
return (catchClass.test(tag) ?
add(tag, Class) :
add(Class, tag)
), htmlClass;
};
return htmlClass;
}({
"collections": {
"HTMLAllCollection": [
"all"
],
"HTMLCollection": [
"forms"
],
"HTMLFormControlsCollection": [
"elements"
],
"HTMLOptionsCollection": [
"options"
]
},
"elements": {
"Element": [
"element"
],
"HTMLAnchorElement": [
"a"
],
"HTMLAppletElement": [
"applet"
],
"HTMLAreaElement": [
"area"
],
"HTMLAttachmentElement": [
"attachment"
],
"HTMLAudioElement": [
"audio"
],
"HTMLBRElement": [
"br"
],
"HTMLBaseElement": [
"base"
],
"HTMLBodyElement": [
"body"
],
"HTMLButtonElement": [
"button"
],
"HTMLCanvasElement": [
"canvas"
],
"HTMLContentElement": [
"content"
],
"HTMLDListElement": [
"dl"
],
"HTMLDataElement": [
"data"
],
"HTMLDataListElement": [
"datalist"
],
"HTMLDetailsElement": [
"details"
],
"HTMLDialogElement": [
"dialog"
],
"HTMLDirectoryElement": [
"dir"
],
"HTMLDivElement": [
"div"
],
"HTMLDocument": [
"document"
],
"HTMLElement": [
"element",
"abbr",
"address",
"article",
"aside",
"b",
"bdi",
"bdo",
"cite",
"code",
"command",
"dd",
"dfn",
"dt",
"em",
"figcaption",
"figure",
"footer",
"header",
"i",
"kbd",
"mark",
"nav",
"noscript",
"rp",
"rt",
"ruby",
"s",
"samp",
"section",
"small",
"strong",
"sub",
"summary",
"sup",
"u",
"var",
"wbr"
],
"HTMLEmbedElement": [
"embed"
],
"HTMLFieldSetElement": [
"fieldset"
],
"HTMLFontElement": [
"font"
],
"HTMLFormElement": [
"form"
],
"HTMLFrameElement": [
"frame"
],
"HTMLFrameSetElement": [
"frameset"
],
"HTMLHRElement": [
"hr"
],
"HTMLHeadElement": [
"head"
],
"HTMLHeadingElement": [
"h1",
"h2",
"h3",
"h4",
"h5",
"h6"
],
"HTMLHtmlElement": [
"html"
],
"HTMLIFrameElement": [
"iframe"
],
"HTMLImageElement": [
"img"
],
"HTMLInputElement": [
"input"
],
"HTMLKeygenElement": [
"keygen"
],
"HTMLLIElement": [
"li"
],
"HTMLLabelElement": [
"label"
],
"HTMLLegendElement": [
"legend"
],
"HTMLLinkElement": [
"link"
],
"HTMLMapElement": [
"map"
],
"HTMLMarqueeElement": [
"marquee"
],
"HTMLMediaElement": [
"media"
],
"HTMLMenuElement": [
"menu"
],
"HTMLMenuItemElement": [
"menuitem"
],
"HTMLMetaElement": [
"meta"
],
"HTMLMeterElement": [
"meter"
],
"HTMLModElement": [
"del",
"ins"
],
"HTMLOListElement": [
"ol"
],
"HTMLObjectElement": [
"object"
],
"HTMLOptGroupElement": [
"optgroup"
],
"HTMLOptionElement": [
"option"
],
"HTMLOutputElement": [
"output"
],
"HTMLParagraphElement": [
"p"
],
"HTMLParamElement": [
"param"
],
"HTMLPictureElement": [
"picture"
],
"HTMLPreElement": [
"pre"
],
"HTMLProgressElement": [
"progress"
],
"HTMLQuoteElement": [
"blockquote",
"q",
"quote"
],
"HTMLScriptElement": [
"script"
],
"HTMLSelectElement": [
"select"
],
"HTMLShadowElement": [
"shadow"
],
"HTMLSlotElement": [
"slot"
],
"HTMLSourceElement": [
"source"
],
"HTMLSpanElement": [
"span"
],
"HTMLStyleElement": [
"style"
],
"HTMLTableCaptionElement": [
"caption"
],
"HTMLTableCellElement": [
"td",
"th"
],
"HTMLTableColElement": [
"col",
"colgroup"
],
"HTMLTableElement": [
"table"
],
"HTMLTableRowElement": [
"tr"
],
"HTMLTableSectionElement": [
"thead",
"tbody",
"tfoot"
],
"HTMLTemplateElement": [
"template"
],
"HTMLTextAreaElement": [
"textarea"
],
"HTMLTimeElement": [
"time"
],
"HTMLTitleElement": [
"title"
],
"HTMLTrackElement": [
"track"
],
"HTMLUListElement": [
"ul"
],
"HTMLUnknownElement": [
"unknown",
"vhgroupv",
"vkeygen"
],
"HTMLVideoElement": [
"video"
]
},
"nodes": {
"Attr": [
"node"
],
"Audio": [
"audio"
],
"CDATASection": [
"node"
],
"CharacterData": [
"node"
],
"Comment": [
"#comment"
],
"Document": [
"#document"
],
"DocumentFragment": [
"#document-fragment"
],
"DocumentType": [
"node"
],
"HTMLDocument": [
"#document"
],
"Image": [
"img"
],
"Option": [
"option"
],
"ProcessingInstruction": [
"node"
],
"ShadowRoot": [
"#shadow-root"
],
"Text": [
"#text"
],
"XMLDocument": [
"xml"
]
}
}));
// DO NOT USE THIS FILE DIRECTLY, IT WON'T WORK
// THIS IS A PROJECT BASED ON A BUILD SYSTEM
// THIS FILE IS JUST WRAPPED UP RESULTING IN
// build/document-register-element.js
// and its .max.js counter part
var
// IE < 11 only + old WebKit for attributes + feature detection
EXPANDO_UID = '__' + REGISTER_ELEMENT + (Math.random() * 10e4 >> 0),
// shortcuts and costants
ATTACHED = 'attached',
DETACHED = 'detached',
EXTENDS = 'extends',
ADDITION = 'ADDITION',
MODIFICATION = 'MODIFICATION',
REMOVAL = 'REMOVAL',
DOM_ATTR_MODIFIED = 'DOMAttrModified',
DOM_CONTENT_LOADED = 'DOMContentLoaded',
DOM_SUBTREE_MODIFIED = 'DOMSubtreeModified',
PREFIX_TAG = '<',
PREFIX_IS = '=',
// valid and invalid node names
validName = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/,
invalidNames = [
'ANNOTATION-XML',
'COLOR-PROFILE',
'FONT-FACE',
'FONT-FACE-SRC',
'FONT-FACE-URI',
'FONT-FACE-FORMAT',
'FONT-FACE-NAME',
'MISSING-GLYPH'
],
// registered types and their prototypes
types = [],
protos = [],
// to query subnodes
query = '',
// html shortcut used to feature detect
documentElement = document.documentElement,
// ES5 inline helpers || basic patches
indexOf = types.indexOf || function (v) {
for(var i = this.length; i-- && this[i] !== v;){}
return i;
},
// other helpers / shortcuts
OP = Object.prototype,
hOP = OP.hasOwnProperty,
iPO = OP.isPrototypeOf,
defineProperty = Object.defineProperty,
gOPD = Object.getOwnPropertyDescriptor,
gOPN = Object.getOwnPropertyNames,
gPO = Object.getPrototypeOf,
sPO = Object.setPrototypeOf,
// jshint proto: true
hasProto = !!Object.__proto__,
// V1 helpers
DRECEV1 = '__dreCEv1',
customElements = window.customElements,
usableCustomElements = !!(
customElements &&
customElements.define &&
customElements.get &&
customElements.whenDefined
),
Dict = Object.create || Object,
Map = window.Map || function Map() {
var K = [], V = [], i;
return {
get: function (k) {
return V[indexOf.call(K, k)];
},
set: function (k, v) {
i = indexOf.call(K, k);
if (i < 0) V[K.push(k) - 1] = v;
else V[i] = v;
}
};
},
Promise = window.Promise || function (fn) {
var
notify = [],
done = false,
p = {
'catch': function () {
return p;
},
'then': function (cb) {
notify.push(cb);
if (done) setTimeout(resolve, 1);
return p;
}
}
;
function resolve(value) {
done = true;
while (notify.length) notify.shift()(value);
}
fn(resolve);
return p;
},
justCreated = false,
constructors = Dict(null),
waitingList = Dict(null),
nodeNames = new Map(),
// used to create unique instances
create = Object.create || function Bridge(proto) {
// silly broken polyfill probably ever used but short enough to work
return proto ? ((Bridge.prototype = proto), new Bridge()) : this;
},
// will set the prototype if possible
// or copy over all properties
setPrototype = sPO || (
hasProto ?
function (o, p) {
o.__proto__ = p;
return o;
} : (
(gOPN && gOPD) ?
(function(){
function setProperties(o, p) {
for (var
key,
names = gOPN(p),
i = 0, length = names.length;
i < length; i++
) {
key = names[i];
if (!hOP.call(o, key)) {
defineProperty(o, key, gOPD(p, key));
}
}
}
return function (o, p) {
do {
setProperties(o, p);
} while ((p = gPO(p)) && !iPO.call(p, o));
return o;
};
}()) :
function (o, p) {
for (var key in p) {
o[key] = p[key];
}
return o;
}
)),
// DOM shortcuts and helpers, if any
MutationObserver = window.MutationObserver ||
window.WebKitMutationObserver,
HTMLElementPrototype = (
window.HTMLElement ||
window.Element ||
window.Node
).prototype,
IE8 = !iPO.call(HTMLElementPrototype, documentElement),
safeProperty = IE8 ? function (o, k, d) {
o[k] = d.value;
return o;
} : defineProperty,
isValidNode = IE8 ?
function (node) {
return node.nodeType === 1;
} :
function (node) {
return iPO.call(HTMLElementPrototype, node);
},
targets = IE8 && [],
cloneNode = HTMLElementPrototype.cloneNode,
dispatchEvent = HTMLElementPrototype.dispatchEvent,
getAttribute = HTMLElementPrototype.getAttribute,
hasAttribute = HTMLElementPrototype.hasAttribute,
removeAttribute = HTMLElementPrototype.removeAttribute,
setAttribute = HTMLElementPrototype.setAttribute,
// replaced later on
createElement = document.createElement,
patchedCreateElement = createElement,
// shared observer for all attributes
attributesObserver = MutationObserver && {
attributes: true,
characterData: true,
attributeOldValue: true
},
// useful to detect only if there's no MutationObserver
DOMAttrModified = MutationObserver || function(e) {
doesNotSupportDOMAttrModified = false;
documentElement.removeEventListener(
DOM_ATTR_MODIFIED,
DOMAttrModified
);
},
// will both be used to make DOMNodeInserted asynchronous
asapQueue,
asapTimer = 0,
// internal flags
setListener = false,
doesNotSupportDOMAttrModified = true,
dropDomContentLoaded = true,
// needed for the innerHTML helper
notFromInnerHTMLHelper = true,
// optionally defined later on
onSubtreeModified,
callDOMAttrModified,
getAttributesMirror,
observer,
// based on setting prototype capability
// will check proto or the expando attribute
// in order to setup the node once
patchIfNotAlready,
patch
;
// only if needed
if (!(REGISTER_ELEMENT in document)) {
if (sPO || hasProto) {
patchIfNotAlready = function (node, proto) {
if (!iPO.call(proto, node)) {
setupNode(node, proto);
}
};
patch = setupNode;
} else {
patchIfNotAlready = function (node, proto) {
if (!node[EXPANDO_UID]) {
node[EXPANDO_UID] = Object(true);
setupNode(node, proto);
}
};
patch = patchIfNotAlready;
}
if (IE8) {
doesNotSupportDOMAttrModified = false;
(function (){
var
descriptor = gOPD(HTMLElementPrototype, 'addEventListener'),
addEventListener = descriptor.value,
patchedRemoveAttribute = function (name) {
var e = new CustomEvent(DOM_ATTR_MODIFIED, {bubbles: true});
e.attrName = name;
e.prevValue = getAttribute.call(this, name);
e.newValue = null;
e[REMOVAL] = e.attrChange = 2;
removeAttribute.call(this, name);
dispatchEvent.call(this, e);
},
patchedSetAttribute = function (name, value) {
var
had = hasAttribute.call(this, name),
old = had && getAttribute.call(this, name),
e = new CustomEvent(DOM_ATTR_MODIFIED, {bubbles: true})
;
setAttribute.call(this, name, value);
e.attrName = name;
e.prevValue = had ? old : null;
e.newValue = value;
if (had) {
e[MODIFICATION] = e.attrChange = 1;
} else {
e[ADDITION] = e.attrChange = 0;
}
dispatchEvent.call(this, e);
},
onPropertyChange = function (e) {
// jshint eqnull:true
var
node = e.currentTarget,
superSecret = node[EXPANDO_UID],
propertyName = e.propertyName,
event
;
if (superSecret.hasOwnProperty(propertyName)) {
superSecret = superSecret[propertyName];
event = new CustomEvent(DOM_ATTR_MODIFIED, {bubbles: true});
event.attrName = superSecret.name;
event.prevValue = superSecret.value || null;
event.newValue = (superSecret.value = node[propertyName] || null);
if (event.prevValue == null) {
event[ADDITION] = event.attrChange = 0;
} else {
event[MODIFICATION] = event.attrChange = 1;
}
dispatchEvent.call(node, event);
}
}
;
descriptor.value = function (type, handler, capture) {
if (
type === DOM_ATTR_MODIFIED &&
this.attributeChangedCallback &&
this.setAttribute !== patchedSetAttribute
) {
this[EXPANDO_UID] = {
className: {
name: 'class',
value: this.className
}
};
this.setAttribute = patchedSetAttribute;
this.removeAttribute = patchedRemoveAttribute;
addEventListener.call(this, 'propertychange', onPropertyChange);
}
addEventListener.call(this, type, handler, capture);
};
defineProperty(HTMLElementPrototype, 'addEventListener', descriptor);
}());
} else if (!MutationObserver) {
documentElement.addEventListener(DOM_ATTR_MODIFIED, DOMAttrModified);
documentElement.setAttribute(EXPANDO_UID, 1);
documentElement.removeAttribute(EXPANDO_UID);
if (doesNotSupportDOMAttrModified) {
onSubtreeModified = function (e) {
var
node = this,
oldAttributes,
newAttributes,
key
;
if (node === e.target) {
oldAttributes = node[EXPANDO_UID];
node[EXPANDO_UID] = (newAttributes = getAttributesMirror(node));
for (key in newAttributes) {
if (!(key in oldAttributes)) {
// attribute was added
return callDOMAttrModified(
0,
node,
key,
oldAttributes[key],
newAttributes[key],
ADDITION
);
} else if (newAttributes[key] !== oldAttributes[key]) {
// attribute was changed
return callDOMAttrModified(
1,
node,
key,
oldAttributes[key],
newAttributes[key],
MODIFICATION
);
}
}
// checking if it has been removed
for (key in oldAttributes) {
if (!(key in newAttributes)) {
// attribute removed
return callDOMAttrModified(
2,
node,
key,
oldAttributes[key],
newAttributes[key],
REMOVAL
);
}
}
}
};
callDOMAttrModified = function (
attrChange,
currentTarget,
attrName,
prevValue,
newValue,
action
) {
var e = {
attrChange: attrChange,
currentTarget: currentTarget,
attrName: attrName,
prevValue: prevValue,
newValue: newValue
};
e[action] = attrChange;
onDOMAttrModified(e);
};
getAttributesMirror = function (node) {
for (var
attr, name,
result = {},
attributes = node.attributes,
i = 0, length = attributes.length;
i < length; i++
) {
attr = attributes[i];
name = attr.name;
if (name !== 'setAttribute') {
result[name] = attr.value;
}
}
return result;
};
}
}
// set as enumerable, writable and configurable
document[REGISTER_ELEMENT] = function registerElement(type, options) {
upperType = type.toUpperCase();
if (!setListener) {
// only first time document.registerElement is used
// we need to set this listener
// setting it by default might slow down for no reason
setListener = true;
if (MutationObserver) {
observer = (function(attached, detached){
function checkEmAll(list, callback) {
for (var i = 0, length = list.length; i < length; callback(list[i++])){}
}
return new MutationObserver(function (records) {
for (var
current, node, newValue,
i = 0, length = records.length; i < length; i++
) {
current = records[i];
if (current.type === 'childList') {
checkEmAll(current.addedNodes, attached);
checkEmAll(current.removedNodes, detached);
} else {
node = current.target;
if (notFromInnerHTMLHelper &&
node.attributeChangedCallback &&
current.attributeName !== 'style') {
newValue = getAttribute.call(node, current.attributeName);
if (newValue !== current.oldValue) {
node.attributeChangedCallback(
current.attributeName,
current.oldValue,
newValue
);
}
}
}
}
});
}(executeAction(ATTACHED), executeAction(DETACHED)));
observer.observe(
document,
{
childList: true,
subtree: true
}
);
} else {
asapQueue = [];
document.addEventListener('DOMNodeInserted', onDOMNode(ATTACHED));
document.addEventListener('DOMNodeRemoved', onDOMNode(DETACHED));
}
document.addEventListener(DOM_CONTENT_LOADED, onReadyStateChange);
document.addEventListener('readystatechange', onReadyStateChange);
HTMLElementPrototype.cloneNode = function (deep) {
var
node = cloneNode.call(this, !!deep),
i = getTypeIndex(node)
;
if (-1 < i) patch(node, protos[i]);
if (deep) loopAndSetup(node.querySelectorAll(query));
return node;
};
}
if (-2 < (
indexOf.call(types, PREFIX_IS + upperType) +
indexOf.call(types, PREFIX_TAG + upperType)
)) {
throwTypeError(type);
}
if (!validName.test(upperType) || -1 < indexOf.call(invalidNames, upperType)) {
throw new Error('The type ' + type + ' is invalid');
}
var
constructor = function () {
return extending ?
document.createElement(nodeName, upperType) :
document.createElement(nodeName);
},
opt = options || OP,
extending = hOP.call(opt, EXTENDS),
nodeName = extending ? options[EXTENDS].toUpperCase() : upperType,
upperType,
i
;
if (extending && -1 < (
indexOf.call(types, PREFIX_TAG + nodeName)
)) {
throwTypeError(nodeName);
}
i = types.push((extending ? PREFIX_IS : PREFIX_TAG) + upperType) - 1;
query = query.concat(
query.length ? ',' : '',
extending ? nodeName + '[is="' + type.toLowerCase() + '"]' : nodeName
);
constructor.prototype = (
protos[i] = hOP.call(opt, 'prototype') ?
opt.prototype :
create(HTMLElementPrototype)
);
loopAndVerify(
document.querySelectorAll(query),
ATTACHED
);
return constructor;
};
document.createElement = (patchedCreateElement = function (localName, typeExtension) {
var
is = typeof typeExtension === 'string' ? typeExtension : '',
node = is ?
createElement.call(document, localName, is) :
createElement.call(document, localName),
name = '' + localName,
i = indexOf.call(
types,
(is ? PREFIX_IS : PREFIX_TAG) +
(is || name).toUpperCase()
),
setup = -1 < i
;
if (is) {
node.setAttribute('is', is = is.toLowerCase());
if (setup) {
setup = isInQSA(name.toUpperCase(), is);
}
}
notFromInnerHTMLHelper = !document.createElement.innerHTMLHelper;
if (setup) patch(node, protos[i]);
return node;
});
}
function ASAP() {
var queue = asapQueue.splice(0, asapQueue.length);
asapTimer = 0;
while (queue.length) {
queue.shift().call(
null, queue.shift()
);
}
}
function loopAndVerify(list, action) {
for (var i = 0, length = list.length; i < length; i++) {
verifyAndSetupAndAction(list[i], action);
}
}
function loopAndSetup(list) {
for (var i = 0, length = list.length, node; i < length; i++) {
node = list[i];
patch(node, protos[getTypeIndex(node)]);
}
}
function executeAction(action) {
return function (node) {
if (isValidNode(node)) {
verifyAndSetupAndAction(node, action);
loopAndVerify(
node.querySelectorAll(query),
action
);
}
};
}
function getTypeIndex(target) {
var
is = getAttribute.call(target, 'is'),
nodeName = target.nodeName.toUpperCase(),
i = indexOf.call(
types,
is ?
PREFIX_IS + is.toUpperCase() :
PREFIX_TAG + nodeName
)
;
return is && -1 < i && !isInQSA(nodeName, is) ? -1 : i;
}
function isInQSA(name, type) {
return -1 < query.indexOf(name + '[is="' + type + '"]');
}
function onDOMAttrModified(e) {
var
node = e.currentTarget,
attrChange = e.attrChange,
attrName = e.attrName,
target = e.target
;
if (notFromInnerHTMLHelper &&
(!target || target === node) &&
node.attributeChangedCallback &&
attrName !== 'style' &&
e.prevValue !== e.newValue) {
node.attributeChangedCallback(
attrName,
attrChange === e[ADDITION] ? null : e.prevValue,
attrChange === e[REMOVAL] ? null : e.newValue
);
}
}
function onDOMNode(action) {
var executor = executeAction(action);
return function (e) {
asapQueue.push(executor, e.target);
if (asapTimer) clearTimeout(asapTimer);
asapTimer = setTimeout(ASAP, 1);
};
}
function onReadyStateChange(e) {
if (dropDomContentLoaded) {
dropDomContentLoaded = false;
e.currentTarget.removeEventListener(DOM_CONTENT_LOADED, onReadyStateChange);
}
loopAndVerify(
(e.target || document).querySelectorAll(query),
e.detail === DETACHED ? DETACHED : ATTACHED
);
if (IE8) purge();
}
function patchedSetAttribute(name, value) {
// jshint validthis:true
var self = this;
setAttribute.call(self, name, value);
onSubtreeModified.call(self, {target: self});
}
function setupNode(node, proto) {
setPrototype(node, proto);
if (observer) {
observer.observe(node, attributesObserver);
} else {
if (doesNotSupportDOMAttrModified) {
node.setAttribute = patchedSetAttribute;
node[EXPANDO_UID] = getAttributesMirror(node);
node.addEventListener(DOM_SUBTREE_MODIFIED, onSubtreeModified);
}
node.addEventListener(DOM_ATTR_MODIFIED, onDOMAttrModified);
}
if (node.createdCallback && notFromInnerHTMLHelper) {
node.created = true;
node.createdCallback();
node.created = false;
}
}
function purge() {
for (var
node,
i = 0,
length = targets.length;
i < length; i++
) {
node = targets[i];
if (!documentElement.contains(node)) {
length--;
targets.splice(i--, 1);
verifyAndSetupAndAction(node, DETACHED);
}
}
}
function throwTypeError(type) {
throw new Error('A ' + type + ' type is already registered');
}
function verifyAndSetupAndAction(node, action) {
var
fn,
i = getTypeIndex(node)
;
if (-1 < i) {
patchIfNotAlready(node, protos[i]);
i = 0;
if (action === ATTACHED && !node[ATTACHED]) {
node[DETACHED] = false;
node[ATTACHED] = true;
i = 1;
if (IE8 && indexOf.call(targets, node) < 0) {
targets.push(node);
}
} else if (action === DETACHED && !node[DETACHED]) {
node[ATTACHED] = false;
node[DETACHED] = true;
i = 1;
}
if (i && (fn = node[action + 'Callback'])) fn.call(node);
}
}
// V1 in da House!
function CustomElementRegistry() {}
CustomElementRegistry.prototype = {
constructor: CustomElementRegistry,
// a workaround for the stubborn WebKit
define: usableCustomElements ?
function (name, Class, options) {
if (options) {
define(name, Class, options);
} else {
customElements.define(name, Class);
name = name.toUpperCase();
constructors[name] = {
constructor: Class,
create: [name]
};
nodeNames.set(Class, name);
}
} :
define,
get: usableCustomElements ?
function (name) {
return customElements.get(name) || get(name);
} :
get,
whenDefined: usableCustomElements ?
function (name) {
return Promise.race([
customElements.whenDefined(name),
whenDefined(name)
]);
} :
whenDefined
};
function define(name, Class, options) {
var
is = options && options[EXTENDS] || '',
CProto = Class.prototype,
proto = create(CProto),
attributes = Class.observedAttributes || Array.prototype,
definition = {prototype: proto}
;
// TODO: is this needed at all since it's inherited?
// defineProperty(proto, 'constructor', {value: Class});
safeProperty(proto, 'createdCallback', {
value: function () {
if (justCreated) justCreated = false;
else if (!this[DRECEV1]) {
this[DRECEV1] = true;
new Class(this);
}
}
});
safeProperty(proto, 'attributeChangedCallback', {
value: function (name) {
if (-1 < indexOf.call(attributes, name))
CProto.attributeChangedCallback.apply(this, arguments);
}
});
if (CProto.connectedCallback) {
safeProperty(proto, 'attachedCallback', {
value: CProto.connectedCallback
});
}
if (CProto.disconnectedCallback) {
safeProperty(proto, 'detachedCallback', {
value: CProto.disconnectedCallback
});
}
if (is) definition[EXTENDS] = is;
document[REGISTER_ELEMENT](name, definition);
name = name.toUpperCase();
constructors[name] = {
constructor: Class,
create: is ? [is, name] : [name]
};
nodeNames.set(Class, name);
whenDefined(name);
waitingList[name].r();
}
function get(name) {
var info = constructors[name.toUpperCase()];
return info && info.constructor;
}
function whenDefined(name) {
name = name.toUpperCase();
if (!(name in waitingList)) {
waitingList[name] = {};
waitingList[name].p = new Promise(function (resolve) {
waitingList[name].r = resolve;
});
}
return waitingList[name].p;
}
function polyfillV1() {
if (customElements) delete window.customElements;
defineProperty(window, 'customElements', {
configurable: true,
value: new CustomElementRegistry()
});
defineProperty(window, 'CustomElementRegistry', {
configurable: true,
value: CustomElementRegistry
});
for (var
patchClass = function (name) {
var Class = window[name];
if (Class) {
window[name] = function CustomElementsV1(self) {
var info;
if (!self) self = this;
if (!self[DRECEV1]) {
justCreated = true;
info = constructors[nodeNames.get(self.constructor)];
self = usableCustomElements && info.create.length === 1 ?
Reflect.construct(Class, [], info.constructor) :
document.createElement.apply(document, info.create);
self[DRECEV1] = true;
justCreated = false;
}
return self;
};
(window[name].prototype = Class.prototype).constructor = window[name];
}
},
Classes = htmlClass.get(/^HTML/),
i = Classes.length;
i--;
patchClass(Classes[i])
) {}
(document.createElement = function (name, options) {
var is = typeof options === 'string' ?
options : (options && options.is || '');
return is ?
patchedCreateElement.call(this, name, is) :
patchedCreateElement.call(this, name);
});
}
if (!customElements) polyfillV1();
try {
(function (DRE, options, name) {
options[EXTENDS] = 'a';
DRE.prototype = HTMLAnchorElement.prototype;
customElements.define(name, DRE, options);
if (document.createElement(name).getAttribute('is') !== name) {
throw options;
}
}(
function DRE() {
return Reflect.construct(HTMLAnchorElement, [], DRE);
},
{},
'document-register-element-a'
));
} catch(o_O) {
polyfillV1();
}
}(window, document, Object, 'registerElement'));
|
/*! JointJS v1.0.2 (2016-10-27) - JavaScript diagramming library
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
joint.shapes.uml = {};
joint.shapes.uml.Class = joint.shapes.basic.Generic.extend({
markup: [
'<g class="rotatable">',
'<g class="scalable">',
'<rect class="uml-class-name-rect"/><rect class="uml-class-attrs-rect"/><rect class="uml-class-methods-rect"/>',
'</g>',
'<text class="uml-class-name-text"/><text class="uml-class-attrs-text"/><text class="uml-class-methods-text"/>',
'</g>'
].join(''),
defaults: _.defaultsDeep({
type: 'uml.Class',
attrs: {
rect: { 'width': 200 },
'.uml-class-name-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#3498db' },
'.uml-class-attrs-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#2980b9' },
'.uml-class-methods-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#2980b9' },
'.uml-class-name-text': {
'ref': '.uml-class-name-rect', 'ref-y': .5, 'ref-x': .5, 'text-anchor': 'middle', 'y-alignment': 'middle', 'font-weight': 'bold',
'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman'
},
'.uml-class-attrs-text': {
'ref': '.uml-class-attrs-rect', 'ref-y': 5, 'ref-x': 5,
'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman'
},
'.uml-class-methods-text': {
'ref': '.uml-class-methods-rect', 'ref-y': 5, 'ref-x': 5,
'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman'
}
},
name: [],
attributes: [],
methods: []
}, joint.shapes.basic.Generic.prototype.defaults),
initialize: function() {
this.on('change:name change:attributes change:methods', function() {
this.updateRectangles();
this.trigger('uml-update');
}, this);
this.updateRectangles();
joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments);
},
getClassName: function() {
return this.get('name');
},
updateRectangles: function() {
var attrs = this.get('attrs');
var rects = [
{ type: 'name', text: this.getClassName() },
{ type: 'attrs', text: this.get('attributes') },
{ type: 'methods', text: this.get('methods') }
];
var offsetY = 0;
_.each(rects, function(rect) {
var lines = _.isArray(rect.text) ? rect.text : [rect.text];
var rectHeight = lines.length * 20 + 20;
attrs['.uml-class-' + rect.type + '-text'].text = lines.join('\n');
attrs['.uml-class-' + rect.type + '-rect'].height = rectHeight;
attrs['.uml-class-' + rect.type + '-rect'].transform = 'translate(0,' + offsetY + ')';
offsetY += rectHeight;
});
}
});
joint.shapes.uml.ClassView = joint.dia.ElementView.extend({
initialize: function() {
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
this.listenTo(this.model, 'uml-update', function() {
this.update();
this.resize();
});
}
});
joint.shapes.uml.Abstract = joint.shapes.uml.Class.extend({
defaults: _.defaultsDeep({
type: 'uml.Abstract',
attrs: {
'.uml-class-name-rect': { fill : '#e74c3c' },
'.uml-class-attrs-rect': { fill : '#c0392b' },
'.uml-class-methods-rect': { fill : '#c0392b' }
}
}, joint.shapes.uml.Class.prototype.defaults),
getClassName: function() {
return ['<<Abstract>>', this.get('name')];
}
});
joint.shapes.uml.AbstractView = joint.shapes.uml.ClassView;
joint.shapes.uml.Interface = joint.shapes.uml.Class.extend({
defaults: _.defaultsDeep({
type: 'uml.Interface',
attrs: {
'.uml-class-name-rect': { fill : '#f1c40f' },
'.uml-class-attrs-rect': { fill : '#f39c12' },
'.uml-class-methods-rect': { fill : '#f39c12' }
}
}, joint.shapes.uml.Class.prototype.defaults),
getClassName: function() {
return ['<<Interface>>', this.get('name')];
}
});
joint.shapes.uml.InterfaceView = joint.shapes.uml.ClassView;
joint.shapes.uml.Generalization = joint.dia.Link.extend({
defaults: {
type: 'uml.Generalization',
attrs: { '.marker-target': { d: 'M 20 0 L 0 10 L 20 20 z', fill: 'white' }}
}
});
joint.shapes.uml.Implementation = joint.dia.Link.extend({
defaults: {
type: 'uml.Implementation',
attrs: {
'.marker-target': { d: 'M 20 0 L 0 10 L 20 20 z', fill: 'white' },
'.connection': { 'stroke-dasharray': '3,3' }
}
}
});
joint.shapes.uml.Aggregation = joint.dia.Link.extend({
defaults: {
type: 'uml.Aggregation',
attrs: { '.marker-target': { d: 'M 40 10 L 20 20 L 0 10 L 20 0 z', fill: 'white' }}
}
});
joint.shapes.uml.Composition = joint.dia.Link.extend({
defaults: {
type: 'uml.Composition',
attrs: { '.marker-target': { d: 'M 40 10 L 20 20 L 0 10 L 20 0 z', fill: 'black' }}
}
});
joint.shapes.uml.Association = joint.dia.Link.extend({
defaults: { type: 'uml.Association' }
});
// Statechart
joint.shapes.uml.State = joint.shapes.basic.Generic.extend({
markup: [
'<g class="rotatable">',
'<g class="scalable">',
'<rect class="uml-state-body"/>',
'</g>',
'<path class="uml-state-separator"/>',
'<text class="uml-state-name"/>',
'<text class="uml-state-events"/>',
'</g>'
].join(''),
defaults: _.defaultsDeep({
type: 'uml.State',
attrs: {
'.uml-state-body': {
'width': 200, 'height': 200, 'rx': 10, 'ry': 10,
'fill': '#ecf0f1', 'stroke': '#bdc3c7', 'stroke-width': 3
},
'.uml-state-separator': {
'stroke': '#bdc3c7', 'stroke-width': 2
},
'.uml-state-name': {
'ref': '.uml-state-body', 'ref-x': .5, 'ref-y': 5, 'text-anchor': 'middle',
'fill': '#000000', 'font-family': 'Courier New', 'font-size': 14
},
'.uml-state-events': {
'ref': '.uml-state-separator', 'ref-x': 5, 'ref-y': 5,
'fill': '#000000', 'font-family': 'Courier New', 'font-size': 14
}
},
name: 'State',
events: []
}, joint.shapes.basic.Generic.prototype.defaults),
initialize: function() {
this.on({
'change:name': this.updateName,
'change:events': this.updateEvents,
'change:size': this.updatePath
}, this);
this.updateName();
this.updateEvents();
this.updatePath();
joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments);
},
updateName: function() {
this.attr('.uml-state-name/text', this.get('name'));
},
updateEvents: function() {
this.attr('.uml-state-events/text', this.get('events').join('\n'));
},
updatePath: function() {
var d = 'M 0 20 L ' + this.get('size').width + ' 20';
// We are using `silent: true` here because updatePath() is meant to be called
// on resize and there's no need to to update the element twice (`change:size`
// triggers also an update).
this.attr('.uml-state-separator/d', d, { silent: true });
}
});
joint.shapes.uml.StartState = joint.shapes.basic.Circle.extend({
defaults: _.defaultsDeep({
type: 'uml.StartState',
attrs: { circle: { 'fill': '#34495e', 'stroke': '#2c3e50', 'stroke-width': 2, 'rx': 1 }}
}, joint.shapes.basic.Circle.prototype.defaults)
});
joint.shapes.uml.EndState = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',
defaults: _.defaultsDeep({
type: 'uml.EndState',
size: { width: 20, height: 20 },
attrs: {
'circle.outer': {
transform: 'translate(10, 10)',
r: 10,
fill: '#ffffff',
stroke: '#2c3e50'
},
'circle.inner': {
transform: 'translate(10, 10)',
r: 6,
fill: '#34495e'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.uml.Transition = joint.dia.Link.extend({
defaults: {
type: 'uml.Transition',
attrs: {
'.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z', fill: '#34495e', stroke: '#2c3e50' },
'.connection': { stroke: '#2c3e50' }
}
}
});
|
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information.
/* global intellisense, window, document, setTimeout, WinJS */
(function () {
"use strict";
var redirect = intellisense.redirectDefinition;
function makeAllEnumerable(v) {
/// <param name="v" type="Object" />
if (v && typeof v === "object") {
Object.getOwnPropertyNames(v).forEach(function (name) {
var pd = Object.getOwnPropertyDescriptor(v, name);
if (!pd.enumerable && pd.configurable) {
pd.enumerable = true;
Object.defineProperty(v, name, pd);
}
});
}
return v;
}
function wrap(old) {
/// <param name="old" type="Function" />
var wrapper = function () {
var args = [];
for (var i = 0, len = arguments.length; i < len; i++) {
args.push(makeAllEnumerable(arguments[i]));
}
return old.apply(this, args);
};
redirect(wrapper, old);
return wrapper;
}
function wrapAllMethods(v) {
/// <param name="v" type="Object" />
if (v) {
Object.getOwnPropertyNames(v).forEach(function (name) {
var value = v[name];
if (typeof value === "function") {
v[name] = wrap(value);
}
});
}
return v;
}
if (this.WinJS) {
wrapAllMethods(WinJS.Namespace);
wrapAllMethods(WinJS.Class);
}
(function () {
var originalApplicationStart = WinJS.Application.start;
WinJS.Application.start = function () {
// Call app.stop() when execution completes to ensure that the subsequent calls to app.start() do not see the app as running.
var app = this;
setTimeout(function () {
app.stop();
}, 0);
return originalApplicationStart.apply(this, arguments);
};
redirect(WinJS.Application.start, originalApplicationStart);
var originalPagesDefine = WinJS.UI.Pages.define;
WinJS.UI.Pages.define = function (uri, members) {
var result = originalPagesDefine.apply(this, arguments);
intellisense.callerDefines(result, members);
if (typeof uri === 'string') {
intellisense.declareNavigationContainer(result, "Page (" + uri + ")");
}
// Set the call contexts for IPageControlMembers
if (members) {
var pageInstance = new result();
if (typeof members.error === 'function') {
intellisense.setCallContext(members.error, { thisArg: pageInstance, args: [new Error()] });
}
if (typeof members.init === 'function') {
intellisense.setCallContext(members.init, { thisArg: pageInstance, args: [document.createElement('element'), {}] });
}
if (typeof members.load === 'function') {
intellisense.setCallContext(members.load, { thisArg: pageInstance, args: [""] });
}
if (typeof members.processed === 'function') {
intellisense.setCallContext(members.processed, { thisArg: pageInstance, args: [document.createElement('element'), {}] });
}
if (typeof members.ready === 'function') {
intellisense.setCallContext(members.ready, { thisArg: pageInstance, args: [document.createElement('element'), {}] });
}
if (typeof members.render === 'function') {
intellisense.setCallContext(members.render, { thisArg: pageInstance, args: [document.createElement('element'), {}, WinJS.Promise.wrap()] });
}
}
return result;
};
redirect(WinJS.UI.Pages.define, originalPagesDefine);
// Simulate a call to a class' instance/static methods for WinJS.Class.define
var originalClassDefine = WinJS.Class.define;
WinJS.Class.define = function (constructor, instanceMembers, staticMembers) {
var result = originalClassDefine.call(this, constructor, instanceMembers, staticMembers);
// Go through the instance members to find methods
if (instanceMembers) {
var classInstance;
Object.getOwnPropertyNames(instanceMembers).forEach(function (name) {
var member = instanceMembers[name];
if (typeof member === 'function') {
intellisense.setCallContext(member, {
get thisArg() {
if (!classInstance) {
classInstance = new result();
}
return classInstance;
}
});
}
});
}
// Go through the static members to find methods
if (staticMembers) {
Object.getOwnPropertyNames(staticMembers).forEach(function (name) {
var member = staticMembers[name];
if (typeof member === 'function') {
intellisense.setCallContext(member, { thisArg: result });
}
});
}
return result;
};
redirect(WinJS.Class.define, originalClassDefine);
// Define the caller location property for WinJS.Namespace.define
var originalNamespaceDefine = WinJS.Namespace.define;
WinJS.Namespace.define = function (name, members) {
var result = originalNamespaceDefine.call(this, name, members);
if (typeof name === 'string' && result) {
// Get the global object
var globalObj = (function () {
return this;
})();
// Define the caller location of parent namespaces that haven't yet been defined
var path;
var namespaceParts = name.split(".");
for (var i = 0; i < namespaceParts.length - 1; i++) {
path = ((i === 0) ? namespaceParts[i] : path += "." + namespaceParts[i]);
var item = globalObj[path];
if (item) {
intellisense.callerDefines(item);
}
}
// Define the caller location of the original namespace
intellisense.callerDefines(result, members);
}
return result;
};
redirect(WinJS.Namespace.define, originalNamespaceDefine);
intellisense.setCallContext(WinJS.Promise, { thisArg: {}, args: [function () { }] });
})();
(function () {
// In the language serivce all promises are completed promises. The completed promise class is private
// to WinJS, however, we can get access to the prototype through one of the promise instances by
// getting the instance's constructor's prototype.
var promisePrototype = WinJS.Promise.as(1).constructor.prototype;
// Setting the argument calling context of the done and then methods to be an instance of Error().
// The completion callback is handled in WinJS itself through a <returns> metadata comment.
var originalDone = promisePrototype.done;
promisePrototype.done = function (c, e, p) {
intellisense.setCallContext(e, { thisArg: this, args: [new Error()] });
return originalDone.apply(this, arguments);
};
redirect(promisePrototype.done, originalDone);
var originalThen = promisePrototype.then;
promisePrototype.then = function (c, e, p) {
intellisense.setCallContext(e, { thisArg: this, args: [new Error()] });
return originalThen.apply(this, arguments);
};
redirect(promisePrototype.then, originalThen);
})();
if (window._$originalAddEventListener) {
window.addEventListener = window._$originalAddEventListener;
window._$originalAddEventListener = null;
delete window._$originalAddEventListener;
}
})();
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Lahadi",
"Litinin",
"Talata",
"Laraba",
"Alhamis",
"Jumma\u02bca",
"Asabar"
],
"MONTH": [
"Janairu",
"Faburairu",
"Maris",
"Afirilu",
"Mayu",
"Yuni",
"Yuli",
"Agusta",
"Satumba",
"Oktoba",
"Nuwamba",
"Disamba"
],
"SHORTDAY": [
"Lh",
"Li",
"Ta",
"Lr",
"Al",
"Ju",
"As"
],
"SHORTMONTH": [
"Jan",
"Fab",
"Mar",
"Afi",
"May",
"Yun",
"Yul",
"Agu",
"Sat",
"Okt",
"Nuw",
"Dis"
],
"fullDate": "EEEE, d MMMM, y",
"longDate": "d MMMM, y",
"medium": "d MMM, y HH:mm:ss",
"mediumDate": "d MMM, y",
"mediumTime": "HH:mm:ss",
"short": "d/M/yy HH:mm",
"shortDate": "d/M/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20a6",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "ha-latn-ng",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
/**
@name: aping
@version: 0.8.1 (11-01-2016)
@author: Jonathan Hornung <jonathan.hornung@gmail.com>
@url: https://github.com/JohnnyTheTank/apiNG#readme
@license: MIT
*/
"use strict";
var apingApp = angular.module('jtt_aping', ['jtt_aping_jsonloader', 'jtt_aping_ng_array'])
.config(['$provide', function ($provide) {
$provide.value("apingDefaultSettings", {
apingApiKeys: {}
});
}])
.directive('aping', ['apingDefaultSettings', 'apingUtilityHelper', function (apingDefaultSettings, apingUtilityHelper) {
return {
restrict: 'E',
replace: 'false',
scope: {
model: '@',
getNativeData: '@',
items: '@',
maxItems: '@',
orderBy: '@',
orderReverse: '@',
templateUrl: '@',
payloadJson: '@',
removeDoubles: '@'
},
controller: ['$scope', function ($scope) {
$scope.results = [];
$scope.payload = $scope.payloadJson ? apingUtilityHelper.replaceSingleQuotesAndParseJson($scope.payloadJson) : {};
/**
* return current appSettings by merging 'apingDefaultSettings' and '$scope params'
* @returns {Object}
*/
this.getAppSettings = function () {
var items;
var maxItems;
var getNativeData;
var orderReverse;
var orderBy;
var removeDoubles;
if (typeof $scope.items !== "undefined") {
items = $scope.items;
} else if (typeof apingDefaultSettings.items !== "undefined") {
items = apingDefaultSettings.items;
} else {
items = undefined;
}
if (typeof $scope.maxItems !== "undefined") {
maxItems = $scope.maxItems;
} else if (typeof apingDefaultSettings.maxItems !== "undefined") {
maxItems = apingDefaultSettings.maxItems;
} else {
maxItems = undefined;
}
if (typeof $scope.getNativeData !== "undefined") {
getNativeData = $scope.getNativeData;
} else if (typeof apingDefaultSettings.getNativeData !== "undefined") {
getNativeData = apingDefaultSettings.getNativeData;
} else {
getNativeData = false;
}
if (typeof $scope.maxItems !== "undefined") {
maxItems = $scope.maxItems;
} else if (typeof apingDefaultSettings.maxItems !== "undefined") {
maxItems = apingDefaultSettings.maxItems;
} else {
maxItems = undefined;
}
if (typeof $scope.orderBy !== "undefined") {
orderBy = $scope.orderBy;
} else if (typeof apingDefaultSettings.orderBy !== "undefined") {
orderBy = apingDefaultSettings.orderBy;
} else {
orderBy = "undefined";
}
if (typeof $scope.orderReverse !== "undefined") {
orderReverse = $scope.orderReverse;
} else if (typeof apingDefaultSettings.orderReverse !== "undefined") {
orderReverse = apingDefaultSettings.orderReverse;
} else {
orderReverse = false;
}
if (typeof $scope.removeDoubles !== "undefined") {
removeDoubles = $scope.removeDoubles;
} else if (typeof apingDefaultSettings.removeDoubles !== "undefined") {
removeDoubles = apingDefaultSettings.removeDoubles;
} else {
removeDoubles = false;
}
return {
model: $scope.model || apingDefaultSettings.model || "native",
getNativeData: getNativeData,
items: items,
maxItems: maxItems,
orderBy: orderBy,
orderReverse: orderReverse,
removeDoubles: removeDoubles
};
};
/**
* merge current '$scope.results' with '_array' and do some operations
*
* @param _array
*/
this.concatToResults = function (_array) {
$scope.results = $scope.results.concat(_array);
var appSettings = this.getAppSettings();
if (appSettings.removeDoubles === true || appSettings.removeDoubles === "true") {
$scope.results = apingUtilityHelper.removeDuplicateObjectsFromArray($scope.results, (appSettings.orderBy === false || appSettings.orderBy === "false" || appSettings.orderBy === "$NONE"));
}
if (appSettings.orderBy !== "undefined" && appSettings.orderBy !== false && appSettings.orderBy !== "false" && appSettings.orderBy !== "$NONE") {
if (appSettings.orderBy === "$RANDOM") {
$scope.results = apingUtilityHelper.shuffleArray($scope.results);
} else {
$scope.results.sort(apingUtilityHelper.sortArrayByProperty(appSettings.orderBy));
if (appSettings.orderReverse === true || appSettings.orderReverse === "true") {
$scope.results.reverse();
}
}
}
if (appSettings.maxItems > -1 && $scope.results.length > appSettings.maxItems) {
$scope.results = $scope.results.splice(0, appSettings.maxItems);
}
$scope.$broadcast('apiNG.resultMerged');
};
this.apply = function () {
$scope.$apply();
};
}],
templateUrl: function (elem, scope) {
return scope.templateUrl || apingDefaultSettings.templateUrl;
}
};
}]);
;"use strict";
apingApp
.service('apingTimeHelper', function () {
/**
* parse Timestamp from DateString and do some math
*
* @param _string {String}
* @param _multiplier {number}
* @param _add {number}
* @returns {Number}
*/
this.getTimestampFromDateString = function (_string, _multiplier, _add) {
if (typeof _multiplier === "undefined" || isNaN(_multiplier)) {
_multiplier = 1;
}
if (typeof _add === "undefined" || isNaN(_add)) {
_add = 0;
}
if (typeof _string === "string") {
var a = _string.split(/[^0-9]/);
try {
return parseInt(Math.round(new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]) / 1000 * _multiplier) + _add, 10);
} catch (e) {
return 0;
}
}
return 0;
};
})
.service('apingUtilityHelper', ['apingInputObjects', 'apingDefaultSettings', function (apingInputObjects, apingDefaultSettings) {
/**
* return random matching API Key from Constant "apingApiKeys". If there is no matching API Key, the function returns 'false'
*
* @param _platform {String}
* @param _keyName {String}
* @returns {String}
*/
this.getApiCredentials = function (_platform, _keyName) {
if (apingDefaultSettings.apingApiKeys) {
if (apingDefaultSettings.apingApiKeys[_platform]) {
return apingDefaultSettings.apingApiKeys[_platform][Math.floor(Math.random() * apingDefaultSettings.apingApiKeys[_platform].length)][_keyName];
}
}
return false;
};
/**
* legacy function for this.parseRequestsFromAttributes()
*
* @param _string {String}
* @param _platform {String}
* @param _appSettings {Object}
* @returns {Array}
*/
this.parseJsonFromAttributes = function (_string, _platform, _appSettings) {
return this.parseRequestsFromAttributes(_string, _platform, _appSettings);
};
/**
* Parse JSON from Attributes and create requests
*
* @param _string {String}
* @param _platform {String}
* @param _appSettings {Object}
* @returns {Array}
*/
this.parseRequestsFromAttributes = function (_string, _platform, _appSettings) {
if (!(typeof _string === "string" && _string)) {
return [];
}
var requests = [];
var tempArray = this.replaceSingleQuotesAndParseJson(_string);
angular.forEach(tempArray, function (value, key) {
value.platform = _platform;
if (_appSettings) {
if (typeof value.items === "undefined" && typeof _appSettings.items !== "undefined") {
value.items = _appSettings.items;
}
if (typeof value.model === "undefined" && typeof _appSettings.model !== "undefined") {
value.model = _appSettings.model;
}
}
var request = apingInputObjects.getNew("request", value);
requests.push(request);
});
return requests;
};
/**
* replace single quotes in string and parse JSON
*
* @param _string {String}
* @returns {Array/Object}
*/
this.replaceSingleQuotesAndParseJson = function (_string) {
return $.parseJSON(_string.replace(/'/g, '"'));
};
/**
* filter function to sort an array by a property
*
* @param _property {Function}
* @returns {Function}
*/
this.sortArrayByProperty = function (_property) {
var sortOrder = 1;
if (_property[0] === "-") {
sortOrder = -1;
_property = _property.substr(1);
}
return function (a, b) {
var result = (a[_property] < b[_property]) ? -1 : (a[_property] > b[_property]) ? 1 : 0;
return result * sortOrder;
}
};
/**
* shuffle array
*
* @param _array {Array}
* @returns {Array}
*/
this.shuffleArray = function (_array) {
for (var i = _array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = _array[i];
_array[i] = _array[j];
_array[j] = temp;
}
return _array;
};
/**
* remove double objects from array
*
* @param _array {Array}
* @param _keepOrder {Boolean}
* @returns {Array}
*/
this.removeDuplicateObjectsFromArray = function (_array, _keepOrder) {
var sortedArray = [];
var stringifyPropertyName = 'apingStringified';
var orderPropertyName = 'apingTempOrder';
if (_array.length === 1) {
return _array;
}
$.each(_array, function (firstIndex, firstValue) {
firstValue['$$hashKey'] = undefined;
firstValue[stringifyPropertyName] = JSON.stringify(firstValue);
if (_keepOrder === true) {
firstValue[orderPropertyName] = firstIndex;
}
sortedArray.push(firstValue);
});
sortedArray.sort(this.sortArrayByProperty(stringifyPropertyName));
var lastValue;
var reducedArray = [];
$.each(sortedArray, function (secondIndex, secondValue) {
if (typeof lastValue !== "undefined") {
if (typeof secondValue[stringifyPropertyName] !== "undefined" && secondValue[stringifyPropertyName] !== lastValue) {
reducedArray.push(secondValue);
}
} else {
reducedArray.push(secondValue);
}
lastValue = secondValue[stringifyPropertyName];
secondValue[stringifyPropertyName] = undefined;
});
if (_keepOrder === true) {
sortedArray.sort(this.sortArrayByProperty(orderPropertyName));
$.each(sortedArray, function (thirdIndex, thirdValue) {
thirdValue[orderPropertyName] = undefined;
});
}
return reducedArray;
};
/**
* Transforms html string to plain text
*
* @param _string {String}
* @returns {String}
*/
this.getTextFromHtml = function(_string) {
_string = _string.replace(/<br ?\/\>|<br ?\/&rt;|\<br ?\/\>/g, " ");
_string = _string.replace(/<(?:.|\n)*?>/gm, '');
return _string;
};
/**
* Parses first image from html string
*
* @param _string
* @returns {Array}
*/
this.getFirstImageFromHtml = function (_string) {
var re = /<img[^>]+src="([^">]+)/g;
return re.exec(_string);
};
/**
* Parses URL Parameters from ULR (string)
*
* @param _string {String}
* @returns {Object}
*/
this.parseParametersFromUrl = function (_string) {
var result = {};
if(typeof _string === 'string') {
result = JSON.parse('{"' + decodeURI(_string.replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}');
}
return result;
}
}]);;"use strict";
apingApp.service('apingInputObjects', ['apingDefaultSettings', function (apingDefaultSettings) {
/**
* * return new clean apiNG input object by _model and _params
*
* @param _model {String}
* @param _params {Object}
* @returns {Object}
*/
this.getNew = function (_model, _params) {
var inputObject = {};
switch (_model) {
case "request":
inputObject = $.extend(true, {
model: apingDefaultSettings.model,
items: apingDefaultSettings.items
}, _params);
break;
default:
break;
}
return inputObject;
}
}]);;"use strict";
apingApp.service('apingModels', [function () {
/**
* return new clean apiNG model object by _model and _platform
*
* @param _model {String}
* @param _platform {String}
* @returns {Object}
*/
this.getNew = function(_model, _platform) {
var model = {};
switch(_model) {
case "social":
model = {
platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
blog_name : undefined, //NAME of blog (channel / youtube uploader / facebook page, instagram account, ..)
blog_id : undefined, //ID of channel / page / account, ...
blog_link : undefined, //link to channel / uploader / page / account, ...
type : undefined, //"video", "image", "post", "audio", "link", "event", ...
timestamp : undefined,
date_time: undefined,
post_url : undefined, //URL to the post / video / tweet ...
intern_id : undefined, // INTERN ID of post / video / tweet / ... (facebook id, youtube id, ...)
text : undefined,
caption : undefined,
img_url : undefined,
source : undefined, //
likes: undefined,
shares: undefined,
comments: undefined,
position: undefined
};
break;
case "video":
model = {
platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
blog_name : undefined, //NAME of blog (channel / youtube uploader / facebook page, instagram account, ..)
blog_id : undefined, //ID of channel / page / account, ...
blog_link : undefined, //link to channel / uploader / page / account, ...
timestamp : undefined,
date_time: undefined,
post_url : undefined, //URL to the post / video / tweet ...
intern_id : undefined, // INTERN ID of video (facebook id, youtube id, ...)
text : undefined,
caption : undefined,
img_url : undefined,
source : undefined, //
markup: undefined,
likes: undefined,
shares: undefined,
duration: undefined, // in seconds
width: undefined,
height: undefined,
comments: undefined,
position: undefined
};
break;
case "image":
model = {
platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
blog_name : undefined, //NAME of blog (channel / youtube uploader / facebook page, instagram account, ..)
blog_id : undefined, //ID of channel / page / account, ...
blog_link : undefined, //link to channel / uploader / page / account, ...
timestamp : undefined,
date_time: undefined,
post_url : undefined, //URL to the post / video / tweet ...
intern_id : undefined, // INTERN ID of image (facebook id, instagram id, ...)
text : undefined,
caption : undefined,
thumb_url : undefined, // best case 200px (min)
thumb_width: undefined,
thumb_height: undefined,
img_url : undefined, // best case 700px
img_width: undefined,
img_height: undefined,
native_url: undefined,
native_width: undefined,
native_height: undefined,
source : undefined, //
likes: undefined,
shares: undefined,
comments: undefined,
position: undefined
};
break;
case "event":
model = {
platform : _platform, //NAME of platform ( "facebook", "bandsintown" , ...)
artist_name : undefined,
artist_id : undefined,
artist_link : undefined,
start_timestamp : undefined,
start_date_time: undefined,
end_timestamp: undefined,
end_date_time: undefined,
event_url : undefined, //URL to the event
ticket_url : undefined, //URL to the ticket
sold_out : undefined,
intern_id : undefined, // INTERN ID of event (facebook id, instagram id, ...)
text : undefined,
caption : undefined,
img_url : undefined,
place_name : undefined,
city: undefined,
country: undefined,
latitude: undefined,
longitude : undefined,
street: undefined,
zip : undefined,
source : undefined
};
break;
case "repo":
model = {
platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
owner_name : undefined,
owner_id : undefined,
owner_link : undefined,
owner_img_url : undefined,
name : undefined,
id: undefined,
fullname: undefined,
description : undefined,
url : undefined,
homepage : undefined,
language : undefined,
clone_url : undefined,
git_url : undefined,
ssh_url : undefined,
svn_url : undefined,
isFork : undefined,
openIssues : undefined,
watchers : undefined,
stargazers : undefined,
forks : undefined,
created_timestamp : undefined,
created_date_time: undefined,
updated_timestamp: undefined,
updated_date_time: undefined,
pushed_timestamp: undefined,
pushed_date_time: undefined
};
break;
case "activity":
model = {
platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
body : undefined,
actor_name : undefined, //who?
actor_id : undefined,
actor_url : undefined,
actor_img_url : undefined,
actor_type: undefined,
action_name: undefined,
action_message : undefined, //what?
action_id : undefined,
action_url : undefined,
action_img : undefined,
action_type: undefined,
object_name : undefined,
object_id : undefined,
object_img : undefined,
object_url : undefined,
object_type: undefined,
context : undefined,
timestamp : undefined,
date_time: undefined
};
break;
case "weather":
model = {
platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
weather_code: undefined,
weather_caption: undefined, //rain
weather_text : undefined, //light rain
weather_icon_name: undefined,
weather_icon_url: undefined,
temp: undefined,
pressure: undefined,
humidity: undefined,
temp_min: undefined,
temp_max: undefined,
sea_level: undefined,
grnd_level: undefined,
wind_speed: undefined,
wind_deg: undefined,
rain_duration: undefined,
rain_volume: undefined,
clouds: undefined,
timestamp: undefined,
date_time: undefined,
sunrise_timestamp : undefined,
sunrise_date_time : undefined,
sunset_timestamp : undefined,
sunset_date_time : undefined,
loc_city : undefined,
loc_city_id: undefined,
loc_country : undefined,
loc_lat : undefined,
loc_lng : undefined,
loc_zip : undefined
};
break;
default:
break;
}
return model;
};
}]);;"use strict";
angular.module("jtt_aping_jsonloader", [])
.directive('apingJsonloader', ['apingUtilityHelper', 'jsonloaderFactory', function (apingUtilityHelper, jsonloaderFactory) {
return {
require: '?aping',
restrict: 'A',
replace: 'false',
link: function (scope, element, attrs, apingController) {
var appSettings = apingController.getAppSettings();
var requests = apingUtilityHelper.parseJsonFromAttributes(attrs.apingJsonloader, "jsonloader", appSettings);
requests.forEach(function (request) {
if (request.path) {
//create requestObject for factory function call
var requestObject = {
path: request.path,
};
if (!request.format || request.format.toLowerCase() != "jsonp") {
requestObject.format = "json";
} else {
requestObject.format = "jsonp";
}
if (request.callback && request.format === "jsonp") {
requestObject.callback = request.callback;
} else {
requestObject.callback = 'JSON_CALLBACK';
}
if(typeof request.items !== "undefined") {
requestObject.count = request.items;
} else {
requestObject.count = appSettings.items;
}
if(requestObject.count === 0 || requestObject.count === '0') {
return false;
}
// -1 is "no explicit limit". same for NaN value
if(requestObject.count < 0 || isNaN(requestObject.count)) {
requestObject.count = undefined;
}
jsonloaderFactory.getJsonData(requestObject)
.then(function (_data) {
var resultArray = [];
if (_data.data) {
if (_data.data.constructor !== Array) {
resultArray.push(_data.data);
} else {
if (request.items < 0 || typeof request.items === "undefined" ) {
resultArray = _data.data;
} else {
angular.forEach(_data.data, function (value, key) {
if (key < request.items) {
resultArray.push(value);
}
});
}
}
}
apingController.concatToResults(resultArray);
});
}
});
}
}
}])
.factory('jsonloaderFactory', ['$http', function ($http) {
var jsonloaderFactory = {};
jsonloaderFactory.getJsonData = function (_requestObject) {
if (_requestObject.format == "jsonp") {
return $http.jsonp(
_requestObject.path,
{
method: 'GET',
params: {callback: _requestObject.callback},
}
);
} else {
return $http({
method: 'GET',
url: _requestObject.path
});
}
};
return jsonloaderFactory;
}]);;"use strict";
angular.module("jtt_aping_ng_array", [])
.directive('apingNgArray', ['apingUtilityHelper', function (apingUtilityHelper) {
return {
require: '?aping',
restrict: 'A',
replace: 'false',
link: function (scope, element, attrs, apingController) {
var appSettings = apingController.getAppSettings();
var requests = apingUtilityHelper.parseJsonFromAttributes(attrs.apingNgArray, "ngArray", appSettings);
requests.forEach(function (request) {
if (request.name && scope[request.name]) {
var requestObject = {};
if(typeof request.items !== "undefined") {
requestObject.count = request.items;
} else {
requestObject.count = appSettings.items;
}
if(requestObject.count === 0 || requestObject.count === '0') {
return false;
}
// -1 is "no explicit limit". same for NaN value
if(requestObject.count < 0 || isNaN(requestObject.count)) {
requestObject.count = undefined;
}
var resultArray = [];
if (scope[request.name].constructor === Array) {
if (requestObject.items < 0 || typeof requestObject.items === "undefined") {
resultArray = scope[request.name];
} else {
angular.forEach(scope[request.name], function (value, key) {
if (key < request.items) {
resultArray.push(value);
}
});
}
} else if (typeof scope[request.name] === 'object' && scope[request.name] !== null) {
resultArray.push(scope[request.name]);
}
if (resultArray.length > 0) {
apingController.concatToResults(resultArray);
}
}
});
}
}
}]);
|
var util = require('../util');
var hammerUtil = require('../hammerUtil');
var moment = require('../module/moment');
var Component = require('./component/Component');
var DateUtil = require('./DateUtil');
/**
* @constructor Range
* A Range controls a numeric range with a start and end value.
* The Range adjusts the range based on mouse events or programmatic changes,
* and triggers events when the range is changing or has been changed.
* @param {{dom: Object, domProps: Object, emitter: Emitter}} body
* @param {Object} [options] See description at Range.setOptions
*/
function Range(body, options) {
var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
this.start = now.clone().add(-3, 'days').valueOf(); // Number
this.end = now.clone().add(4, 'days').valueOf(); // Number
this.body = body;
this.deltaDifference = 0;
this.scaleOffset = 0;
this.startToFront = false;
this.endToFront = true;
// default options
this.defaultOptions = {
rtl: false,
start: null,
end: null,
moment: moment,
direction: 'horizontal', // 'horizontal' or 'vertical'
moveable: true,
zoomable: true,
min: null,
max: null,
zoomMin: 10, // milliseconds
zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds
};
this.options = util.extend({}, this.defaultOptions);
this.props = {
touch: {}
};
this.animationTimer = null;
// drag listeners for dragging
this.body.emitter.on('panstart', this._onDragStart.bind(this));
this.body.emitter.on('panmove', this._onDrag.bind(this));
this.body.emitter.on('panend', this._onDragEnd.bind(this));
// mouse wheel for zooming
this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
// pinch to zoom
this.body.emitter.on('touch', this._onTouch.bind(this));
this.body.emitter.on('pinch', this._onPinch.bind(this));
this.setOptions(options);
}
Range.prototype = new Component();
/**
* Set options for the range controller
* @param {Object} options Available options:
* {Number | Date | String} start Start date for the range
* {Number | Date | String} end End date for the range
* {Number} min Minimum value for start
* {Number} max Maximum value for end
* {Number} zoomMin Set a minimum value for
* (end - start).
* {Number} zoomMax Set a maximum value for
* (end - start).
* {Boolean} moveable Enable moving of the range
* by dragging. True by default
* {Boolean} zoomable Enable zooming of the range
* by pinching/scrolling. True by default
*/
Range.prototype.setOptions = function (options) {
if (options) {
// copy the options that we know
var fields = [
'direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable',
'moment', 'activate', 'hiddenDates', 'zoomKey', 'rtl'
];
util.selectiveExtend(fields, this.options, options);
if ('start' in options || 'end' in options) {
// apply a new range. both start and end are optional
this.setRange(options.start, options.end);
}
}
};
/**
* Test whether direction has a valid value
* @param {String} direction 'horizontal' or 'vertical'
*/
function validateDirection (direction) {
if (direction != 'horizontal' && direction != 'vertical') {
throw new TypeError('Unknown direction "' + direction + '". ' +
'Choose "horizontal" or "vertical".');
}
}
/**
* Set a new start and end range
* @param {Date | Number | String} [start]
* @param {Date | Number | String} [end]
* @param {boolean | {duration: number, easingFunction: string}} [animation=false]
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {Boolean} [byUser=false]
*
*/
Range.prototype.setRange = function(start, end, animation, byUser) {
if (byUser !== true) {
byUser = false;
}
var finalStart = start != undefined ? util.convert(start, 'Date').valueOf() : null;
var finalEnd = end != undefined ? util.convert(end, 'Date').valueOf() : null;
this._cancelAnimation();
if (animation) { // true or an Object
var me = this;
var initStart = this.start;
var initEnd = this.end;
var duration = (typeof animation === 'object' && 'duration' in animation) ? animation.duration : 500;
var easingName = (typeof animation === 'object' && 'easingFunction' in animation) ? animation.easingFunction : 'easeInOutQuad';
var easingFunction = util.easingFunctions[easingName];
if (!easingFunction) {
throw new Error('Unknown easing function ' + JSON.stringify(easingName) + '. ' +
'Choose from: ' + Object.keys(util.easingFunctions).join(', '));
}
var initTime = new Date().valueOf();
var anyChanged = false;
var next = function () {
if (!me.props.touch.dragging) {
var now = new Date().valueOf();
var time = now - initTime;
var ease = easingFunction(time / duration);
var done = time > duration;
var s = (done || finalStart === null) ? finalStart : initStart + (finalStart - initStart) * ease;
var e = (done || finalEnd === null) ? finalEnd : initEnd + (finalEnd - initEnd) * ease;
changed = me._applyRange(s, e);
DateUtil.updateHiddenDates(me.options.moment, me.body, me.options.hiddenDates);
anyChanged = anyChanged || changed;
if (changed) {
me.body.emitter.emit('rangechange', {start: new Date(me.start), end: new Date(me.end), byUser:byUser});
}
if (done) {
if (anyChanged) {
me.body.emitter.emit('rangechanged', {start: new Date(me.start), end: new Date(me.end), byUser:byUser});
}
}
else {
// animate with as high as possible frame rate, leave 20 ms in between
// each to prevent the browser from blocking
me.animationTimer = setTimeout(next, 20);
}
}
};
return next();
}
else {
var changed = this._applyRange(finalStart, finalEnd);
DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
if (changed) {
var params = {start: new Date(this.start), end: new Date(this.end), byUser:byUser};
this.body.emitter.emit('rangechange', params);
this.body.emitter.emit('rangechanged', params);
}
}
};
/**
* Stop an animation
* @private
*/
Range.prototype._cancelAnimation = function () {
if (this.animationTimer) {
clearTimeout(this.animationTimer);
this.animationTimer = null;
}
};
/**
* Set a new start and end range. This method is the same as setRange, but
* does not trigger a range change and range changed event, and it returns
* true when the range is changed
* @param {Number} [start]
* @param {Number} [end]
* @return {Boolean} changed
* @private
*/
Range.prototype._applyRange = function(start, end) {
var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
diff;
// check for valid number
if (isNaN(newStart) || newStart === null) {
throw new Error('Invalid start "' + start + '"');
}
if (isNaN(newEnd) || newEnd === null) {
throw new Error('Invalid end "' + end + '"');
}
// prevent start < end
if (newEnd < newStart) {
newEnd = newStart;
}
// prevent start < min
if (min !== null) {
if (newStart < min) {
diff = (min - newStart);
newStart += diff;
newEnd += diff;
// prevent end > max
if (max != null) {
if (newEnd > max) {
newEnd = max;
}
}
}
}
// prevent end > max
if (max !== null) {
if (newEnd > max) {
diff = (newEnd - max);
newStart -= diff;
newEnd -= diff;
// prevent start < min
if (min != null) {
if (newStart < min) {
newStart = min;
}
}
}
}
// prevent (end-start) < zoomMin
if (this.options.zoomMin !== null) {
var zoomMin = parseFloat(this.options.zoomMin);
if (zoomMin < 0) {
zoomMin = 0;
}
if ((newEnd - newStart) < zoomMin) {
if ((this.end - this.start) === zoomMin && newStart > this.start && newEnd < this.end) {
// ignore this action, we are already zoomed to the minimum
newStart = this.start;
newEnd = this.end;
}
else {
// zoom to the minimum
diff = (zoomMin - (newEnd - newStart));
newStart -= diff / 2;
newEnd += diff / 2;
}
}
}
// prevent (end-start) > zoomMax
if (this.options.zoomMax !== null) {
var zoomMax = parseFloat(this.options.zoomMax);
if (zoomMax < 0) {
zoomMax = 0;
}
if ((newEnd - newStart) > zoomMax) {
if ((this.end - this.start) === zoomMax && newStart < this.start && newEnd > this.end) {
// ignore this action, we are already zoomed to the maximum
newStart = this.start;
newEnd = this.end;
}
else {
// zoom to the maximum
diff = ((newEnd - newStart) - zoomMax);
newStart += diff / 2;
newEnd -= diff / 2;
}
}
}
var changed = (this.start != newStart || this.end != newEnd);
// if the new range does NOT overlap with the old range, emit checkRangedItems to avoid not showing ranged items (ranged meaning has end time, not necessarily of type Range)
if (!((newStart >= this.start && newStart <= this.end) || (newEnd >= this.start && newEnd <= this.end)) &&
!((this.start >= newStart && this.start <= newEnd) || (this.end >= newStart && this.end <= newEnd) )) {
this.body.emitter.emit('checkRangedItems');
}
this.start = newStart;
this.end = newEnd;
return changed;
};
/**
* Retrieve the current range.
* @return {Object} An object with start and end properties
*/
Range.prototype.getRange = function() {
return {
start: this.start,
end: this.end
};
};
/**
* Calculate the conversion offset and scale for current range, based on
* the provided width
* @param {Number} width
* @returns {{offset: number, scale: number}} conversion
*/
Range.prototype.conversion = function (width, totalHidden) {
return Range.conversion(this.start, this.end, width, totalHidden);
};
/**
* Static method to calculate the conversion offset and scale for a range,
* based on the provided start, end, and width
* @param {Number} start
* @param {Number} end
* @param {Number} width
* @returns {{offset: number, scale: number}} conversion
*/
Range.conversion = function (start, end, width, totalHidden) {
if (totalHidden === undefined) {
totalHidden = 0;
}
if (width != 0 && (end - start != 0)) {
return {
offset: start,
scale: width / (end - start - totalHidden)
}
}
else {
return {
offset: 0,
scale: 1
};
}
};
/**
* Start dragging horizontally or vertically
* @param {Event} event
* @private
*/
Range.prototype._onDragStart = function(event) {
this.deltaDifference = 0;
this.previousDelta = 0;
// only allow dragging when configured as movable
if (!this.options.moveable) return;
// only start dragging when the mouse is inside the current range
if (!this._isInsideRange(event)) return;
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.props.touch.allowDragging) return;
this.props.touch.start = this.start;
this.props.touch.end = this.end;
this.props.touch.dragging = true;
if (this.body.dom.root) {
this.body.dom.root.style.cursor = 'move';
}
};
/**
* Perform dragging operation
* @param {Event} event
* @private
*/
Range.prototype._onDrag = function (event) {
if (!this.props.touch.dragging) return;
// only allow dragging when configured as movable
if (!this.options.moveable) return;
// TODO: this may be redundant in hammerjs2
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.props.touch.allowDragging) return;
var direction = this.options.direction;
validateDirection(direction);
var delta = (direction == 'horizontal') ? event.deltaX : event.deltaY;
delta -= this.deltaDifference;
var interval = (this.props.touch.end - this.props.touch.start);
// normalize dragging speed if cutout is in between.
var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
interval -= duration;
var width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height;
if (this.options.rtl) {
var diffRange = delta / width * interval;
} else {
var diffRange = -delta / width * interval;
}
var newStart = this.props.touch.start + diffRange;
var newEnd = this.props.touch.end + diffRange;
// snapping times away from hidden zones
var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta-delta, true);
var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta-delta, true);
if (safeStart != newStart || safeEnd != newEnd) {
this.deltaDifference += delta;
this.props.touch.start = safeStart;
this.props.touch.end = safeEnd;
this._onDrag(event);
return;
}
this.previousDelta = delta;
this._applyRange(newStart, newEnd);
var startDate = new Date(this.start);
var endDate = new Date(this.end);
// fire a rangechange event
this.body.emitter.emit('rangechange', {
start: startDate,
end: endDate,
byUser: true
});
};
/**
* Stop dragging operation
* @param {event} event
* @private
*/
Range.prototype._onDragEnd = function (event) {
if (!this.props.touch.dragging) return;
// only allow dragging when configured as movable
if (!this.options.moveable) return;
// TODO: this may be redundant in hammerjs2
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.props.touch.allowDragging) return;
this.props.touch.dragging = false;
if (this.body.dom.root) {
this.body.dom.root.style.cursor = 'auto';
}
// fire a rangechanged event
this.body.emitter.emit('rangechanged', {
start: new Date(this.start),
end: new Date(this.end),
byUser: true
});
};
/**
* Event handler for mouse wheel event, used to zoom
* Code from http://adomas.org/javascript-mouse-wheel/
* @param {Event} event
* @private
*/
Range.prototype._onMouseWheel = function(event) {
// only allow zooming when configured as zoomable and moveable
if (!(this.options.zoomable && this.options.moveable)) return;
// only zoom when the mouse is inside the current range
if (!this._isInsideRange(event)) return;
// only zoom when the according key is pressed and the zoomKey option is set
if (this.options.zoomKey && !event[this.options.zoomKey]) return;
// retrieve delta
var delta = 0;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta / 120;
} else if (event.detail) { /* Mozilla case. */
// In Mozilla, sign of delta is different than in IE.
// Also, delta is multiple of 3.
delta = -event.detail / 3;
}
// If delta is nonzero, handle it.
// Basically, delta is now positive if wheel was scrolled up,
// and negative, if wheel was scrolled down.
if (delta) {
// perform the zoom action. Delta is normally 1 or -1
// adjust a negative delta such that zooming in with delta 0.1
// equals zooming out with a delta -0.1
var scale;
if (delta < 0) {
scale = 1 - (delta / 5);
}
else {
scale = 1 / (1 + (delta / 5)) ;
}
// calculate center, the date to zoom around
var pointer = this.getPointer({x: event.clientX, y: event.clientY}, this.body.dom.center);
var pointerDate = this._pointerToDate(pointer);
this.zoom(scale, pointerDate, delta);
}
// Prevent default actions caused by mouse wheel
// (else the page and timeline both zoom and scroll)
event.preventDefault();
};
/**
* Start of a touch gesture
* @private
*/
Range.prototype._onTouch = function (event) {
this.props.touch.start = this.start;
this.props.touch.end = this.end;
this.props.touch.allowDragging = true;
this.props.touch.center = null;
this.scaleOffset = 0;
this.deltaDifference = 0;
};
/**
* Handle pinch event
* @param {Event} event
* @private
*/
Range.prototype._onPinch = function (event) {
// only allow zooming when configured as zoomable and moveable
if (!(this.options.zoomable && this.options.moveable)) return;
this.props.touch.allowDragging = false;
if (!this.props.touch.center) {
this.props.touch.center = this.getPointer(event.center, this.body.dom.center);
}
var scale = 1 / (event.scale + this.scaleOffset);
var centerDate = this._pointerToDate(this.props.touch.center);
var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, centerDate);
var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
// calculate new start and end
var newStart = (centerDate - hiddenDurationBefore) + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
var newEnd = (centerDate + hiddenDurationAfter) + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
// snapping times away from hidden zones
this.startToFront = 1 - scale <= 0; // used to do the right auto correction with periodic hidden times
this.endToFront = scale - 1 <= 0; // used to do the right auto correction with periodic hidden times
var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
if (safeStart != newStart || safeEnd != newEnd) {
this.props.touch.start = safeStart;
this.props.touch.end = safeEnd;
this.scaleOffset = 1 - event.scale;
newStart = safeStart;
newEnd = safeEnd;
}
this.setRange(newStart, newEnd, false, true);
this.startToFront = false; // revert to default
this.endToFront = true; // revert to default
};
/**
* Test whether the mouse from a mouse event is inside the visible window,
* between the current start and end date
* @param {Object} event
* @return {boolean} Returns true when inside the visible window
* @private
*/
Range.prototype._isInsideRange = function(event) {
// calculate the time where the mouse is, check whether inside
// and no scroll action should happen.
var clientX = event.center ? event.center.x : event.clientX;
if (this.options.rtl) {
var x = clientX - util.getAbsoluteLeft(this.body.dom.centerContainer);
} else {
var x = util.getAbsoluteRight(this.body.dom.centerContainer) - clientX;
}
var time = this.body.util.toTime(x);
return time >= this.start && time <= this.end;
};
/**
* Helper function to calculate the center date for zooming
* @param {{x: Number, y: Number}} pointer
* @return {number} date
* @private
*/
Range.prototype._pointerToDate = function (pointer) {
var conversion;
var direction = this.options.direction;
validateDirection(direction);
if (direction == 'horizontal') {
return this.body.util.toTime(pointer.x).valueOf();
}
else {
var height = this.body.domProps.center.height;
conversion = this.conversion(height);
return pointer.y / conversion.scale + conversion.offset;
}
};
/**
* Get the pointer location relative to the location of the dom element
* @param {{x: Number, y: Number}} touch
* @param {Element} element HTML DOM element
* @return {{x: Number, y: Number}} pointer
* @private
*/
Range.prototype.getPointer = function (touch, element) {
if (this.options.rtl) {
return {
x: util.getAbsoluteRight(element) - touch.x,
y: touch.y - util.getAbsoluteTop(element)
};
} else {
return {
x: touch.x - util.getAbsoluteLeft(element),
y: touch.y - util.getAbsoluteTop(element)
};
}
}
/**
* Zoom the range the given scale in or out. Start and end date will
* be adjusted, and the timeline will be redrawn. You can optionally give a
* date around which to zoom.
* For example, try scale = 0.9 or 1.1
* @param {Number} scale Scaling factor. Values above 1 will zoom out,
* values below 1 will zoom in.
* @param {Number} [center] Value representing a date around which will
* be zoomed.
*/
Range.prototype.zoom = function(scale, center, delta) {
// if centerDate is not provided, take it half between start Date and end Date
if (center == null) {
center = (this.start + this.end) / 2;
}
var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, center);
var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
// calculate new start and end
var newStart = (center-hiddenDurationBefore) + (this.start - (center-hiddenDurationBefore)) * scale;
var newEnd = (center+hiddenDurationAfter) + (this.end - (center+hiddenDurationAfter)) * scale;
// snapping times away from hidden zones
this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
if (safeStart != newStart || safeEnd != newEnd) {
newStart = safeStart;
newEnd = safeEnd;
}
this.setRange(newStart, newEnd, false, true);
this.startToFront = false; // revert to default
this.endToFront = true; // revert to default
};
/**
* Move the range with a given delta to the left or right. Start and end
* value will be adjusted. For example, try delta = 0.1 or -0.1
* @param {Number} delta Moving amount. Positive value will move right,
* negative value will move left
*/
Range.prototype.move = function(delta) {
// zoom start Date and end Date relative to the centerDate
var diff = (this.end - this.start);
// apply new values
var newStart = this.start + diff * delta;
var newEnd = this.end + diff * delta;
// TODO: reckon with min and max range
this.start = newStart;
this.end = newEnd;
};
/**
* Move the range to a new center point
* @param {Number} moveTo New center point of the range
*/
Range.prototype.moveTo = function(moveTo) {
var center = (this.start + this.end) / 2;
var diff = center - moveTo;
// calculate new start and end
var newStart = this.start - diff;
var newEnd = this.end - diff;
this.setRange(newStart, newEnd);
};
module.exports = Range;
|
/**
* @license Highcharts JS v5.0.11 (2017-05-04)
* Solid angular gauge module
*
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function(factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function(Highcharts) {
(function(H) {
/**
* Solid angular gauge module
*
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
var pInt = H.pInt,
pick = H.pick,
each = H.each,
isNumber = H.isNumber,
wrap = H.wrap,
Renderer = H.Renderer,
colorAxisMethods;
/**
* Symbol definition of an arc with round edges.
*
* @param {Number} x - The X coordinate for the top left position.
* @param {Number} y - The Y coordinate for the top left position.
* @param {Number} w - The pixel width.
* @param {Number} h - The pixel height.
* @param {Object} [options] - Additional options, depending on the actual
* symbol drawn.
* @param {boolean} [options.rounded] - Whether to draw rounded edges.
* @return {Array} Path of the created arc.
*/
wrap(Renderer.prototype.symbols, 'arc', function(proceed, x, y, w, h, options) {
var arc = proceed,
path = arc(x, y, w, h, options);
if (options.rounded) {
var r = options.r || w,
smallR = (r - options.innerR) / 2,
x1 = path[1],
y1 = path[2],
x2 = path[12],
y2 = path[13],
roundStart = ['A', smallR, smallR, 0, 1, 1, x1, y1],
roundEnd = ['A', smallR, smallR, 0, 1, 1, x2, y2];
// Insert rounded edge on end, and remove line.
path.splice.apply(path, [path.length - 1, 0].concat(roundStart));
// Insert rounded edge on end, and remove line.
path.splice.apply(path, [11, 3].concat(roundEnd));
}
return path;
});
// These methods are defined in the ColorAxis object, and copied here.
// If we implement an AMD system we should make ColorAxis a dependency.
colorAxisMethods = {
initDataClasses: function(userOptions) {
var axis = this,
chart = this.chart,
dataClasses,
colorCounter = 0,
options = this.options;
this.dataClasses = dataClasses = [];
each(userOptions.dataClasses, function(dataClass, i) {
var colors;
dataClass = H.merge(dataClass);
dataClasses.push(dataClass);
if (!dataClass.color) {
if (options.dataClassColor === 'category') {
colors = chart.options.colors;
dataClass.color = colors[colorCounter++];
// loop back to zero
if (colorCounter === colors.length) {
colorCounter = 0;
}
} else {
dataClass.color = axis.tweenColors(H.color(options.minColor), H.color(options.maxColor), i / (userOptions.dataClasses.length - 1));
}
}
});
},
initStops: function(userOptions) {
this.stops = userOptions.stops || [
[0, this.options.minColor],
[1, this.options.maxColor]
];
each(this.stops, function(stop) {
stop.color = H.color(stop[1]);
});
},
/**
* Translate from a value to a color
*/
toColor: function(value, point) {
var pos,
stops = this.stops,
from,
to,
color,
dataClasses = this.dataClasses,
dataClass,
i;
if (dataClasses) {
i = dataClasses.length;
while (i--) {
dataClass = dataClasses[i];
from = dataClass.from;
to = dataClass.to;
if ((from === undefined || value >= from) && (to === undefined || value <= to)) {
color = dataClass.color;
if (point) {
point.dataClass = i;
}
break;
}
}
} else {
if (this.isLog) {
value = this.val2lin(value);
}
pos = 1 - ((this.max - value) / (this.max - this.min));
i = stops.length;
while (i--) {
if (pos > stops[i][0]) {
break;
}
}
from = stops[i] || stops[i + 1];
to = stops[i + 1] || from;
// The position within the gradient
pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1);
color = this.tweenColors(
from.color,
to.color,
pos
);
}
return color;
},
/*
* Return an intermediate color between two colors, according to pos where 0
* is the from color and 1 is the to color.
*/
tweenColors: function(from, to, pos) {
// Check for has alpha, because rgba colors perform worse due to lack of
// support in WebKit.
var hasAlpha,
ret;
// Unsupported color, return to-color (#3920)
if (!to.rgba.length || !from.rgba.length) {
ret = to.input || 'none';
// Interpolate
} else {
from = from.rgba;
to = to.rgba;
hasAlpha = (to[3] !== 1 || from[3] !== 1);
ret = (hasAlpha ? 'rgba(' : 'rgb(') +
Math.round(to[0] + (from[0] - to[0]) * (1 - pos)) + ',' +
Math.round(to[1] + (from[1] - to[1]) * (1 - pos)) + ',' +
Math.round(to[2] + (from[2] - to[2]) * (1 - pos)) +
(hasAlpha ? (',' + (to[3] + (from[3] - to[3]) * (1 - pos))) : '') + ')';
}
return ret;
}
};
/**
* Handle animation of the color attributes directly
*/
each(['fill', 'stroke'], function(prop) {
H.Fx.prototype[prop + 'Setter'] = function() {
this.elem.attr(
prop,
colorAxisMethods.tweenColors(
H.color(this.start),
H.color(this.end),
this.pos
),
null,
true
);
};
});
// The solidgauge series type
H.seriesType('solidgauge', 'gauge', {
colorByPoint: true
}, {
/**
* Extend the translate function to extend the Y axis with the necessary
* decoration (#5895).
*/
translate: function() {
var axis = this.yAxis;
H.extend(axis, colorAxisMethods);
// Prepare data classes
if (!axis.dataClasses && axis.options.dataClasses) {
axis.initDataClasses(axis.options);
}
axis.initStops(axis.options);
// Generate points and inherit data label position
H.seriesTypes.gauge.prototype.translate.call(this);
},
/**
* Draw the points where each point is one needle
*/
drawPoints: function() {
var series = this,
yAxis = series.yAxis,
center = yAxis.center,
options = series.options,
renderer = series.chart.renderer,
overshoot = options.overshoot,
overshootVal = isNumber(overshoot) ? overshoot / 180 * Math.PI : 0,
thresholdAngleRad;
// Handle the threshold option
if (isNumber(options.threshold)) {
thresholdAngleRad = yAxis.startAngleRad + yAxis.translate(
options.threshold,
null,
null,
null,
true
);
}
this.thresholdAngleRad = pick(thresholdAngleRad, yAxis.startAngleRad);
each(series.points, function(point) {
var graphic = point.graphic,
rotation = yAxis.startAngleRad + yAxis.translate(point.y, null, null, null, true),
radius = (pInt(pick(point.options.radius, options.radius, 100)) * center[2]) / 200,
innerRadius = (pInt(pick(point.options.innerRadius, options.innerRadius, 60)) * center[2]) / 200,
shapeArgs,
d,
toColor = yAxis.toColor(point.y, point),
axisMinAngle = Math.min(yAxis.startAngleRad, yAxis.endAngleRad),
axisMaxAngle = Math.max(yAxis.startAngleRad, yAxis.endAngleRad),
minAngle,
maxAngle;
if (toColor === 'none') { // #3708
toColor = point.color || series.color || 'none';
}
if (toColor !== 'none') {
point.color = toColor;
}
// Handle overshoot and clipping to axis max/min
rotation = Math.max(axisMinAngle - overshootVal, Math.min(axisMaxAngle + overshootVal, rotation));
// Handle the wrap option
if (options.wrap === false) {
rotation = Math.max(axisMinAngle, Math.min(axisMaxAngle, rotation));
}
minAngle = Math.min(rotation, series.thresholdAngleRad);
maxAngle = Math.max(rotation, series.thresholdAngleRad);
if (maxAngle - minAngle > 2 * Math.PI) {
maxAngle = minAngle + 2 * Math.PI;
}
point.shapeArgs = shapeArgs = {
x: center[0],
y: center[1],
r: radius,
innerR: innerRadius,
start: minAngle,
end: maxAngle,
rounded: options.rounded
};
point.startR = radius; // For PieSeries.animate
if (graphic) {
d = shapeArgs.d;
graphic.animate(H.extend({
fill: toColor
}, shapeArgs));
if (d) {
shapeArgs.d = d; // animate alters it
}
} else {
point.graphic = renderer.arc(shapeArgs)
.addClass(point.getClassName(), true)
.attr({
fill: toColor,
'sweep-flag': 0
})
.add(series.group);
}
});
},
/**
* Extend the pie slice animation by animating from start angle and up
*/
animate: function(init) {
if (!init) {
this.startAngleRad = this.thresholdAngleRad;
H.seriesTypes.pie.prototype.animate.call(this, init);
}
}
});
}(Highcharts));
}));
|
var Datastore = require('../lib/datastore')
, benchDb = 'workspace/loaddb.bench.db'
, fs = require('fs')
, path = require('path')
, async = require('async')
, commonUtilities = require('./commonUtilities')
, execTime = require('exec-time')
, profiler = new execTime('LOADDB BENCH')
, d = new Datastore(benchDb)
, program = require('commander')
, n
;
program
.option('-n --number [number]', 'Size of the collection to test on', parseInt)
.option('-i --with-index', 'Test with an index')
.parse(process.argv);
n = program.number || 10000;
console.log("----------------------------");
console.log("Test with " + n + " documents");
console.log(program.withIndex ? "Use an index" : "Don't use an index");
console.log("----------------------------");
async.waterfall([
async.apply(commonUtilities.prepareDb, benchDb)
, function (cb) {
d.loadDatabase(cb);
}
, function (cb) { profiler.beginProfiling(); return cb(); }
, async.apply(commonUtilities.insertDocs, d, n, profiler)
, async.apply(commonUtilities.loadDatabase, d, n, profiler)
], function (err) {
profiler.step("Benchmark finished");
if (err) { return console.log("An error was encountered: ", err); }
});
|
/* ==========================================================
* GitGraph v1.1.3
* https://github.com/nicoespeon/gitgraph.js
* ==========================================================
* Copyright (c) 2016 Nicolas CARLO (@nicoespeon) ٩(^‿^)۶
* Copyright (c) 2016 Fabien BERNARD (@fabien0102) ✌(✰‿✰)✌
*
* GitGraph.js may be freely distributed under the MIT Licence
* ========================================================== */
(function () {
"use strict";
/**
* Emit an event on the given element.
*
* @param {HTMLElement} element - DOM element to trigger the event on.
* @param {String} eventName - Name of the triggered event.
* @param {Object} [data={}] - Custom data to attach to the event.
* @private
*/
function _emitEvent ( element, eventName, data ) {
var event;
if ( document.createEvent ) {
event = document.createEvent( "HTMLEvents" );
event.initEvent( eventName, true, true );
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.data = data || {};
if ( document.createEvent ) {
element.dispatchEvent( event );
} else {
element.fireEvent( "on" + event.eventType, event );
}
}
/**
* Returns the scaling factor of given canvas `context`.
* Handles high-resolution displays.
*
* @param {Object} context
* @returns {Number}
* @private
*/
function _getScale ( context ) {
var backingStorePixelRatio;
var scalingFactor;
// Account for high-resolution displays
scalingFactor = 1;
if ( window.devicePixelRatio ) {
backingStorePixelRatio = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
scalingFactor *= window.devicePixelRatio / backingStorePixelRatio;
}
return scalingFactor;
}
/**
* GitGraph
*
* @constructor
*
* @param {Object} options - GitGraph options
* @param {String} [options.elementId = "gitGraph"] - Id of the canvas container
* @param {Template|String|Object} [options.template] - Template of the graph
* @param {String} [options.author = "Sergio Flores <saxo-guy@epic.com>"] - Default author for commits
* @param {String} [options.mode = (null|"compact")] - Display mode
* @param {HTMLElement} [options.canvas] - DOM canvas (ex: document.getElementById("id"))
* @param {String} [options.orientation = ("vertical-reverse"|"horizontal"|"horizontal-reverse")] - Graph orientation
*
* @this GitGraph
**/
function GitGraph ( options ) {
// Options
options = (typeof options === "object") ? options : {};
this.elementId = (typeof options.elementId === "string") ? options.elementId : "gitGraph";
this.author = (typeof options.author === "string") ? options.author : "Sergio Flores <saxo-guy@epic.com>";
// Template management
if ( (typeof options.template === "string")
|| (typeof options.template === "object") ) {
this.template = this.newTemplate( options.template );
}
else if ( options.template instanceof Template ) {
this.template = options.template;
}
else {
this.template = this.newTemplate( "metro" );
}
this.mode = options.mode || null;
if ( this.mode === "compact" ) {
this.template.commit.message.display = false;
}
// Orientation
switch ( options.orientation ) {
case "vertical-reverse" :
this.template.commit.spacingY *= -1;
this.orientation = "vertical-reverse";
this.template.branch.labelRotation = 0;
this.template.commit.tag.spacingY *= -1;
break;
case "horizontal" :
this.template.commit.message.display = false;
this.template.commit.spacingX = this.template.commit.spacingY;
this.template.branch.spacingY = this.template.branch.spacingX;
this.template.commit.spacingY = 0;
this.template.branch.spacingX = 0;
this.orientation = "horizontal";
this.template.branch.labelRotation = -90;
this.template.commit.tag.spacingX = -this.template.commit.spacingX;
this.template.commit.tag.spacingY = this.template.branch.spacingY;
break;
case "horizontal-reverse" :
this.template.commit.message.display = false;
this.template.commit.spacingX = -this.template.commit.spacingY;
this.template.branch.spacingY = this.template.branch.spacingX;
this.template.commit.spacingY = 0;
this.template.branch.spacingX = 0;
this.orientation = "horizontal-reverse";
this.template.branch.labelRotation = 90;
this.template.commit.tag.spacingX = -this.template.commit.spacingY;
this.template.commit.tag.spacingY = this.template.branch.spacingY;
break;
default:
this.orientation = "vertical";
this.template.branch.labelRotation = 0;
break;
}
this.marginX = this.template.branch.spacingX + this.template.commit.dot.size * 2;
this.marginY = this.template.branch.spacingY + this.template.commit.dot.size * 2;
this.offsetX = 0;
this.offsetY = 0;
// Canvas init
this.canvas = document.getElementById( this.elementId ) || options.canvas;
this.context = this.canvas.getContext( "2d" );
this.context.textBaseline = "center";
// Tooltip layer
this.tooltip = document.createElement( "div" );
this.tooltip.className = "gitgraph-tooltip";
this.tooltip.style.position = "fixed";
this.tooltip.style.display = "none";
// Add tooltip div into body
document.body.appendChild( this.tooltip );
// Navigation vars
this.HEAD = null;
this.branches = [];
this.commits = [];
// Utilities
this.columnMax = 0; // nb of column for message position
this.commitOffsetX = 0;
this.commitOffsetY = 0;
// Bindings
var mouseMoveOptions = {
handleEvent: this.hover,
gitgraph: this
};
this.canvas.addEventListener( "mousemove", mouseMoveOptions, false );
var mouseDownOptions = {
handleEvent: this.click,
gitgraph: this
};
this.canvas.addEventListener( "mousedown", mouseDownOptions, false );
// Render on window resize
window.onresize = this.render.bind( this );
}
/**
* Create new branch
*
* @param {(String | Object)} options - Branch name | Options of Branch
*
* @see Branch
* @this GitGraph
*
* @return {Branch} New branch
**/
GitGraph.prototype.branch = function ( options ) {
// Options
if ( typeof options === "string" ) {
var name = options;
options = {};
options.name = name;
}
options = (typeof options === "object") ? options : {};
options.parent = this;
options.parentBranch = options.parentBranch || this.HEAD;
// Add branch
var branch = new Branch( options );
this.branches.push( branch );
// Return
return branch;
};
/**
* Create new orphan branch
*
* @param {(String | Object)} options - Branch name | Options of Branch
*
* @see Branch
* @this GitGraph
*
* @return {Branch} New branch
**/
GitGraph.prototype.orphanBranch = function ( options ) {
// Options
if ( typeof options === "string" ) {
var name = options;
options = {};
options.name = name;
}
options = (typeof options === "object") ? options : {};
options.parent = this;
// Add branch
var branch = new Branch( options );
this.branches.push( branch );
// Return
return branch;
};
/**
* Commit on HEAD
*
* @param {Object} options - Options of commit
*
* @see Commit
* @this GitGraph
*
* @return {GitGraph} this - Return the main object so we can chain
**/
GitGraph.prototype.commit = function ( options ) {
this.HEAD.commit( options );
// Return the main object so we can chain
return this;
};
/**
* Create a new template
*
* @param {(String|Object)} options - The template name, or the template options
*
* @return {Template}
**/
GitGraph.prototype.newTemplate = function ( options ) {
if ( typeof options === "string" ) {
return new Template().get( options );
}
return new Template( options );
};
/**
* Render the canvas
*
* @this GitGraph
**/
GitGraph.prototype.render = function () {
var scalingFactor = _getScale( this.context );
// Resize canvas
var unscaledResolution = {
x: Math.abs( (this.columnMax + 1 ) * this.template.branch.spacingX )
+ Math.abs( this.commitOffsetX )
+ this.marginX * 2,
y: Math.abs( (this.columnMax + 1 ) * this.template.branch.spacingY )
+ Math.abs( this.commitOffsetY )
+ this.marginY * 2
};
if ( this.template.commit.message.display ) {
unscaledResolution.x += 800;
}
unscaledResolution.x += this.template.commit.widthExtension;
this.canvas.style.width = unscaledResolution.x + "px";
this.canvas.style.height = unscaledResolution.y + "px";
this.canvas.width = unscaledResolution.x * scalingFactor;
this.canvas.height = unscaledResolution.y * scalingFactor;
// Clear All
this.context.clearRect( 0, 0, this.canvas.width, this.canvas.height );
// Add some margin
this.context.translate( this.marginX, this.marginY );
// Translate for inverse orientation
if ( this.template.commit.spacingY > 0 ) {
this.context.translate( 0, this.canvas.height - this.marginY * 2 );
this.offsetY = this.canvas.height - this.marginY * 2;
}
if ( this.template.commit.spacingX > 0 ) {
this.context.translate( this.canvas.width - this.marginX * 2, 0 );
this.offsetX = this.canvas.width - this.marginX * 2;
}
// Scale the context when every transformations have been made.
this.context.scale( scalingFactor, scalingFactor );
// Render branches
for ( var i = this.branches.length - 1, branch; !!(branch = this.branches[ i ]); i-- ) {
branch.render();
}
this.tagNum = 0;
// Render commits after to put them on the foreground
for ( var j = 0, commit; !!(commit = this.commits[ j ]); j++ ) {
commit.render();
}
};
/**
* A callback for each commit
*
* @callback commitCallback
* @param {Commit} commit - A commit
* @param {boolean} mouseOver - True, if the mouse is currently hovering over the commit
*/
/**
* Hover event on commit dot
*
* @param {MouseEvent} event - Mouse event
* @param {commitCallback} callbackFn - A callback function that will be called for each commit
*
* @this GitGraph
**/
GitGraph.prototype.applyCommits = function ( event, callbackFn ) {
var scalingFactor = _getScale( this.context );
for ( var i = 0, commit; !!(commit = this.commits[ i ]); i++ ) {
var distanceX = (commit.x + (this.offsetX + this.marginX) / scalingFactor - event.offsetX);
var distanceY = (commit.y + (this.offsetY + this.marginY) / scalingFactor - event.offsetY);
var distanceBetweenCommitCenterAndMouse = Math.sqrt( Math.pow( distanceX, 2 ) + Math.pow( distanceY, 2 ) );
var isOverCommit = distanceBetweenCommitCenterAndMouse < this.template.commit.dot.size;
callbackFn( commit, isOverCommit );
}
};
/**
* Hover event on commit dot
*
* @param {MouseEvent} event - Mouse event
*
* @this GitGraph
**/
GitGraph.prototype.hover = function ( event ) {
var self = this.gitgraph;
var isOut = true;
function showCommitTooltip ( commit ) {
// Fix firefox MouseEvent
if ( typeof InstallTrigger !== "undefined" )/* == (is Firefox) */ {
event.x = event.x ? event.x : event.clientX;
event.y = event.y ? event.y : event.clientY;
}
self.tooltip.style.left = event.x + "px"; // TODO Scroll bug
self.tooltip.style.top = event.y + "px"; // TODO Scroll bug
if ( self.template.commit.tooltipHTMLFormatter !== null ) {
self.tooltip.innerHTML = self.template.commit.tooltipHTMLFormatter( commit );
} else {
self.tooltip.textContent = commit.sha1 + " - " + commit.message;
}
self.tooltip.style.display = "block";
}
function emitMouseoverEvent ( commit ) {
var mouseoverEventOptions = {
author: commit.author,
message: commit.message,
date: commit.date,
sha1: commit.sha1
};
_emitEvent( self.canvas, "commit:mouseover", mouseoverEventOptions );
}
self.applyCommits( event, function ( commit, isOverCommit ) {
if ( isOverCommit ) {
if ( !self.template.commit.message.display ) {
showCommitTooltip( commit );
}
if ( !commit.isMouseover ) {
emitMouseoverEvent( commit );
}
isOut = false;
commit.isMouseover = true;
} else {
commit.isMouseover = false;
}
} );
if ( isOut ) {
self.tooltip.style.display = "none";
}
};
/**
* Click event on commit dot
*
* @param {MouseEvent} event - Mouse event
*
* @this GitGraph
**/
GitGraph.prototype.click = function ( event ) {
this.gitgraph.applyCommits( event, function ( commit, isOverCommit ) {
if ( !isOverCommit ) {
return;
}
if ( commit.onClick !== null ) {
commit.onClick( commit, true );
}
} );
};
// --------------------------------------------------------------------
// ----------------------- Branch ------------------------
// --------------------------------------------------------------------
/**
* Branch
*
* @constructor
*
* @param {Object} options - Options of branch
* @param {GitGraph} options.parent - GitGraph constructor
* @param {Branch} [options.parentBranch] - Parent branch
* @param {String} [options.name = "no-name"] - Branch name
*
* @this Branch
**/
function Branch ( options ) {
// Check integrity
if ( options.parent instanceof GitGraph === false ) {
return;
}
// Options
options = (typeof options === "object") ? options : {};
this.parent = options.parent;
this.parentBranch = options.parentBranch;
this.name = (typeof options.name === "string") ? options.name : "no-name";
this.context = this.parent.context;
this.template = this.parent.template;
this.lineWidth = options.lineWidth || this.template.branch.lineWidth;
this.lineDash = options.lineDash || this.template.branch.lineDash;
this.showLabel = booleanOptionOr( options.showLabel, this.template.branch.showLabel );
this.spacingX = this.template.branch.spacingX;
this.spacingY = this.template.branch.spacingY;
this.size = 0;
this.height = 0;
this.width = 0;
this.commits = [];
this.path = []; // Path to draw, this is an array of points {x, y, type("start"|"join"|"end")}
// Column number calculation for auto-color & auto-offset
if ( typeof options.column === "number" ) {
this.column = options.column;
} else {
this.column = 0;
this.calculColumn();
}
this.parent.columnMax = (this.column > this.parent.columnMax) ? this.column : this.parent.columnMax;
// Options with auto value
this.offsetX = this.column * this.spacingX;
this.offsetY = this.column * this.spacingY;
var columnIndex = (this.column % this.template.colors.length);
this.color = options.color || this.template.branch.color || this.template.colors[ columnIndex ];
// Checkout on this new branch
this.checkout();
}
/**
* Create new branch
*
* @param {(String | Object)} options - Branch name | Options of Branch
*
* @see Branch
* @this Branch
*
* @return {Branch} New Branch
**/
Branch.prototype.branch = function ( options ) {
// Options
if ( typeof options === "string" ) {
var name = options;
options = {};
options.name = name;
}
options = (typeof options === "object") ? options : {};
options.parent = this.parent;
options.parentBranch = options.parentBranch || this;
// Add branch
var branch = new Branch( options );
this.parent.branches.push( branch );
// Return
return branch;
};
/**
* Render the branch
*
* @this Branch
**/
Branch.prototype.render = function () {
this.context.beginPath();
for ( var i = 0, point; !!(point = this.path[ i ]); i++ ) {
if ( point.type === "start" ) {
this.context.moveTo( point.x, point.y );
} else {
if ( this.template.branch.mergeStyle === "bezier" ) {
var path = this.path[ i - 1 ];
this.context.bezierCurveTo(
path.x - this.template.commit.spacingX / 2, path.y - this.template.commit.spacingY / 2,
point.x + this.template.commit.spacingX / 2, point.y + this.template.commit.spacingY / 2,
point.x, point.y
);
} else {
this.context.lineTo( point.x, point.y );
}
}
}
this.context.lineWidth = this.lineWidth;
this.context.strokeStyle = this.color;
if ( this.context.setLineDash !== undefined ) {
this.context.setLineDash( this.lineDash );
}
this.context.stroke();
this.context.closePath();
};
/**
* Add a commit
*
* @param {(String | Object)} [options] - Message | Options of commit
* @param {String} [options.detailId] - Id of detail DOM Element
*
* @see Commit
*
* @this Branch
**/
Branch.prototype.commit = function ( options ) {
if ( typeof (options) === "string" ) {
var message = options;
options = { message: message };
} else if ( typeof (options) !== "object" ) {
options = {};
}
options.arrowDisplay = this.template.arrow.active;
options.branch = this;
var columnIndex = (this.column % this.template.colors.length);
options.color = options.color || this.template.commit.color || this.template.colors[ columnIndex ];
options.parent = this.parent;
options.parentCommit = options.parentCommit || this.commits.slice( -1 )[ 0 ];
// Special compact mode
if ( this.parent.mode === "compact"
&& this.parent.commits.slice( -1 )[ 0 ]
&& this.parent.commits.slice( -1 )[ 0 ].branch !== options.branch
&& options.branch.commits.length
&& options.type !== "mergeCommit" ) {
this.parent.commitOffsetX -= this.template.commit.spacingX;
this.parent.commitOffsetY -= this.template.commit.spacingY;
}
options.messageColor = options.messageColor || this.template.commit.message.color || options.color || null;
options.labelColor = options.labelColor || this.template.branch.labelColor || options.color || null;
options.tagColor = options.tagColor || this.template.commit.tag.color || options.color || null;
options.dotColor = options.dotColor || this.template.commit.dot.color || options.color || null;
options.x = this.offsetX - this.parent.commitOffsetX;
options.y = this.offsetY - this.parent.commitOffsetY;
// Detail
var isVertical = this.parent.orientation === "vertical";
var isNotCompact = this.parent.mode !== "compact";
if ( typeof options.detailId === "string" && isVertical && isNotCompact ) {
options.detail = document.getElementById( options.detailId );
} else {
options.detail = null;
}
// Check collision (Cause of special compact mode)
var previousCommit = options.branch.commits.slice( -1 )[ 0 ] || {};
var commitPosition = options.x + options.y;
var previousCommitPosition = previousCommit.x + previousCommit.y;
var isCommitAtSamePlaceThanPreviousOne = (commitPosition === previousCommitPosition);
if ( isCommitAtSamePlaceThanPreviousOne ) {
this.parent.commitOffsetX += this.template.commit.spacingX;
this.parent.commitOffsetY += this.template.commit.spacingY;
options.x = this.offsetX - this.parent.commitOffsetX;
options.y = this.offsetY - this.parent.commitOffsetY;
}
// Fork case: Parent commit from parent branch
if ( options.parentCommit instanceof Commit === false && this.parentBranch instanceof Branch ) {
options.parentCommit = this.parentBranch.commits.slice( -1 )[ 0 ];
}
// First commit
var isFirstBranch = options.parentCommit instanceof Commit;
var isPathBeginning = this.path.length === 0;
options.showLabel = (isPathBeginning && this.showLabel) ? true : false;
if ( options.showLabel ) {
options.x -= this.template.commit.spacingX;
options.y -= this.template.commit.spacingY;
}
var commit = new Commit( options );
this.commits.push( commit );
// Add point(s) to path
var point = {
x: commit.x,
y: commit.y,
type: "join"
};
if ( isFirstBranch && isPathBeginning ) {
var parent = {
x: commit.parentCommit.branch.offsetX - this.parent.commitOffsetX + this.template.commit.spacingX,
y: commit.parentCommit.branch.offsetY - this.parent.commitOffsetY + this.template.commit.spacingY,
type: "start"
};
this.path.push( JSON.parse( JSON.stringify( parent ) ) ); // Elegant way for cloning an object
parent.type = "join";
this.parentBranch.path.push( parent );
} else if ( isPathBeginning ) {
point.type = "start";
}
// Increment commitOffset for next commit position
this.path.push( point );
this.parent.commitOffsetX += this.template.commit.spacingX * (options.showLabel ? 2 : 1);
this.parent.commitOffsetY += this.template.commit.spacingY * (options.showLabel ? 2 : 1);
// Add height of detail div (normal vertical mode only)
if ( commit.detail !== null ) {
commit.detail.style.display = "block";
this.parent.commitOffsetY -= commit.detail.clientHeight - 40;
}
// Auto-render
this.parent.render();
// Return the main object so we can chain
return this;
};
/**
* Checkout onto this branch
*
* @this Branch
**/
Branch.prototype.checkout = function () {
this.parent.HEAD = this;
};
/**
* Delete this branch
*
* @this Branch
**/
Branch.prototype.delete = function () {
this.isfinish = true;
};
/**
* Merge branch
*
* @param {Branch} [target = this.parent.HEAD]
* @param {(String | Object)} [commitOptions] - Message | Options of commit
*
* @this Branch
*
* @return {Branch} this
**/
Branch.prototype.merge = function ( target, commitOptions ) {
// Merge target
var targetBranch = target || this.parent.HEAD;
// Check integrity of target
if ( targetBranch instanceof Branch === false || targetBranch === this ) {
return;
}
// Merge commit
var defaultMessage = "Merge branch `" + this.name + "` into `" + targetBranch.name + "`";
if ( typeof commitOptions !== "object" ) {
var message = commitOptions;
commitOptions = {};
commitOptions.message = (typeof message === "string") ? message : defaultMessage;
} else {
commitOptions.message = commitOptions.message || defaultMessage;
}
commitOptions.type = "mergeCommit";
commitOptions.parentCommit = this.commits.slice( -1 )[ 0 ];
targetBranch.commit( commitOptions );
// Add points to path
var targetCommit = targetBranch.commits.slice( -1 )[ 0 ];
var endOfBranch = {
x: this.offsetX + this.template.commit.spacingX * (targetCommit.showLabel ? 3 : 2) - this.parent.commitOffsetX,
y: this.offsetY + this.template.commit.spacingY * (targetCommit.showLabel ? 3 : 2) - this.parent.commitOffsetY,
type: "join"
};
this.path.push( JSON.parse( JSON.stringify( endOfBranch ) ) ); // Elegant way for cloning an object
var mergeCommit = {
x: targetCommit.x,
y: targetCommit.y,
type: "end"
};
this.path.push( mergeCommit );
endOfBranch.type = "start";
this.path.push( endOfBranch ); // End of branch for future commits
// Auto-render
this.parent.render();
// Checkout on target
this.parent.HEAD = targetBranch;
// Return the main object so we can chain
return this;
};
/**
* Calcul column
*
* @this Branch
**/
Branch.prototype.calculColumn = function () {
var candidates = [];
for ( var i = 0, branch; !!(branch = this.parent.branches[ i ]); i++ ) {
if ( !branch.isfinish ) {
if ( !( branch.column in candidates ) ) {
candidates[ branch.column ] = 0;
}
candidates[ branch.column ]++;
}
}
this.column = 0;
for ( ; ; this.column++ ) {
if ( !( this.column in candidates ) || candidates[ this.column ] === 0 ) {
break;
}
}
};
// --------------------------------------------------------------------
// ----------------------- Commit ------------------------
// --------------------------------------------------------------------
/**
* Commit
*
* @constructor
*
* @param {Object} options - Commit options
* @param {GitGraph} options.parent - GitGraph constructor
* @param {Number} options.x - Position X (dot)
* @param {Number} options.y - Position Y (dot)
* @param {String} options.color - Master color (dot & message)
* @param {Boolean} options.arrowDisplay - Add a arrow under commit dot
* @param {String} [options.author = this.parent.author] - Author name & email
* @param {String} [options.date] - Date of commit, default is now
* @param {String} [options.detail] - DOM Element of detail part
* @param {String} [options.sha1] - Sha1, default is a random short sha1
* @param {String} [options.dotColor = options.color] - Specific dot color
* @param {Number} [options.dotSize = this.template.commit.dot.size] - Dot size
* @param {Number} [options.dotStrokeWidth = this.template.commit.dot.strokeWidth] - Dot stroke width
* @param {Number} [options.dotStrokeColor = this.template.commit.dot.strokeColor]
* @param {Commit} [options.parentCommit] - Parent commit
* @param {String} [options.message = "He doesn't like George Michael! Boooo!"] - Commit message
* @param {String} [options.messageColor = options.color] - Specific message color
* @param {Boolean} [options.messageDisplay = this.template.commit.message.display] - Commit message policy
* @param {Boolean} [options.messageAuthorDisplay = this.template.commit.message.displayAuthor] - Commit message author policy
* @param {Boolean} [options.messageBranchDisplay = this.template.commit.message.displayBranch] - Commit message author policy
* @param {Boolean} [options.messageHashDisplay = this.template.commit.message.displayHash] - Commit message hash policy
* @param {String} [options.type = ("mergeCommit"|null)] - Type of commit
* @param {commitCallback} [options.onClick] - OnClick event for the commit dot
* @param {Object} [options.representedObject] - Any object which is related to this commit. Can be used in onClick or the formatter. Useful to bind the commit to external objects such as database id etc.
*
* @this Commit
**/
function Commit ( options ) {
// Check integrity
if ( options.parent instanceof GitGraph === false ) {
return;
}
// Options
options = (typeof options === "object") ? options : {};
this.parent = options.parent;
this.template = this.parent.template;
this.context = this.parent.context;
this.branch = options.branch;
this.author = options.author || this.parent.author;
this.date = options.date || new Date().toUTCString();
this.detail = options.detail || null;
this.tag = options.tag || null;
this.tagColor = options.tagColor || options.color;
this.tagFont = options.tagFont || this.template.commit.tag.font;
this.sha1 = options.sha1 || (Math.random( 100 )).toString( 16 ).substring( 3, 10 );
this.message = options.message || "He doesn't like George Michael! Boooo!";
this.arrowDisplay = options.arrowDisplay;
this.messageDisplay = booleanOptionOr( options.messageDisplay, this.template.commit.message.display );
this.messageAuthorDisplay = booleanOptionOr( options.messageAuthorDisplay, this.template.commit.message.displayAuthor );
this.messageBranchDisplay = booleanOptionOr( options.messageBranchDisplay, this.template.commit.message.displayBranch );
this.messageHashDisplay = booleanOptionOr( options.messageHashDisplay, this.template.commit.message.displayHash );
this.messageColor = options.messageColor || options.color;
this.messageFont = options.messageFont || this.template.commit.message.font;
this.dotColor = options.dotColor || options.color;
this.dotSize = options.dotSize || this.template.commit.dot.size;
this.dotStrokeWidth = options.dotStrokeWidth || this.template.commit.dot.strokeWidth;
this.dotStrokeColor = options.dotStrokeColor || this.template.commit.dot.strokeColor || options.color;
this.type = options.type || null;
this.onClick = options.onClick || null;
this.representedObject = options.representedObject || null;
this.parentCommit = options.parentCommit;
this.x = options.x;
this.y = options.y;
this.showLabel = options.showLabel;
this.labelColor = options.labelColor || options.color;
this.labelFont = options.labelFont || this.template.branch.labelFont;
this.parent.commits.push( this );
}
/**
* Render the commit
*
* @this Commit
**/
Commit.prototype.render = function () {
// Label
if ( this.showLabel ) {
drawTextBG( this.context, this.x + this.template.commit.spacingX, this.y + this.template.commit.spacingY, this.branch.name, "black", this.labelColor, this.labelFont, this.template.branch.labelRotation );
}
// Dot
this.context.beginPath();
this.context.arc( this.x, this.y, this.dotSize, 0, 2 * Math.PI, false );
this.context.fillStyle = this.dotColor;
this.context.strokeStyle = this.dotStrokeColor;
this.context.lineWidth = this.dotStrokeWidth;
if ( typeof (this.dotStrokeWidth) === "number" ) {
this.context.stroke();
}
this.context.fill();
this.context.closePath();
// Arrow
if ( this.arrowDisplay && this.parentCommit instanceof Commit ) {
this.arrow();
}
this.context.font = this.messageFont;
// Tag
var tagWidth = this.template.commit.tag.spacingX;
if ( this.tag !== null ) {
this.parent.tagNum++;
var textWidth = this.context.measureText( this.tag ).width;
if ( this.template.branch.labelRotation !== 0 ) {
var textHeight = getFontHeight( this.tagFont );
drawTextBG( this.context,
this.x - this.dotSize / 2,
((this.parent.columnMax + 1) * this.template.commit.tag.spacingY) - this.template.commit.tag.spacingY / 2 + (this.parent.tagNum % 2) * textHeight * 1.5,
this.tag, "black", this.tagColor, this.tagFont, 0 );
} else {
drawTextBG( this.context,
((this.parent.columnMax + 1) * this.template.commit.tag.spacingX) - this.template.commit.tag.spacingX / 2 + textWidth / 2,
this.y - this.dotSize / 2,
this.tag, "black", this.tagColor, this.tagFont, 0 );
}
tagWidth = (tagWidth < textWidth) ? textWidth : tagWidth;
}
var commitOffsetLeft = (this.parent.columnMax + 1) * this.template.branch.spacingX + tagWidth;
// Detail
if ( this.detail !== null ) {
this.detail.style.left = this.parent.canvas.offsetLeft + commitOffsetLeft + this.x + 30 + "px";
this.detail.style.top = this.parent.canvas.offsetTop + this.y + 40 + "px";
this.detail.width = 30;
}
// Message
if ( this.messageDisplay ) {
var message = this.message;
if ( this.messageHashDisplay ) {
message = this.sha1 + " " + message;
}
if ( this.messageAuthorDisplay ) {
message = message + (this.author ? " - " + this.author : "");
}
if ( this.messageBranchDisplay ) {
message = (this.branch.name ? "[" + this.branch.name + "] " : "") + message;
}
this.context.fillStyle = this.messageColor;
this.context.fillText( message, commitOffsetLeft, this.y + this.dotSize / 2 );
}
};
/**
* Render a arrow before commit
*
* @this Commit
**/
Commit.prototype.arrow = function Arrow () {
// Options
var size = this.template.arrow.size;
var color = this.template.arrow.color || this.branch.color;
// Angles calculation
var alpha = Math.atan2(
this.parentCommit.y - this.y,
this.parentCommit.x - this.x
);
// Merge & Fork case
if ( this.type === "mergeCommit" || this === this.branch.commits[ 0 ] /* First commit */ ) {
alpha = Math.atan2(
this.template.branch.spacingY * (this.parentCommit.branch.column - this.branch.column) + this.template.commit.spacingY * (this.showLabel ? 2 : 1),
this.template.branch.spacingX * (this.parentCommit.branch.column - this.branch.column) + this.template.commit.spacingX * (this.showLabel ? 2 : 1)
);
color = this.parentCommit.branch.color;
}
var delta = Math.PI / 7; // Delta between left & right (radian)
// Top
var h = this.template.commit.dot.size + this.template.arrow.offset;
var x1 = h * Math.cos( alpha ) + this.x;
var y1 = h * Math.sin( alpha ) + this.y;
// Bottom left
var x2 = (h + size) * Math.cos( alpha - delta ) + this.x;
var y2 = (h + size) * Math.sin( alpha - delta ) + this.y;
// Bottom center
var x3 = (h + size / 2) * Math.cos( alpha ) + this.x;
var y3 = (h + size / 2) * Math.sin( alpha ) + this.y;
// Bottom right
var x4 = (h + size) * Math.cos( alpha + delta ) + this.x;
var y4 = (h + size) * Math.sin( alpha + delta ) + this.y;
this.context.beginPath();
this.context.fillStyle = color;
this.context.moveTo( x1, y1 ); // Top
this.context.lineTo( x2, y2 ); // Bottom left
this.context.quadraticCurveTo( x3, y3, x4, y4 ); // Bottom center
this.context.lineTo( x4, y4 ); // Bottom right
this.context.fill();
};
// --------------------------------------------------------------------
// ----------------------- Template ------------------------
// --------------------------------------------------------------------
/**
* Template
*
* @constructor
*
* @param {Object} options - Template options
* @param {Array} [options.colors] - Colors scheme: One color for each column
* @param {String} [options.arrow.color] - Arrow color
* @param {Number} [options.arrow.size] - Arrow size
* @param {Number} [options.arrow.offser] - Arrow offset
* @param {String} [options.branch.color] - Branch color
* @param {Number} [options.branch.linewidth] - Branch line width
* @param {String} [options.branch.mergeStyle = ("bezier"|"straight")] - Branch merge style
* @param {Number} [options.branch.spacingX] - Space between branches
* @param {Number} [options.branch.spacingY] - Space between branches
* @param {Number} [options.commit.spacingX] - Space between commits
* @param {Number} [options.commit.spacingY] - Space between commits
* @param {Number} [options.commit.widthExtension = 0] - Additional width to be added to the calculated width
* @param {String} [options.commit.color] - Master commit color (dot & message)
* @param {String} [options.commit.dot.color] - Commit dot color
* @param {Number} [options.commit.dot.size] - Commit dot size
* @param {Number} [options.commit.dot.strokewidth] - Commit dot stroke width
* @param {Number} [options.commit.dot.strokeColor] - Commit dot stroke color
* @param {String} [options.commit.message.color] - Commit message color
* @param {Boolean} [options.commit.message.display] - Commit display policy
* @param {Boolean} [options.commit.message.displayAuthor] - Commit message author policy
* @param {Boolean} [options.commit.message.displayBranch] - Commit message branch policy
* @param {Boolean} [options.commit.message.displayHash] - Commit message hash policy
* @param {String} [options.commit.message.font = "normal 12pt Calibri"] - Commit message font
* @param {commitCallback} [options.commit.tooltipHTMLFormatter] - Formatter for the tooltip contents.
*
* @this Template
**/
function Template ( options ) {
// Options
options = (typeof options === "object") ? options : {};
options.branch = options.branch || {};
options.arrow = options.arrow || {};
options.commit = options.commit || {};
options.commit.dot = options.commit.dot || {};
options.commit.tag = options.commit.tag || {};
options.commit.message = options.commit.message || {};
// One color per column
this.colors = options.colors || [ "#6963FF", "#47E8D4", "#6BDB52", "#E84BA5", "#FFA657" ];
// Branch style
this.branch = {};
this.branch.color = options.branch.color || null; // Only one color
this.branch.lineWidth = options.branch.lineWidth || 2;
this.branch.lineDash = options.branch.lineDash || [];
this.branch.showLabel = options.branch.showLabel || false;
this.branch.labelColor = options.branch.labelColor || null;
this.branch.labelFont = options.branch.labelFont || "normal 8pt Calibri";
this.branch.labelRotation = options.branch.labelRotation || 0;
// Merge style = "bezier" | "straight"
this.branch.mergeStyle = options.branch.mergeStyle || "bezier";
// Space between branches
this.branch.spacingX = (typeof options.branch.spacingX === "number") ? options.branch.spacingX : 20;
this.branch.spacingY = options.branch.spacingY || 0;
// Arrow style
this.arrow = {};
this.arrow.size = options.arrow.size || null;
this.arrow.color = options.arrow.color || null;
this.arrow.active = typeof (this.arrow.size) === "number";
this.arrow.offset = options.arrow.offset || 2;
// Commit style
this.commit = {};
this.commit.spacingX = options.commit.spacingX || 0;
this.commit.spacingY = (typeof options.commit.spacingY === "number") ? options.commit.spacingY : 25;
this.commit.widthExtension = (typeof options.commit.widthExtension === "number") ? options.commit.widthExtension : 0;
this.commit.tooltipHTMLFormatter = options.commit.tooltipHTMLFormatter || null;
// Only one color, if null message takes branch color (full commit)
this.commit.color = options.commit.color || null;
this.commit.dot = {};
// Only one color, if null message takes branch color (only dot)
this.commit.dot.color = options.commit.dot.color || null;
this.commit.dot.size = options.commit.dot.size || 3;
this.commit.dot.strokeWidth = options.commit.dot.strokeWidth || null;
this.commit.dot.strokeColor = options.commit.dot.strokeColor || null;
this.commit.tag = {};
this.commit.tag.color = options.commit.tag.color || this.commit.dot.color;
this.commit.tag.font = options.commit.tag.font || options.commit.message.font || "normal 10pt Calibri";
this.commit.tag.spacingX = this.branch.spacingX;
this.commit.tag.spacingY = this.commit.spacingY;
this.commit.message = {};
this.commit.message.display = booleanOptionOr( options.commit.message.display, true );
this.commit.message.displayAuthor = booleanOptionOr( options.commit.message.displayAuthor, true );
this.commit.message.displayBranch = booleanOptionOr( options.commit.message.displayBranch, true );
this.commit.message.displayHash = booleanOptionOr( options.commit.message.displayHash, true );
// Only one color, if null message takes commit color (only message)
this.commit.message.color = options.commit.message.color || null;
this.commit.message.font = options.commit.message.font || "normal 12pt Calibri";
}
/**
* Get a default template from library
*
* @param {String} name - Template name
*
* @return {Template} [template] - Template if exist
**/
Template.prototype.get = function ( name ) {
var template = {};
switch ( name ) {
case "blackarrow":
template = {
branch: {
color: "#000000",
lineWidth: 4,
spacingX: 50,
mergeStyle: "straight"
},
commit: {
spacingY: -60,
dot: {
size: 12,
strokeColor: "#000000",
strokeWidth: 7
},
message: {
color: "black"
}
},
arrow: {
size: 16,
offset: 2.5
}
};
break;
case "metro":
/* falls through */
default:
template = {
colors: [ "#979797", "#008fb5", "#f1c109" ],
branch: {
lineWidth: 10,
spacingX: 50
},
commit: {
spacingY: -80,
dot: {
size: 14
},
message: {
font: "normal 14pt Arial"
}
}
};
break;
}
return new Template( template );
};
// --------------------------------------------------------------------
// ----------------------- Utilities -----------------------
// --------------------------------------------------------------------
var getFontHeight = function ( font ) {
var body = document.getElementsByTagName( "body" )[ 0 ];
var dummy = document.createElement( "div" );
var dummyText = document.createTextNode( "Mg" );
dummy.appendChild( dummyText );
dummy.setAttribute( "style", "font: " + font + ";" );
body.appendChild( dummy );
var result = dummy.offsetHeight;
body.removeChild( dummy );
return result;
};
function booleanOptionOr ( booleanOption, defaultOption ) {
return (typeof booleanOption === "boolean") ? booleanOption : defaultOption;
}
function drawTextBG ( context, x, y, text, fgcolor, bgcolor, font, angle ) {
context.save();
context.translate( x, y );
context.rotate( angle * (Math.PI / 180) );
context.textAlign = "center";
context.font = font;
var width = context.measureText( text ).width;
var height = getFontHeight( font );
context.beginPath();
context.rect( -(width / 2) - 4, -(height / 2) + 2, width + 8, height + 2 );
context.fillStyle = bgcolor;
context.fill();
context.lineWidth = 2;
context.strokeStyle = "black";
context.stroke();
context.fillStyle = fgcolor;
context.fillText( text, 0, height / 2 );
context.restore();
}
// Expose GitGraph object
window.GitGraph = GitGraph;
window.GitGraph.Branch = Branch;
window.GitGraph.Commit = Commit;
window.GitGraph.Template = Template;
})();
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReduxForm"] = factory(require("react"));
else
root["ReduxForm"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_12__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(12);
var _react2 = _interopRequireDefault(_react);
var _reactRedux = __webpack_require__(29);
var _createAll2 = __webpack_require__(13);
var _createAll3 = _interopRequireDefault(_createAll2);
var _createAll = _createAll3['default'](false, _react2['default'], _reactRedux.connect);
var blur = _createAll.blur;
var change = _createAll.change;
var connectReduxForm = _createAll.connectReduxForm;
var destroy = _createAll.destroy;
var focus = _createAll.focus;
var reducer = _createAll.reducer;
var reduxForm = _createAll.reduxForm;
var initialize = _createAll.initialize;
var initializeWithKey = _createAll.initializeWithKey;
var reset = _createAll.reset;
var startAsyncValidation = _createAll.startAsyncValidation;
var startSubmit = _createAll.startSubmit;
var stopAsyncValidation = _createAll.stopAsyncValidation;
var stopSubmit = _createAll.stopSubmit;
var touch = _createAll.touch;
var untouch = _createAll.untouch;
exports.blur = blur;
exports.change = change;
exports.connectReduxForm = connectReduxForm;
exports.destroy = destroy;
exports.focus = focus;
exports.reducer = reducer;
exports.reduxForm = reduxForm;
exports.initialize = initialize;
exports.initializeWithKey = initializeWithKey;
exports.reset = reset;
exports.startAsyncValidation = startAsyncValidation;
exports.startSubmit = startSubmit;
exports.stopAsyncValidation = stopAsyncValidation;
exports.stopSubmit = stopSubmit;
exports.touch = touch;
exports.untouch = untouch;
/***/ },
/* 1 */
/***/ function(module, exports) {
/**
* Maps all the values in the given object through the given function and saves them, by key, to a result object
*/
"use strict";
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports["default"] = mapValues;
function mapValues(obj, fn) {
return Object.keys(obj).reduce(function (accumulator, key) {
var _extends2;
return _extends({}, accumulator, (_extends2 = {}, _extends2[key] = fn(obj[key], key), _extends2));
}, {});
}
module.exports = exports["default"];
/***/ },
/* 2 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var BLUR = 'redux-form/BLUR';
exports.BLUR = BLUR;
var CHANGE = 'redux-form/CHANGE';
exports.CHANGE = CHANGE;
var DESTROY = 'redux-form/DESTROY';
exports.DESTROY = DESTROY;
var FOCUS = 'redux-form/FOCUS';
exports.FOCUS = FOCUS;
var INITIALIZE = 'redux-form/INITIALIZE';
exports.INITIALIZE = INITIALIZE;
var RESET = 'redux-form/RESET';
exports.RESET = RESET;
var START_ASYNC_VALIDATION = 'redux-form/START_ASYNC_VALIDATION';
exports.START_ASYNC_VALIDATION = START_ASYNC_VALIDATION;
var START_SUBMIT = 'redux-form/START_SUBMIT';
exports.START_SUBMIT = START_SUBMIT;
var STOP_ASYNC_VALIDATION = 'redux-form/STOP_ASYNC_VALIDATION';
exports.STOP_ASYNC_VALIDATION = STOP_ASYNC_VALIDATION;
var STOP_SUBMIT = 'redux-form/STOP_SUBMIT';
exports.STOP_SUBMIT = STOP_SUBMIT;
var TOUCH = 'redux-form/TOUCH';
exports.TOUCH = TOUCH;
var UNTOUCH = 'redux-form/UNTOUCH';
exports.UNTOUCH = UNTOUCH;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.blur = blur;
exports.change = change;
exports.destroy = destroy;
exports.focus = focus;
exports.initialize = initialize;
exports.reset = reset;
exports.startAsyncValidation = startAsyncValidation;
exports.startSubmit = startSubmit;
exports.stopAsyncValidation = stopAsyncValidation;
exports.stopSubmit = stopSubmit;
exports.touch = touch;
exports.untouch = untouch;
var _actionTypes = __webpack_require__(2);
function blur(field, value) {
return { type: _actionTypes.BLUR, field: field, value: value };
}
function change(field, value) {
return { type: _actionTypes.CHANGE, field: field, value: value };
}
function destroy() {
return { type: _actionTypes.DESTROY };
}
function focus(field) {
return { type: _actionTypes.FOCUS, field: field };
}
function initialize(data) {
return { type: _actionTypes.INITIALIZE, data: data };
}
function reset() {
return { type: _actionTypes.RESET };
}
function startAsyncValidation() {
return { type: _actionTypes.START_ASYNC_VALIDATION };
}
function startSubmit() {
return { type: _actionTypes.START_SUBMIT };
}
function stopAsyncValidation(errors) {
return { type: _actionTypes.STOP_ASYNC_VALIDATION, errors: errors };
}
function stopSubmit(errors) {
return { type: _actionTypes.STOP_SUBMIT, errors: errors };
}
function touch() {
for (var _len = arguments.length, fields = Array(_len), _key = 0; _key < _len; _key++) {
fields[_key] = arguments[_key];
}
return { type: _actionTypes.TOUCH, fields: fields };
}
function untouch() {
for (var _len2 = arguments.length, fields = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
fields[_key2] = arguments[_key2];
}
return { type: _actionTypes.UNTOUCH, fields: fields };
}
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = bindActionData;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _mapValues = __webpack_require__(1);
var _mapValues2 = _interopRequireDefault(_mapValues);
/**
* Adds additional properties to the results of the function or map of functions passed
*/
function bindActionData(action, data) {
if (typeof action === 'function') {
return function () {
return _extends({}, action.apply(undefined, arguments), data);
};
}
if (typeof action === 'object') {
return _mapValues2['default'](action, function (value) {
return bindActionData(value, data);
});
}
return action;
}
module.exports = exports['default'];
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _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'] = createReduxForm;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _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 _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 _actions = __webpack_require__(3);
var formActions = _interopRequireWildcard(_actions);
var _getDisplayName = __webpack_require__(15);
var _getDisplayName2 = _interopRequireDefault(_getDisplayName);
var _isPristine = __webpack_require__(16);
var _isPristine2 = _interopRequireDefault(_isPristine);
var _isValid = __webpack_require__(17);
var _isValid2 = _interopRequireDefault(_isValid);
var _bindActionData = __webpack_require__(4);
var _bindActionData2 = _interopRequireDefault(_bindActionData);
var _reducer = __webpack_require__(6);
var _reactLazyCache = __webpack_require__(24);
var _reactLazyCache2 = _interopRequireDefault(_reactLazyCache);
function isReadonly(prop) {
var writeProps = ['asyncValidate', 'handleBlur', 'handleChange', 'handleFocus', 'handleSubmit', 'onBlur', 'onChange', 'onFocus'];
return ! ~writeProps.indexOf(prop);
}
function silenceEvents(fn) {
return function (event) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (event && event.preventDefault) {
event.preventDefault();
event.stopPropagation();
return fn.apply(undefined, args);
}
return fn.apply(undefined, [event].concat(args));
};
}
function isAsyncValid(errors) {
return !errors || Object.keys(errors).reduce(function (valid, error) {
return valid && _isValid2['default'](errors[error]);
}, true);
}
function createReduxForm(isReactNative, React) {
var Component = React.Component;
var PropTypes = React.PropTypes;
function getValue(passedValue, event) {
if (passedValue !== undefined || !event) {
// extract value from { value: value } structure. https://github.com/nikgraf/belle/issues/58
return typeof passedValue === 'object' && passedValue.value ? passedValue.value : passedValue;
}
if (!isReactNative && event.nativeEvent !== undefined && event.nativeEvent.text !== undefined) {
return event.nativeEvent.text;
}
if (isReactNative && event.nativeEvent !== undefined) {
return event.nativeEvent.text;
}
if (event.target === undefined) {
// is it a value instead of an event?
return event;
}
var _event$target = event.target;
var type = _event$target.type;
var value = _event$target.value;
var checked = _event$target.checked;
var files = _event$target.files;
var dataTransfer = event.dataTransfer;
if (type === 'checkbox') {
return checked;
}
if (type === 'file') {
return files || dataTransfer && dataTransfer.files;
}
return value;
}
return function reduxForm(config) {
var _extends7 = _extends({
validate: function validate() {
return {};
},
touchOnBlur: true,
touchOnChange: false,
readonly: false,
asyncValidate: null,
asyncBlurFields: []
}, config);
var formName = _extends7.form;
var fields = _extends7.fields;
var syncValidate = _extends7.validate;
var readonly = _extends7.readonly;
var touchOnBlur = _extends7.touchOnBlur;
var touchOnChange = _extends7.touchOnChange;
var asyncValidate = _extends7.asyncValidate;
var asyncBlurFields = _extends7.asyncBlurFields;
if (!fields || !fields.length) {
throw new Error('No fields passed to redux-form. Must be passed to ' + 'connectReduxForm({fields: ["my", "field", "names"]})');
}
var filterProps = function filterProps(props) {
return readonly ? Object.keys(props).reduce(function (accumulator, prop) {
var _extends2;
return isReadonly(prop) ? _extends({}, accumulator, (_extends2 = {}, _extends2[prop] = props[prop], _extends2)) : accumulator;
}, {}) : props;
};
return function (DecoratedComponent) {
return (function (_Component) {
_inherits(ReduxForm, _Component);
_createClass(ReduxForm, null, [{
key: 'displayName',
value: 'ReduxForm(' + _getDisplayName2['default'](DecoratedComponent) + ')',
enumerable: true
}, {
key: 'DecoratedComponent',
value: DecoratedComponent,
enumerable: true
}, {
key: 'propTypes',
value: {
formName: PropTypes.string,
formKey: PropTypes.string,
form: PropTypes.object,
onSubmit: PropTypes.func,
dispatch: PropTypes.func.isRequired,
initialValues: PropTypes.object
},
enumerable: true
}, {
key: 'defaultProps',
value: {
formName: formName
},
enumerable: true
}]);
function ReduxForm(props) {
var _this = this;
_classCallCheck(this, ReduxForm);
_Component.call(this, props);
this.cache = _reactLazyCache2['default'](this, {
_actions: {
params: ['formName', 'formKey'],
fn: function fn(formName, formKey) {
return (// eslint-disable-line no-shadow
formKey ? _bindActionData2['default'](formActions, { form: formName, key: formKey }) : _bindActionData2['default'](formActions, { form: formName })
);
}
},
_handleBlur: {
params: ['_actions', 'dispatch'],
fn: function fn(actions, dispatch) {
return function (name, value) {
return function (event) {
var fieldValue = getValue(value, event);
var doBlur = _bindActionData2['default'](actions.blur, { touch: touchOnBlur });
dispatch(doBlur(name, fieldValue));
if (asyncValidate && ~asyncBlurFields.indexOf(name)) {
var _extends3;
var values = _this.getValues();
var syncError = _this.runSyncValidation(_extends({}, values, (_extends3 = {}, _extends3[name] = fieldValue, _extends3)))[name];
// only dispatch async call if all synchronous client-side validation passes for this field
if (!syncError) {
_this.runAsyncValidation(actions, values);
}
}
};
};
}
},
_handleFocus: {
params: ['_actions', 'dispatch'],
fn: function fn(actions, dispatch) {
return function (name) {
return function () {
return dispatch(actions.focus(name));
};
};
}
},
_handleChange: {
params: ['_actions', 'dispatch'],
fn: function fn(actions, dispatch) {
return function (name, value) {
var doChange = _bindActionData2['default'](actions.change, { touch: touchOnChange });
return value ? dispatch(doChange(name, getValue(value))) : function (event) {
return dispatch(doChange(name, getValue(value, event)));
};
};
}
},
_fieldActions: {
params: ['_handleBlur', '_handleChange', '_handleFocus'],
fn: function fn(handleBlur, handleChange, handleFocus) {
return fields.reduce(function (accumulator, name) {
var _extends4;
var fieldBlur = handleBlur(name);
var fieldChange = handleChange(name);
var fieldFocus = handleFocus(name);
return _extends({}, accumulator, (_extends4 = {}, _extends4[name] = filterProps({
handleBlur: fieldBlur,
handleChange: fieldChange,
handleFocus: fieldFocus,
name: name,
onBlur: fieldBlur,
onChange: fieldChange,
onDrop: function onDrop(event) {
fieldChange(event.dataTransfer.getData('value'));
},
onFocus: fieldFocus,
onUpdate: fieldChange // alias to support belle. https://github.com/nikgraf/belle/issues/58
}), _extends4));
}, {});
}
}
});
}
ReduxForm.prototype.componentWillMount = function componentWillMount() {
var _props = this.props;
var initialValues = _props.initialValues;
var dispatch = _props.dispatch;
// eslint-disable-line no-shadow
if (initialValues) {
var initialize = this.cache._actions.initialize;
dispatch(initialize(initialValues));
}
};
ReduxForm.prototype.runSyncValidation = function runSyncValidation(values) {
return syncValidate(values, this.props);
};
ReduxForm.prototype.runAsyncValidation = function runAsyncValidation(actions, values) {
var _props2 = this.props;
var dispatch = _props2.dispatch;
var formKey = _props2.formKey;
// eslint-disable-line no-shadow
dispatch(actions.startAsyncValidation(formKey));
var promise = asyncValidate(values, dispatch);
if (!promise || typeof promise.then !== 'function') {
throw new Error('asyncValidate function passed to reduxForm must return a promise!');
}
var handleErrors = function handleErrors(asyncErrors) {
dispatch(actions.stopAsyncValidation(asyncErrors));
return isAsyncValid(asyncErrors);
};
return promise.then(handleErrors, handleErrors);
};
ReduxForm.prototype.getSubForm = function getSubForm() {
var _props3 = this.props;
var formName = _props3.formName;
var form = _props3.form;
var formKey = _props3.formKey;
// eslint-disable-line no-shadow
if (form && form[formName]) {
if (formKey) {
if (form[formName][formKey]) {
return form[formName][formKey];
}
} else {
return form[formName];
}
}
return _reducer.initialState;
};
ReduxForm.prototype.getValues = function getValues() {
var subForm = this.getSubForm();
return fields.reduce(function (accumulator, field) {
var _extends5;
return _extends({}, accumulator, (_extends5 = {}, _extends5[field] = subForm[field] ? subForm[field].value : undefined, _extends5));
}, {});
};
ReduxForm.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
this.cache.componentWillReceiveProps(nextProps);
};
ReduxForm.prototype.render = function render() {
var _this2 = this;
// Read props
var _props4 = this.props;
var formName = _props4.formName;
var form = _props4.form;
var formKey = _props4.formKey;
var dispatch = _props4.dispatch;
var passableProps = _objectWithoutProperties(_props4, ['formName', 'form', 'formKey', 'dispatch']);
// eslint-disable-line no-shadow
if (!formName) {
throw new Error('No form name given to redux-form. Must be passed to ' + 'connectReduxForm({form: [form name]}) or as a "formName" prop');
}
var _cache = this.cache;
var actions = _cache._actions;
var fieldActions = _cache._fieldActions;
var handleBlur = _cache._handleBlur;
var handleChange = _cache._handleChange;
var handleFocus = _cache._handleFocus;
var subForm = this.getSubForm();
// Calculate calculable state
var allValid = true;
var allPristine = true;
var handleSubmit = function handleSubmit(submitOrEvent) {
var createEventHandler = function createEventHandler(submit) {
return function (event) {
if (event && event.preventDefault) {
event.preventDefault();
event.stopPropagation();
}
var values = _this2.getValues();
var submitWithPromiseCheck = function submitWithPromiseCheck() {
var result = submit(values);
if (result && typeof result.then === 'function') {
// you're showing real promise, kid!
dispatch(actions.startSubmit());
return result.then(function (submitResult) {
dispatch(actions.stopSubmit());
return submitResult;
}, function (submitError) {
dispatch(actions.stopSubmit(submitError));
return submitError;
});
}
};
dispatch(actions.touch.apply(actions, fields));
if (allValid) {
if (asyncValidate) {
return _this2.runAsyncValidation(actions, values).then(function (asyncValid) {
if (allValid && asyncValid) {
return submitWithPromiseCheck(values);
}
});
}
return submitWithPromiseCheck(values);
}
};
};
if (typeof submitOrEvent === 'function') {
return createEventHandler(submitOrEvent);
}
var onSubmit = _this2.props.onSubmit;
if (!onSubmit) {
throw new Error('You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop');
}
createEventHandler(onSubmit)(submitOrEvent /* is event */);
};
// Define fields
var values = this.getValues();
var syncErrors = this.runSyncValidation(values);
var allFields = fields.reduce(function (accumulator, name) {
var _extends6;
var field = subForm[name] || {};
var pristine = _isPristine2['default'](field.value, field.initial);
var error = syncErrors[name] || field.asyncError || field.submitError;
var valid = _isValid2['default'](error);
var initialValue = passableProps.initialValues && passableProps.initialValues[name];
if (!valid) {
allValid = false;
}
if (!pristine) {
allPristine = false;
}
return _extends({}, accumulator, (_extends6 = {}, _extends6[name] = filterProps(_extends({
active: subForm._active === name,
checked: typeof field.value === 'boolean' ? field.value : undefined,
defaultChecked: initialValue,
defaultValue: initialValue,
dirty: !pristine,
error: error
}, fieldActions[name], {
invalid: !valid,
name: name,
onDrag: function onDrag(event) {
return event.dataTransfer.setData('value', field.value);
},
pristine: pristine,
touched: field.touched,
valid: valid,
value: field.value,
visited: field.visited
})), _extends6));
}, {});
var formError = syncErrors._error || subForm._error;
if (formError) {
allValid = false;
}
// Return decorated component
return React.createElement(DecoratedComponent, _extends({
// State:
active: subForm._active,
asyncValidating: subForm._asyncValidating,
dirty: !allPristine,
error: formError,
fields: allFields,
formKey: formKey,
invalid: !allValid,
pristine: allPristine,
submitting: subForm._submitting,
valid: allValid,
values: values,
// Actions:
asyncValidate: silenceEvents(function () {
return _this2.runAsyncValidation(actions, values);
}),
destroyForm: silenceEvents(function () {
return dispatch(actions.destroy());
}),
handleBlur: silenceEvents(handleBlur),
handleChange: silenceEvents(handleChange),
handleFocus: handleFocus,
handleSubmit: silenceEvents(handleSubmit),
initializeForm: silenceEvents(function (initialValues) {
return dispatch(actions.initialize(initialValues));
}),
resetForm: silenceEvents(function () {
return dispatch(actions.reset());
}),
touch: silenceEvents(function () {
return dispatch(actions.touch.apply(actions, arguments));
}),
touchAll: silenceEvents(function () {
return dispatch(actions.touch.apply(actions, fields));
}),
untouch: silenceEvents(function () {
return dispatch(actions.untouch.apply(actions, arguments));
}),
untouchAll: silenceEvents(function () {
return dispatch(actions.untouch.apply(actions, fields));
}),
// Other:
dispatch: dispatch
}, passableProps));
};
return ReduxForm;
})(Component);
};
};
}
module.exports = exports['default'];
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var _actionTypes = __webpack_require__(2);
var _mapValues = __webpack_require__(1);
var _mapValues2 = _interopRequireDefault(_mapValues);
var initialState = {
_active: undefined,
_asyncValidating: false,
_error: undefined,
_submitting: false
};
exports.initialState = initialState;
var getValues = function getValues(state) {
return Object.keys(state).reduce(function (accumulator, name) {
var _extends2;
return name[0] === '_' ? accumulator : _extends({}, accumulator, (_extends2 = {}, _extends2[name] = state[name].value, _extends2));
}, {});
};
var reducer = function reducer() {
var state = arguments.length <= 0 || arguments[0] === undefined ? initialState : arguments[0];
var _extends3, _extends4, _extends5;
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
switch (action.type) {
case _actionTypes.BLUR:
return _extends({}, state, (_extends3 = {}, _extends3[action.field] = _extends({}, state[action.field], {
value: action.value === undefined ? (state[action.field] || {}).value : action.value,
touched: !!(action.touch || (state[action.field] || {}).touched)
}), _extends3._active = undefined, _extends3));
case _actionTypes.CHANGE:
return _extends({}, state, (_extends4 = {}, _extends4[action.field] = _extends({}, state[action.field], {
value: action.value,
touched: !!(action.touch || (state[action.field] || {}).touched),
asyncError: null,
submitError: null
}), _extends4._error = undefined, _extends4));
case _actionTypes.DESTROY:
return undefined;
case _actionTypes.FOCUS:
return _extends({}, state, (_extends5 = {}, _extends5[action.field] = _extends({}, state[action.field], {
visited: true
}), _extends5._active = action.field, _extends5));
case _actionTypes.INITIALIZE:
return _extends({}, _mapValues2['default'](action.data, function (value) {
return {
initial: value,
value: value
};
}), {
_asyncValidating: false,
_active: undefined,
_error: undefined,
_submitting: false
});
case _actionTypes.RESET:
return _extends({}, _mapValues2['default'](state, function (field, name) {
return name[0] === '_' ? field : {
initial: field.initial,
value: field.initial
};
}), {
_active: undefined,
_asyncValidating: false,
_error: undefined,
_submitting: false
});
case _actionTypes.START_ASYNC_VALIDATION:
return _extends({}, state, {
_asyncValidating: true
});
case _actionTypes.START_SUBMIT:
return _extends({}, state, {
_submitting: true
});
case _actionTypes.STOP_ASYNC_VALIDATION:
return _extends({}, state, _mapValues2['default'](action.errors, function (error, key) {
return _extends({}, state[key], {
asyncError: error
});
}), {
_asyncValidating: false,
_error: action.errors._error
});
case _actionTypes.STOP_SUBMIT:
return _extends({}, state, action.errors ? _mapValues2['default'](action.errors, function (error, key) {
return _extends({}, state[key], {
submitError: error
});
}) : {}, {
_error: action.errors && action.errors._error,
_submitting: false
});
case _actionTypes.TOUCH:
return _extends({}, state, action.fields.reduce(function (accumulator, field) {
var _extends6;
return _extends({}, accumulator, (_extends6 = {}, _extends6[field] = _extends({}, state[field], {
touched: true
}), _extends6));
}, {}));
case _actionTypes.UNTOUCH:
return _extends({}, state, action.fields.reduce(function (accumulator, field) {
var _extends7;
return _extends({}, accumulator, (_extends7 = {}, _extends7[field] = _extends({}, state[field], {
touched: false
}), _extends7));
}, {}));
default:
return state;
}
};
function formReducer() {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _extends13;
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var form = action.form;
var key = action.key;
var rest = _objectWithoutProperties(action, ['form', 'key']);
if (!form) {
return state;
}
if (key) {
var _extends10, _extends11;
if (action.type === _actionTypes.DESTROY) {
var _extends9;
return _extends({}, state, (_extends9 = {}, _extends9[form] = Object.keys(state[form]).reduce(function (accumulator, stateKey) {
var _extends8;
return stateKey === key ? accumulator : _extends({}, accumulator, (_extends8 = {}, _extends8[stateKey] = state[form][stateKey], _extends8));
}, {}), _extends9));
}
return _extends({}, state, (_extends11 = {}, _extends11[form] = _extends({}, state[form], (_extends10 = {}, _extends10[key] = reducer((state[form] || {})[key], rest), _extends10)), _extends11));
}
if (action.type === _actionTypes.DESTROY) {
return Object.keys(state).reduce(function (accumulator, formName) {
var _extends12;
return formName === form ? accumulator : _extends({}, accumulator, (_extends12 = {}, _extends12[formName] = state[formName], _extends12));
}, {});
}
return _extends({}, state, (_extends13 = {}, _extends13[form] = reducer(state[form], rest), _extends13));
}
/**
* Adds additional functionality to the reducer
*/
function decorate(target) {
target.plugin = function plugin(reducers) {
var _this = this;
return decorate(function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var result = _this(state, action);
return _extends({}, result, _mapValues2['default'](reducers, function (red, key) {
return red(result[key] || initialState, action);
}));
});
};
target.normalize = function normalize(normalizers) {
var _this2 = this;
return decorate(function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var result = _this2(state, action);
return _extends({}, result, _mapValues2['default'](normalizers, function (formNormalizers, form) {
var formResult = _extends({}, initialState, result[form]);
return _extends({}, formResult, _mapValues2['default'](formNormalizers, function (fieldNormalizer, field) {
return _extends({}, formResult[field], {
value: fieldNormalizer(formResult[field] ? formResult[field].value : undefined, // value
state[form] && state[form][field] ? state[form][field].value : undefined, // previous value
getValues(formResult)) // all field values
});
}));
}));
});
};
return target;
}
exports['default'] = decorate(formReducer);
/***/ },
/* 7 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = createStoreShape;
function createStoreShape(PropTypes) {
return PropTypes.shape({
subscribe: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
getState: PropTypes.func.isRequired
});
}
module.exports = exports["default"];
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = createStore;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _utilsIsPlainObject = __webpack_require__(10);
var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject);
/**
* These are private action types reserved by Redux.
* For any unknown actions, you must return the current state.
* If the current state is undefined, you must return the initial state.
* Do not reference these action types directly in your code.
*/
var ActionTypes = {
INIT: '@@redux/INIT'
};
exports.ActionTypes = ActionTypes;
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [initialState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
function createStore(reducer, initialState) {
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.');
}
var currentReducer = reducer;
var currentState = initialState;
var listeners = [];
var isDispatching = false;
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
return currentState;
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
var index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will
* be considered the **next** state of the tree, and the change listeners
* will be notified.
*
* The base implementation only supports plain object actions. If you want to
* dispatch a Promise, an Observable, a thunk, or something else, you need to
* wrap your store creating function into the corresponding middleware. For
* example, see the documentation for the `redux-thunk` package. Even the
* middleware will eventually dispatch plain object actions using this method.
*
* @param {Object} action A plain object representing “what changed”. It is
* a good idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`. An action must have
* a `type` property which may not be `undefined`. It is a good idea to use
* string constants for action types.
*
* @returns {Object} For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
function dispatch(action) {
if (!_utilsIsPlainObject2['default'](action)) {
throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
}
if (typeof action.type === 'undefined') {
throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
}
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.');
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
listeners.slice().forEach(function (listener) {
return listener();
});
return action;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param {Function} nextReducer The reducer for the store to use instead.
* @returns {void}
*/
function replaceReducer(nextReducer) {
currentReducer = nextReducer;
dispatch({ type: ActionTypes.INIT });
}
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({ type: ActionTypes.INIT });
return {
dispatch: dispatch,
subscribe: subscribe,
getState: getState,
replaceReducer: replaceReducer
};
}
/***/ },
/* 9 */
/***/ function(module, exports) {
/**
* Composes single-argument functions from right to left.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing functions from right to
* left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))).
*/
"use strict";
exports.__esModule = true;
exports["default"] = compose;
function compose() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
return function (arg) {
return funcs.reduceRight(function (composed, f) {
return f(composed);
}, arg);
};
}
module.exports = exports["default"];
/***/ },
/* 10 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = isPlainObject;
var fnToString = function fnToString(fn) {
return Function.prototype.toString.call(fn);
};
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype;
if (proto === null) {
return true;
}
var constructor = proto.constructor;
return typeof constructor === 'function' && constructor instanceof constructor && fnToString(constructor) === fnToString(Object);
}
module.exports = exports['default'];
/***/ },
/* 11 */
/***/ function(module, exports) {
/**
* Applies a function to every key-value pair inside an object.
*
* @param {Object} obj The source object.
* @param {Function} fn The mapper function that receives the value and the key.
* @returns {Object} A new object that contains the mapped values for the keys.
*/
"use strict";
exports.__esModule = true;
exports["default"] = mapValues;
function mapValues(obj, fn) {
return Object.keys(obj).reduce(function (result, key) {
result[key] = fn(obj[key], key);
return result;
}, {});
}
module.exports = exports["default"];
/***/ },
/* 12 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_12__;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = createAll;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _reducer = __webpack_require__(6);
var _reducer2 = _interopRequireDefault(_reducer);
var _createReduxForm = __webpack_require__(5);
var _createReduxForm2 = _interopRequireDefault(_createReduxForm);
var _createConnectReduxForm = __webpack_require__(14);
var _createConnectReduxForm2 = _interopRequireDefault(_createConnectReduxForm);
var _mapValues = __webpack_require__(1);
var _mapValues2 = _interopRequireDefault(_mapValues);
var _bindActionData = __webpack_require__(4);
var _bindActionData2 = _interopRequireDefault(_bindActionData);
var _actions = __webpack_require__(3);
var actions = _interopRequireWildcard(_actions);
// bind form as first parameter of action creators
var boundActions = _extends({}, _mapValues2['default'](_extends({}, actions, {
initializeWithKey: function initializeWithKey(key, data) {
return _bindActionData2['default'](actions.initialize, { key: key })(data);
}
}), function (action) {
return function (form) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return _bindActionData2['default'](action, { form: form }).apply(undefined, args);
};
}));
var blur = boundActions.blur;
var change = boundActions.change;
var destroy = boundActions.destroy;
var focus = boundActions.focus;
var initialize = boundActions.initialize;
var initializeWithKey = boundActions.initializeWithKey;
var reset = boundActions.reset;
var startAsyncValidation = boundActions.startAsyncValidation;
var startSubmit = boundActions.startSubmit;
var stopAsyncValidation = boundActions.stopAsyncValidation;
var stopSubmit = boundActions.stopSubmit;
var touch = boundActions.touch;
var untouch = boundActions.untouch;
function createAll(isReactNative, React, connect) {
return {
blur: blur,
change: change,
connectReduxForm: _createConnectReduxForm2['default'](isReactNative, React, connect),
destroy: destroy,
focus: focus,
reducer: _reducer2['default'],
initialize: initialize,
initializeWithKey: initializeWithKey,
reduxForm: _createReduxForm2['default'](isReactNative, React),
reset: reset,
startAsyncValidation: startAsyncValidation,
startSubmit: startSubmit,
stopAsyncValidation: stopAsyncValidation,
stopSubmit: stopSubmit,
touch: touch,
untouch: untouch
};
}
module.exports = exports['default'];
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = createConnectReduxForm;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _createReduxForm = __webpack_require__(5);
var _createReduxForm2 = _interopRequireDefault(_createReduxForm);
function reduceDecorators() {
for (var _len = arguments.length, decorators = Array(_len), _key = 0; _key < _len; _key++) {
decorators[_key] = arguments[_key];
}
return function (DecoratedComponent) {
return decorators.reduce(function (accumulator, decorator) {
return decorator(accumulator);
}, DecoratedComponent);
};
}
function createConnectReduxForm(isReactNative, React, connect) {
var reduxForm = _createReduxForm2['default'](isReactNative, React);
var connector = connect(function (state) {
return {
form: state.form
};
});
return function connectReduxForm() {
return reduceDecorators(reduxForm.apply(undefined, arguments), connector);
};
}
module.exports = exports['default'];
/***/ },
/* 15 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = getDisplayName;
function getDisplayName(Comp) {
return Comp.displayName || Comp.name || 'Component';
}
module.exports = exports['default'];
/***/ },
/* 16 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = isPristine;
function isPristine(initial, data) {
if (initial === data) {
return true;
}
if (initial && typeof initial === 'object') {
if (!data || typeof data !== 'object') {
return false;
}
var dataKeys = Object.keys(data);
for (var index = 0; index < dataKeys.length; index++) {
var key = dataKeys[index];
if (!isPristine(initial[key], data[key])) {
return false;
}
}
} else if (initial || data) {
// allow '' to equate to undefined or null
return initial === data;
}
return true;
}
module.exports = exports['default'];
/***/ },
/* 17 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = isValid;
function isValid(error) {
if (Array.isArray(error)) {
return error.reduce(function (valid, errorValue) {
return valid && isValid(errorValue);
}, true);
}
return !error;
}
module.exports = exports["default"];
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
var pSlice = Array.prototype.slice;
var objectKeys = __webpack_require__(20);
var isArguments = __webpack_require__(19);
var deepEqual = module.exports = function (actual, expected, opts) {
if (!opts) opts = {};
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') {
return opts.strict ? actual === expected : actual == expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, opts);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer (x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') return false;
return true;
}
function objEquiv(a, b, opts) {
var i, key;
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return deepEqual(a, b, opts);
}
if (isBuffer(a)) {
if (!isBuffer(b)) {
return false;
}
if (a.length !== b.length) return false;
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
try {
var ka = objectKeys(a),
kb = objectKeys(b);
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) return false;
}
return typeof a === typeof b;
}
/***/ },
/* 19 */
/***/ function(module, exports) {
var supportsArgumentsClass = (function(){
return Object.prototype.toString.call(arguments)
})() == '[object Arguments]';
exports = module.exports = supportsArgumentsClass ? supported : unsupported;
exports.supported = supported;
function supported(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
};
exports.unsupported = unsupported;
function unsupported(object){
return object &&
typeof object == 'object' &&
typeof object.length == 'number' &&
Object.prototype.hasOwnProperty.call(object, 'callee') &&
!Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
false;
};
/***/ },
/* 20 */
/***/ function(module, exports) {
exports = module.exports = typeof Object.keys === 'function'
? Object.keys : shim;
exports.shim = shim;
function shim (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/***/ },
/* 21 */
/***/ function(module, exports) {
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
var REACT_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
arguments: true,
arity: true
};
module.exports = function hoistNonReactStatics(targetComponent, sourceComponent) {
var keys = Object.getOwnPropertyNames(sourceComponent);
for (var i=0; i<keys.length; ++i) {
if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]]) {
targetComponent[keys[i]] = sourceComponent[keys[i]];
}
}
return targetComponent;
};
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if (true) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
'Invariant Violation: ' +
format.replace(/%s/g, function() { return args[argIndex++]; })
);
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
/***/ },
/* 23 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = getParamNames;
var stripComments = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/mg;
var argNames = /([^\s,]+)/g;
function getParamNames(fn) {
var fnStr = fn.toString().replace(stripComments, '');
var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(argNames);
return result || [];
}
module.exports = exports['default'];
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _lazyCache = __webpack_require__(25);
var _lazyCache2 = _interopRequireDefault(_lazyCache);
exports['default'] = _lazyCache2['default'];
module.exports = exports['default'];
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = lazyCache;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _getParamNames = __webpack_require__(23);
var _getParamNames2 = _interopRequireDefault(_getParamNames);
var _deepEqual = __webpack_require__(18);
var _deepEqual2 = _interopRequireDefault(_deepEqual);
function lazyCache(component, calculators) {
var allProps = [];
var cache = {};
var api = {};
var uncache = function uncache(changedProp) {
Object.keys(cache).forEach(function (key) {
if (~cache[key].props.indexOf(changedProp)) {
delete cache[key].value;
uncache(key);
}
});
};
Object.keys(calculators).forEach(function (key) {
var calculate = calculators[key];
var props = _getParamNames2['default'](calculate);
props.forEach(function (param) {
if (! ~allProps.indexOf(param)) {
allProps.push(param);
}
});
cache[key] = { props: props };
Object.defineProperty(api, key, {
get: function get() {
var cached = cache[key];
if (cached && cached.value !== undefined) {
return cached.value;
}
var params = props.map(function (prop) {
return component.props[prop] || api[prop];
});
var value = calculate.apply(undefined, params);
cache[key] = { props: props, value: value };
return value;
}
});
});
api.componentWillReceiveProps = function (nextProps) {
var diffProps = [];
allProps.forEach(function (prop) {
if (!_deepEqual2['default'](component.props[prop], nextProps[prop])) {
diffProps.push(prop);
}
});
diffProps.forEach(uncache);
};
return api;
}
module.exports = exports['default'];
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = createAll;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _createProvider = __webpack_require__(28);
var _createProvider2 = _interopRequireDefault(_createProvider);
var _createConnect = __webpack_require__(27);
var _createConnect2 = _interopRequireDefault(_createConnect);
function createAll(React) {
var Provider = _createProvider2['default'](React);
var connect = _createConnect2['default'](React);
return { Provider: Provider, connect: connect };
}
module.exports = exports['default'];
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = createConnect;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _utilsCreateStoreShape = __webpack_require__(7);
var _utilsCreateStoreShape2 = _interopRequireDefault(_utilsCreateStoreShape);
var _utilsShallowEqual = __webpack_require__(31);
var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual);
var _utilsIsPlainObject = __webpack_require__(30);
var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject);
var _utilsWrapActionCreators = __webpack_require__(32);
var _utilsWrapActionCreators2 = _interopRequireDefault(_utilsWrapActionCreators);
var _hoistNonReactStatics = __webpack_require__(21);
var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics);
var _invariant = __webpack_require__(22);
var _invariant2 = _interopRequireDefault(_invariant);
var defaultMapStateToProps = function defaultMapStateToProps() {
return {};
};
var defaultMapDispatchToProps = function defaultMapDispatchToProps(dispatch) {
return { dispatch: dispatch };
};
var defaultMergeProps = function defaultMergeProps(stateProps, dispatchProps, parentProps) {
return _extends({}, parentProps, stateProps, dispatchProps);
};
function getDisplayName(Component) {
return Component.displayName || Component.name || 'Component';
}
// Helps track hot reloading.
var nextVersion = 0;
function createConnect(React) {
var Component = React.Component;
var PropTypes = React.PropTypes;
var storeShape = _utilsCreateStoreShape2['default'](PropTypes);
return function connect(mapStateToProps, mapDispatchToProps, mergeProps) {
var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
var shouldSubscribe = Boolean(mapStateToProps);
var finalMapStateToProps = mapStateToProps || defaultMapStateToProps;
var finalMapDispatchToProps = _utilsIsPlainObject2['default'](mapDispatchToProps) ? _utilsWrapActionCreators2['default'](mapDispatchToProps) : mapDispatchToProps || defaultMapDispatchToProps;
var finalMergeProps = mergeProps || defaultMergeProps;
var shouldUpdateStateProps = finalMapStateToProps.length > 1;
var shouldUpdateDispatchProps = finalMapDispatchToProps.length > 1;
var _options$pure = options.pure;
var pure = _options$pure === undefined ? true : _options$pure;
// Helps track hot reloading.
var version = nextVersion++;
function computeStateProps(store, props) {
var state = store.getState();
var stateProps = shouldUpdateStateProps ? finalMapStateToProps(state, props) : finalMapStateToProps(state);
_invariant2['default'](_utilsIsPlainObject2['default'](stateProps), '`mapStateToProps` must return an object. Instead received %s.', stateProps);
return stateProps;
}
function computeDispatchProps(store, props) {
var dispatch = store.dispatch;
var dispatchProps = shouldUpdateDispatchProps ? finalMapDispatchToProps(dispatch, props) : finalMapDispatchToProps(dispatch);
_invariant2['default'](_utilsIsPlainObject2['default'](dispatchProps), '`mapDispatchToProps` must return an object. Instead received %s.', dispatchProps);
return dispatchProps;
}
function _computeNextState(stateProps, dispatchProps, parentProps) {
var mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps);
_invariant2['default'](_utilsIsPlainObject2['default'](mergedProps), '`mergeProps` must return an object. Instead received %s.', mergedProps);
return mergedProps;
}
return function wrapWithConnect(WrappedComponent) {
var Connect = (function (_Component) {
_inherits(Connect, _Component);
Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
if (!pure) {
this.updateStateProps(nextProps);
this.updateDispatchProps(nextProps);
this.updateState(nextProps);
return true;
}
var storeChanged = nextState.storeState !== this.state.storeState;
var propsChanged = !_utilsShallowEqual2['default'](nextProps, this.props);
var mapStateProducedChange = false;
var dispatchPropsChanged = false;
if (storeChanged || propsChanged && shouldUpdateStateProps) {
mapStateProducedChange = this.updateStateProps(nextProps);
}
if (propsChanged && shouldUpdateDispatchProps) {
dispatchPropsChanged = this.updateDispatchProps(nextProps);
}
if (propsChanged || mapStateProducedChange || dispatchPropsChanged) {
this.updateState(nextProps);
return true;
}
return false;
};
function Connect(props, context) {
_classCallCheck(this, Connect);
_Component.call(this, props, context);
this.version = version;
this.store = props.store || context.store;
_invariant2['default'](this.store, 'Could not find "store" in either the context or ' + ('props of "' + this.constructor.displayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "store" as a prop to "' + this.constructor.displayName + '".'));
this.stateProps = computeStateProps(this.store, props);
this.dispatchProps = computeDispatchProps(this.store, props);
this.state = { storeState: null };
this.updateState();
}
Connect.prototype.computeNextState = function computeNextState() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
return _computeNextState(this.stateProps, this.dispatchProps, props);
};
Connect.prototype.updateStateProps = function updateStateProps() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var nextStateProps = computeStateProps(this.store, props);
if (_utilsShallowEqual2['default'](nextStateProps, this.stateProps)) {
return false;
}
this.stateProps = nextStateProps;
return true;
};
Connect.prototype.updateDispatchProps = function updateDispatchProps() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var nextDispatchProps = computeDispatchProps(this.store, props);
if (_utilsShallowEqual2['default'](nextDispatchProps, this.dispatchProps)) {
return false;
}
this.dispatchProps = nextDispatchProps;
return true;
};
Connect.prototype.updateState = function updateState() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
this.nextState = this.computeNextState(props);
};
Connect.prototype.isSubscribed = function isSubscribed() {
return typeof this.unsubscribe === 'function';
};
Connect.prototype.trySubscribe = function trySubscribe() {
if (shouldSubscribe && !this.unsubscribe) {
this.unsubscribe = this.store.subscribe(this.handleChange.bind(this));
this.handleChange();
}
};
Connect.prototype.tryUnsubscribe = function tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
}
};
Connect.prototype.componentDidMount = function componentDidMount() {
this.trySubscribe();
};
Connect.prototype.componentWillUnmount = function componentWillUnmount() {
this.tryUnsubscribe();
};
Connect.prototype.handleChange = function handleChange() {
if (!this.unsubscribe) {
return;
}
this.setState({
storeState: this.store.getState()
});
};
Connect.prototype.getWrappedInstance = function getWrappedInstance() {
return this.refs.wrappedInstance;
};
Connect.prototype.render = function render() {
return React.createElement(WrappedComponent, _extends({ ref: 'wrappedInstance'
}, this.nextState));
};
return Connect;
})(Component);
Connect.displayName = 'Connect(' + getDisplayName(WrappedComponent) + ')';
Connect.WrappedComponent = WrappedComponent;
Connect.contextTypes = {
store: storeShape
};
Connect.propTypes = {
store: storeShape
};
if (true) {
Connect.prototype.componentWillUpdate = function componentWillUpdate() {
if (this.version === version) {
return;
}
// We are hot reloading!
this.version = version;
// Update the state and bindings.
this.trySubscribe();
this.updateStateProps();
this.updateDispatchProps();
this.updateState();
};
}
return _hoistNonReactStatics2['default'](Connect, WrappedComponent);
};
};
}
module.exports = exports['default'];
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = createProvider;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _utilsCreateStoreShape = __webpack_require__(7);
var _utilsCreateStoreShape2 = _interopRequireDefault(_utilsCreateStoreShape);
function isUsingOwnerContext(React) {
var version = React.version;
if (typeof version !== 'string') {
return true;
}
var sections = version.split('.');
var major = parseInt(sections[0], 10);
var minor = parseInt(sections[1], 10);
return major === 0 && minor === 13;
}
function createProvider(React) {
var Component = React.Component;
var PropTypes = React.PropTypes;
var Children = React.Children;
var storeShape = _utilsCreateStoreShape2['default'](PropTypes);
var requireFunctionChild = isUsingOwnerContext(React);
var didWarnAboutChild = false;
function warnAboutFunctionChild() {
if (didWarnAboutChild || requireFunctionChild) {
return;
}
didWarnAboutChild = true;
console.error( // eslint-disable-line no-console
'With React 0.14 and later versions, you no longer need to ' + 'wrap <Provider> child into a function.');
}
function warnAboutElementChild() {
if (didWarnAboutChild || !requireFunctionChild) {
return;
}
didWarnAboutChild = true;
console.error( // eslint-disable-line no-console
'With React 0.13, you need to ' + 'wrap <Provider> child into a function. ' + 'This restriction will be removed with React 0.14.');
}
var didWarnAboutReceivingStore = false;
function warnAboutReceivingStore() {
if (didWarnAboutReceivingStore) {
return;
}
didWarnAboutReceivingStore = true;
console.error( // eslint-disable-line no-console
'<Provider> does not support changing `store` on the fly. ' + 'It is most likely that you see this error because you updated to ' + 'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' + 'automatically. See https://github.com/rackt/react-redux/releases/' + 'tag/v2.0.0 for the migration instructions.');
}
var Provider = (function (_Component) {
_inherits(Provider, _Component);
Provider.prototype.getChildContext = function getChildContext() {
return { store: this.store };
};
function Provider(props, context) {
_classCallCheck(this, Provider);
_Component.call(this, props, context);
this.store = props.store;
}
Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var store = this.store;
var nextStore = nextProps.store;
if (store !== nextStore) {
warnAboutReceivingStore();
}
};
Provider.prototype.render = function render() {
var children = this.props.children;
if (typeof children === 'function') {
warnAboutFunctionChild();
children = children();
} else {
warnAboutElementChild();
}
return Children.only(children);
};
return Provider;
})(Component);
Provider.childContextTypes = {
store: storeShape.isRequired
};
Provider.propTypes = {
store: storeShape.isRequired,
children: (requireFunctionChild ? PropTypes.func : PropTypes.element).isRequired
};
return Provider;
}
module.exports = exports['default'];
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(12);
var _react2 = _interopRequireDefault(_react);
var _componentsCreateAll = __webpack_require__(26);
var _componentsCreateAll2 = _interopRequireDefault(_componentsCreateAll);
var _createAll = _componentsCreateAll2['default'](_react2['default']);
var Provider = _createAll.Provider;
var connect = _createAll.connect;
exports.Provider = Provider;
exports.connect = connect;
/***/ },
/* 30 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports['default'] = isPlainObject;
var fnToString = function fnToString(fn) {
return Function.prototype.toString.call(fn);
};
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype;
if (proto === null) {
return true;
}
var constructor = proto.constructor;
return typeof constructor === 'function' && constructor instanceof constructor && fnToString(constructor) === fnToString(Object);
}
module.exports = exports['default'];
/***/ },
/* 31 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = shallowEqual;
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = exports["default"];
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = wrapActionCreators;
var _redux = __webpack_require__(33);
function wrapActionCreators(actionCreators) {
return function (dispatch) {
return _redux.bindActionCreators(actionCreators, dispatch);
};
}
module.exports = exports['default'];
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _createStore = __webpack_require__(8);
var _createStore2 = _interopRequireDefault(_createStore);
var _utilsCombineReducers = __webpack_require__(36);
var _utilsCombineReducers2 = _interopRequireDefault(_utilsCombineReducers);
var _utilsBindActionCreators = __webpack_require__(35);
var _utilsBindActionCreators2 = _interopRequireDefault(_utilsBindActionCreators);
var _utilsApplyMiddleware = __webpack_require__(34);
var _utilsApplyMiddleware2 = _interopRequireDefault(_utilsApplyMiddleware);
var _utilsCompose = __webpack_require__(9);
var _utilsCompose2 = _interopRequireDefault(_utilsCompose);
exports.createStore = _createStore2['default'];
exports.combineReducers = _utilsCombineReducers2['default'];
exports.bindActionCreators = _utilsBindActionCreators2['default'];
exports.applyMiddleware = _utilsApplyMiddleware2['default'];
exports.compose = _utilsCompose2['default'];
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = applyMiddleware;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _compose = __webpack_require__(9);
var _compose2 = _interopRequireDefault(_compose);
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
*
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
function applyMiddleware() {
for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
return function (next) {
return function (reducer, initialState) {
var store = next(reducer, initialState);
var _dispatch = store.dispatch;
var chain = [];
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch(action) {
return _dispatch(action);
}
};
chain = middlewares.map(function (middleware) {
return middleware(middlewareAPI);
});
_dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch);
return _extends({}, store, {
dispatch: _dispatch
});
};
};
}
module.exports = exports['default'];
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = bindActionCreators;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _utilsMapValues = __webpack_require__(11);
var _utilsMapValues2 = _interopRequireDefault(_utilsMapValues);
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(undefined, arguments));
};
}
/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* For convenience, you can also pass a single function as the first argument,
* and get a function in return.
*
* @param {Function|Object} actionCreators An object whose values are action
* creator functions. One handy way to obtain it is to use ES6 `import * as`
* syntax. You may also pass a single function.
*
* @param {Function} dispatch The `dispatch` function available on your Redux
* store.
*
* @returns {Function|Object} The object mimicking the original object, but with
* every action creator wrapped into the `dispatch` call. If you passed a
* function as `actionCreators`, the return value will also be a single
* function.
*/
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== 'object' || actionCreators === null || actionCreators === undefined) {
// eslint-disable-line no-eq-null
throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
}
return _utilsMapValues2['default'](actionCreators, function (actionCreator) {
return bindActionCreator(actionCreator, dispatch);
});
}
module.exports = exports['default'];
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = combineReducers;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _createStore = __webpack_require__(8);
var _utilsIsPlainObject = __webpack_require__(10);
var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject);
var _utilsMapValues = __webpack_require__(11);
var _utilsMapValues2 = _interopRequireDefault(_utilsMapValues);
var _utilsPick = __webpack_require__(37);
var _utilsPick2 = _interopRequireDefault(_utilsPick);
/* eslint-disable no-console */
function getUndefinedStateErrorMessage(key, action) {
var actionType = action && action.type;
var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
return 'Reducer "' + key + '" returned undefined handling ' + actionName + '. ' + 'To ignore an action, you must explicitly return the previous state.';
}
function getUnexpectedStateKeyWarningMessage(inputState, outputState, action) {
var reducerKeys = Object.keys(outputState);
var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'initialState argument passed to createStore' : 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
}
if (!_utilsIsPlainObject2['default'](inputState)) {
return 'The ' + argumentName + ' has unexpected type of "' + ({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"');
}
var unexpectedKeys = Object.keys(inputState).filter(function (key) {
return reducerKeys.indexOf(key) < 0;
});
if (unexpectedKeys.length > 0) {
return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.');
}
}
function assertReducerSanity(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.');
}
var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type: type }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.');
}
});
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var finalReducers = _utilsPick2['default'](reducers, function (val) {
return typeof val === 'function';
});
var sanityError;
try {
assertReducerSanity(finalReducers);
} catch (e) {
sanityError = e;
}
var defaultState = _utilsMapValues2['default'](finalReducers, function () {
return undefined;
});
return function combination(state, action) {
if (state === undefined) state = defaultState;
if (sanityError) {
throw sanityError;
}
var finalState = _utilsMapValues2['default'](finalReducers, function (reducer, key) {
var newState = reducer(state[key], action);
if (typeof newState === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action);
throw new Error(errorMessage);
}
return newState;
});
if (true) {
var warningMessage = getUnexpectedStateKeyWarningMessage(state, finalState, action);
if (warningMessage) {
console.error(warningMessage);
}
}
return finalState;
};
}
module.exports = exports['default'];
/***/ },
/* 37 */
/***/ function(module, exports) {
/**
* Picks key-value pairs from an object where values satisfy a predicate.
*
* @param {Object} obj The object to pick from.
* @param {Function} fn The predicate the values must satisfy to be copied.
* @returns {Object} The object with the values that satisfied the predicate.
*/
"use strict";
exports.__esModule = true;
exports["default"] = pick;
function pick(obj, fn) {
return Object.keys(obj).reduce(function (result, key) {
if (fn(obj[key])) {
result[key] = obj[key];
}
return result;
}, {});
}
module.exports = exports["default"];
/***/ }
/******/ ])
});
;
|
import Ember from 'ember';
const {Mixin} = Ember;
export default Mixin.create({
transitionAuthor() {
return (user) => {
if (user.get('isAuthor')) {
return this.transitionTo('team.user', user);
}
return user;
};
},
transitionEditor() {
return (user) => {
if (user.get('isEditor')) {
return this.transitionTo('team');
}
return user;
};
}
});
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('./core'),
Persist = _dereq_('../lib/Persist');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Persist":26,"./core":2}],2:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":6,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
// Convert the index object to an array of key val objects
this.keys(this.extractKeys(index));
}
return this.$super.call(this, index);
});
BinaryTree.prototype.extractKeys = function (obj) {
var i,
keys = [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push({
key: i,
val: obj[i]
});
}
}
return keys;
};
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return true;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.val === 1) {
result = this.sortAsc(a[indexData.key], b[indexData.key]);
} else if (indexData.val === -1) {
result = this.sortDesc(a[indexData.key], b[indexData.key]);
}
if (result !== 0) {
return result;
}
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.key];
}
return hash;*/
return obj[this._keys[0].key];
};
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (!this._data) {
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === -1) {
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === 1) {
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
return false;
};
BinaryTree.prototype.lookup = function (data, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, resultArr); }
}
return resultArr;
};
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use)
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRange(type, key, from, to, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
BinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path(),
indexKeyArr = pathSolver.parseArr(this._index),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":25,"./Shared":31}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: dataSet});
}
if (callback) { callback(false, dataSet); }
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.emit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return false;
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
//renameFieldMethod,
//renameFieldPath,
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; }
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
return new Path(query.substr(3, query.length - 3)).value(item)[0];
}
return new Path(query).value(item)[0];
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var name = options.name;
if (name) {
if (!this._collection[name]) {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":7,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":29,"./Shared":31}],5:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
// Handle being passed an instance
if (collectionGroupName instanceof CollectionGroup) {
return collectionGroupName;
}
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":4,"./Shared":31}],6:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
callback();
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":12,"./Overload":24,"./Shared":31}],7:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":12,"./Overload":24,"./Shared":31}],9:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
treeInstance = new BinaryTree(),
btree = function () {};
treeInstance.inOrder('hash');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":25,"./Shared":31}],10:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":25,"./Shared":31}],11:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":31}],12:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":23,"./Shared":31}],13:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],14:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
arrItem.chainReceive(this, type, data, options);
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],15:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":24,"./Serialiser":30}],16:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],17:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":24}],18:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) {
return true;
} else if (inArr[inArrIndex] === source) {
return true;
}
}
return false;
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
return false;
}
}
return true;
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
}
return -1;
}
};
module.exports = Matching;
},{}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":24}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":25,"./Shared":31}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],25:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":31}],26:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
callback(false, val, {});
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
callback(false, val, {});
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) {
callback('No data handler or unrecognised data type.');
}
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '::' + this._name);
this._db.persist.drop(this._db._name + '::' + this._name + '::metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '::' + this._name, function () {
self._db.persist.drop(self._db._name + '::' + self._name + '::metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '::' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '::' + self._name + '::metaData', self.metaData(), function (err, data, metaStats) {
if (callback) {
callback(err, data, tableStats, metaStats);
}
});
} else {
if (callback) {
callback(err);
}
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) {
callback('Cannot save a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot save a collection with no assigned name!');
}
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '::' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '::' + self._name + '::metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) {
callback(err, tableStats, metaStats);
}
});
} else {
if (callback) {
callback(err);
}
}
});
} else {
if (callback) {
callback('Cannot load a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot load a collection with no assigned name!');
}
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Db.prototype.load = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
obj[index].load(loadCallback);
}
}
};
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Db.prototype.save = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
obj[index].save(saveCallback);
}
}
};
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":27,"./PersistCrypto":28,"./Shared":31,"async":33,"localforage":75}],27:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":31,"pako":77}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":31,"crypto-js":42}],29:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactoreOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":31}],30:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Register our handlers
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],31:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.376',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: new Overload({
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],32:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}],33:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (!callback) {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has inexistant dependency');
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback(null);
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
while(workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (key in queues) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":68}],34:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],35:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":36}],36:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],37:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":36}],38:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":36}],39:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":36,"./hmac":41,"./sha1":60}],40:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":35,"./core":36}],41:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":36}],42:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":34,"./cipher-core":35,"./core":36,"./enc-base64":37,"./enc-utf16":38,"./evpkdf":39,"./format-hex":40,"./hmac":41,"./lib-typedarrays":43,"./md5":44,"./mode-cfb":45,"./mode-ctr":47,"./mode-ctr-gladman":46,"./mode-ecb":48,"./mode-ofb":49,"./pad-ansix923":50,"./pad-iso10126":51,"./pad-iso97971":52,"./pad-nopadding":53,"./pad-zeropadding":54,"./pbkdf2":55,"./rabbit":57,"./rabbit-legacy":56,"./rc4":58,"./ripemd160":59,"./sha1":60,"./sha224":61,"./sha256":62,"./sha3":63,"./sha384":64,"./sha512":65,"./tripledes":66,"./x64-core":67}],43:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":36}],44:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":36}],45:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":35,"./core":36}],46:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":35,"./core":36}],47:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":35,"./core":36}],48:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":35,"./core":36}],49:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":35,"./core":36}],50:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":35,"./core":36}],51:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":35,"./core":36}],52:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":35,"./core":36}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":35,"./core":36}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":35,"./core":36}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":36,"./hmac":41,"./sha1":60}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],59:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":36}],60:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":36}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":36,"./sha256":62}],62:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":36}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":36,"./x64-core":67}],64:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":36,"./sha512":65,"./x64-core":67}],65:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":36,"./x64-core":67}],66:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],67:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":36}],68:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],69:[function(_dereq_,module,exports){
'use strict';
var asap = _dereq_('asap')
module.exports = Promise
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
if (typeof fn !== 'function') throw new TypeError('not a function')
var state = null
var value = null
var deferreds = []
var self = this
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle(new Handler(onFulfilled, onRejected, resolve, reject))
})
}
function handle(deferred) {
if (state === null) {
deferreds.push(deferred)
return
}
asap(function() {
var cb = state ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state ? deferred.resolve : deferred.reject)(value)
return
}
var ret
try {
ret = cb(value)
}
catch (e) {
deferred.reject(e)
return
}
deferred.resolve(ret)
})
}
function resolve(newValue) {
try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.')
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then
if (typeof then === 'function') {
doResolve(then.bind(newValue), resolve, reject)
return
}
}
state = true
value = newValue
finale()
} catch (e) { reject(e) }
}
function reject(newValue) {
state = false
value = newValue
finale()
}
function finale() {
for (var i = 0, len = deferreds.length; i < len; i++)
handle(deferreds[i])
deferreds = null
}
doResolve(fn, resolve, reject)
}
function Handler(onFulfilled, onRejected, resolve, reject){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.resolve = resolve
this.reject = reject
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function (value) {
if (done) return
done = true
onFulfilled(value)
}, function (reason) {
if (done) return
done = true
onRejected(reason)
})
} catch (ex) {
if (done) return
done = true
onRejected(ex)
}
}
},{"asap":71}],70:[function(_dereq_,module,exports){
'use strict';
//This file contains then/promise specific extensions to the core promise API
var Promise = _dereq_('./core.js')
var asap = _dereq_('asap')
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Object.create(Promise.prototype)
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.from = Promise.cast = function (value) {
var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead')
err.name = 'Warning'
console.warn(err.stack)
return Promise.resolve(value)
}
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
fn.apply(self, args)
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
try {
return fn.apply(this, arguments).nodeify(callback)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback(ex)
})
}
}
}
}
Promise.all = function () {
var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0])
var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments)
if (!calledWithArray) {
var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated')
err.name = 'Warning'
console.warn(err.stack)
}
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([])
var remaining = args.length
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then
if (typeof then === 'function') {
then.call(val, function (val) { res(i, val) }, reject)
return
}
}
args[i] = val
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex)
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i])
}
})
}
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
asap(function () {
throw err
})
})
}
Promise.prototype.nodeify = function (callback) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback(null, value)
})
}, function (err) {
asap(function () {
callback(err)
})
})
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":69,"asap":71}],71:[function(_dereq_,module,exports){
(function (process){
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestFlush = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestFlush = setImmediate.bind(window, flush);
} else {
requestFlush = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
channel.port1.onmessage = flush;
requestFlush = function () {
channel.port2.postMessage(0);
};
} else {
// old browsers
requestFlush = function () {
setTimeout(flush, 0);
};
}
function asap(task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestFlush();
}
};
module.exports = asap;
}).call(this,_dereq_('_process'))
},{"_process":68}],72:[function(_dereq_,module,exports){
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
(function() {
'use strict';
// Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB ||
this.mozIndexedDB || this.OIndexedDB ||
this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = window.BlobBuilder ||
window.MSBlobBuilder ||
window.MozBlobBuilder ||
window.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({status: xhr.status, response: xhr.response});
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function(resolve, reject) {
var blob = _createBlob([''], {type: 'image/png'});
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function() {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE],
'readwrite');
var getBlobReq = blobTxn.objectStore(
DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function(e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function(res) {
resolve(!!(res && res.type === 'image/png'));
}, function() {
resolve(false);
}).then(function() {
URL.revokeObjectURL(url);
});
};
};
})['catch'](function() {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function(value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function(e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type});
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
return new Promise(function(resolve, reject) {
var openreq = indexedDB.open(dbInfo.name, dbInfo.version);
openreq.onerror = function() {
reject(openreq.error);
};
openreq.onupgradeneeded = function(e) {
// First time setup: create an empty object store
openreq.result.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// added when support for blob shims was added
openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
};
openreq.onsuccess = function() {
dbInfo.db = openreq.result;
self._dbInfo = dbInfo;
resolve();
};
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function() {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void(0)) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
var dbInfo;
self.ready().then(function() {
dbInfo = self._dbInfo;
return _checkBlobSupport(dbInfo.db);
}).then(function(blobSupport) {
if (!blobSupport && value instanceof Blob) {
return _encodeBlob(value);
}
return value;
}).then(function(value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function() {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function() {
resolve();
};
transaction.onerror = function() {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function() {
resolve();
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function() {
resolve(req.result);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = asyncStorage;
} else if (typeof define === 'function' && define.amd) {
define('asyncStorage', function() {
return asyncStorage;
});
} else {
this.asyncStorage = asyncStorage;
}
}).call(window);
},{"promise":70}],73:[function(_dereq_,module,exports){
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
self._dbInfo = dbInfo;
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
return serializerPromise.then(function(lib) {
serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), i + 1);
if (value !== void(0)) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function(keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function(resolve, reject) {
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
try {
var dbInfo = self._dbInfo;
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.EXPORT) {
module.exports = localStorageWrapper;
} else if (moduleType === ModuleType.DEFINE) {
define('localStorageWrapper', function() {
return localStorageWrapper;
});
} else {
this.localStorageWrapper = localStorageWrapper;
}
}).call(window);
},{"./../utils/serializer":76,"promise":70}],74:[function(_dereq_,module,exports){
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof(options[i]) !== 'string' ?
options[i].toString() : options[i];
}
}
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
var dbInfoPromise = new Promise(function(resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version),
dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver(self.LOCALSTORAGE).then(function() {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function(t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName +
' (id INTEGER PRIMARY KEY, key unique, value)', [],
function() {
self._dbInfo = dbInfo;
resolve();
}, function(t, error) {
reject(error);
});
});
});
return serializerPromise.then(function(lib) {
serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName +
' WHERE key = ? LIMIT 1', [key],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = serializer.deserialize(result);
}
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [],
function(t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void(0)) {
resolve(result);
return;
}
}
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('INSERT OR REPLACE INTO ' +
dbInfo.storeName +
' (key, value) VALUES (?, ?)',
[key, value], function() {
resolve(originalValue);
}, function(t, error) {
reject(error);
});
}, function(sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName +
' WHERE key = ?', [key],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' +
dbInfo.storeName, [], function(t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName +
' WHERE id = ? LIMIT 1', [n + 1],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).key : null;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [],
function(t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.DEFINE) {
define('webSQLStorage', function() {
return webSQLStorage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = webSQLStorage;
} else {
this.webSQLStorage = webSQLStorage;
}
}).call(window);
},{"./../utils/serializer":76,"promise":70}],75:[function(_dereq_,module,exports){
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports &&
typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [
DriverType.INDEXEDDB,
DriverType.WEBSQL,
DriverType.LOCALSTORAGE
];
var LibraryMethods = [
'clear',
'getItem',
'iterate',
'key',
'keys',
'length',
'removeItem',
'setItem'
];
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function(self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB ||
self.mozIndexedDB || self.OIndexedDB ||
self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function() {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator &&
self.navigator.userAgent &&
/Safari/.test(self.navigator.userAgent) &&
!/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB &&
typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function() {
try {
return (self.localStorage &&
('setItem' in self.localStorage) &&
(self.localStorage.setItem));
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function() {
var _args = arguments;
return localForageInstance.ready().then(function() {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) &&
DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var globalObject = this;
function LocalForage(options) {
this._config = extend({}, DefaultConfig, options);
this._driverSet = null;
this._ready = false;
this._dbInfo = null;
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
this.setDriver(this._config.driver);
}
LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB;
LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE;
LocalForage.prototype.WEBSQL = DriverType.WEBSQL;
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof(options) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " +
'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof(options) === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function(driverObject, callback,
errorCallback) {
var defineDriver = new Promise(function(resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error(
'Custom driver not compliant; see ' +
'https://mozilla.github.io/localForage/#definedriver'
);
var namingError = new Error(
'Custom driver name already in use: ' + driverObject._driver
);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod ||
!driverObject[customDriverMethod] ||
typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function(supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
defineDriver.then(callback, errorCallback);
return defineDriver;
};
LocalForage.prototype.driver = function() {
return this._driver || null;
};
LocalForage.prototype.ready = function(callback) {
var self = this;
var ready = new Promise(function(resolve, reject) {
self._driverSet.then(function() {
if (self._ready === null) {
self._ready = self._initStorage(self._config);
}
self._ready.then(resolve, reject);
})['catch'](reject);
});
ready.then(callback, callback);
return ready;
};
LocalForage.prototype.setDriver = function(drivers, callback,
errorCallback) {
var self = this;
if (typeof drivers === 'string') {
drivers = [drivers];
}
this._driverSet = new Promise(function(resolve, reject) {
var driverName = self._getFirstSupportedDriver(drivers);
var error = new Error('No available storage method found.');
if (!driverName) {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
self._dbInfo = null;
self._ready = null;
if (isLibraryDriver(driverName)) {
var driverPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_([driverName], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
switch (driverName) {
case self.INDEXEDDB:
resolve(_dereq_('./drivers/indexeddb'));
break;
case self.LOCALSTORAGE:
resolve(_dereq_('./drivers/localstorage'));
break;
case self.WEBSQL:
resolve(_dereq_('./drivers/websql'));
break;
}
} else {
resolve(globalObject[driverName]);
}
});
driverPromise.then(function(driver) {
self._extend(driver);
resolve();
});
} else if (CustomDrivers[driverName]) {
self._extend(CustomDrivers[driverName]);
resolve();
} else {
self._driverSet = Promise.reject(error);
reject(error);
}
});
function setDriverToConfig() {
self._config.driver = self.driver();
}
this._driverSet.then(setDriverToConfig, setDriverToConfig);
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
// Used to determine which driver we should use as the backend for this
// instance of localForage.
LocalForage.prototype._getFirstSupportedDriver = function(drivers) {
if (drivers && isArray(drivers)) {
for (var i = 0; i < drivers.length; i++) {
var driver = drivers[i];
if (this.supports(driver)) {
return driver;
}
}
}
return null;
};
LocalForage.prototype.createInstance = function(options) {
return new LocalForage(options);
};
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localForage = new LocalForage();
// We allow localForage to be declared as a module or as a library
// available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
define('localforage', function() {
return localForage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = localForage;
} else {
this.localforage = localForage;
}
}).call(window);
},{"./drivers/indexeddb":72,"./drivers/localstorage":73,"./drivers/websql":74,"promise":70}],76:[function(_dereq_,module,exports){
(function() {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH +
TYPE_ARRAYBUFFER.length;
// Get out of our habit of using `window` inline, at least.
var globalObject = this;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder ||
globalObject.MSBlobBuilder ||
globalObject.MozBlobBuilder ||
globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' ||
value.buffer &&
value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function() {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' +
bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ",
value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0,
SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH,
TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], {type: blobType});
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i+=4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i+1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i+2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i+3]);
/*jslint bitwise: true */
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if ((bytes.length % 3) === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = localforageSerializer;
} else if (typeof define === 'function' && define.amd) {
define('localforageSerializer', function() {
return localforageSerializer;
});
} else {
this.localforageSerializer = localforageSerializer;
}
}).call(window);
},{}],77:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":78,"./lib/inflate":79,"./lib/utils/common":80,"./lib/zlib/constants":83}],78:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":80,"./utils/strings":81,"./zlib/deflate.js":85,"./zlib/messages":90,"./zlib/zstream":92}],79:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var gzheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":80,"./utils/strings":81,"./zlib/constants":83,"./zlib/gzheader":86,"./zlib/inflate.js":88,"./zlib/messages":90,"./zlib/zstream":92}],80:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],81:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":80}],82:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],83:[function(_dereq_,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],84:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],85:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":80,"./adler32":82,"./crc32":84,"./messages":90,"./trees":91}],86:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],87:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],88:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":80,"./adler32":82,"./crc32":84,"./inffast":87,"./inftrees":89}],89:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":80}],90:[function(_dereq_,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],91:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":80}],92:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}]},{},[1]);
|
Type.registerNamespace("Strings");
Strings.OfficeOM = function()
{
};
Strings.OfficeOM.registerClass("Strings.OfficeOM");
Strings.OfficeOM.L_InvalidNamedItemForBindingType = "Navedeni tip povezivanja nije kompatibilan sa navedenom imenovanom stavkom.";
Strings.OfficeOM.L_EventHandlerNotExist = "Navedeni tip događaja nije podržan na ovom objektu.";
Strings.OfficeOM.L_UnknownBindingType = "Tip povezivanja nije podržan.";
Strings.OfficeOM.L_InvalidNode = "Nevažeći čvor";
Strings.OfficeOM.L_NotImplemented = "Funkcija {0} nije primenjena.";
Strings.OfficeOM.L_NoCapability = "Nemate dovoljno dozvola za ovu radnju.";
Strings.OfficeOM.L_SettingsCannotSave = "Nije bilo moguće sačuvati postavke.";
Strings.OfficeOM.L_DataWriteReminder = "Data Write Reminder";
Strings.OfficeOM.L_InvalidBinding = "Nevažeće povezivanje";
Strings.OfficeOM.L_InvalidSetColumns = "Navedene kolone su nevažeće.";
Strings.OfficeOM.L_BindingCreationError = "Greška u stvaranju povezivanja";
Strings.OfficeOM.L_FormatValueOutOfRange = "Vrednost je izvan dozvoljenog opsega.";
Strings.OfficeOM.L_SelectionNotSupportCoercionType = "Trenutna selekcija nije kompatibilna sa navedenim tipom promene.";
Strings.OfficeOM.L_InvalidBindingError = "Greška nevažećeg povezivanja";
Strings.OfficeOM.L_InvalidGetStartRowColumn = "Navedene vrednosti za početni red ili početnu kolonu nisu važeće.";
Strings.OfficeOM.L_InvalidSetRows = "Navedeni redovi su nevažeći.";
Strings.OfficeOM.L_CannotWriteToSelection = "Upisivanje u trenutnu selekciju nije moguće.";
Strings.OfficeOM.L_MissingParameter = "Parametar nedostaje";
Strings.OfficeOM.L_IndexOutOfRange = "Indeks je izvan opsega.";
Strings.OfficeOM.L_SettingsStaleError = "Greška usled zastarelih postavki";
Strings.OfficeOM.L_CannotNavigateTo = "Objekat se nalazi na lokaciji na kojoj navigacija nije podržana.";
Strings.OfficeOM.L_ReadSettingsError = "Greška u postavkama čitanja";
Strings.OfficeOM.L_InvalidGetColumns = "Navedene kolone su nevažeće.";
Strings.OfficeOM.L_CoercionTypeNotSupported = "Navedeni tip promene nije podržan.";
Strings.OfficeOM.L_AppNotExistInitializeNotCalled = "Aplikacija {0} ne postoji. Microsoft.Office.WebExtension.initialize(razlog) nije pozvan.";
Strings.OfficeOM.L_OverwriteWorksheetData = "Operacija postavljanja nije uspela zato što će navedeni objekat podataka zameniti ili premestiti podatke.";
Strings.OfficeOM.L_RowIndexOutOfRange = "Vrednost indeksa reda je izvan dozvoljenog opsega. Koristite vrednost (0 ili veću) koja je manja od broja redova.";
Strings.OfficeOM.L_ColIndexOutOfRange = "Vrednost indeksa kolone je izvan dozvoljenog opsega. Koristite vrednost (0 ili veću) koja je manja od broja kolona.";
Strings.OfficeOM.L_UnsupportedEnumeration = "Nepodržano nabrajanje";
Strings.OfficeOM.L_InvalidParameters = "Funkcija {0} ima nevažeće parametre.";
Strings.OfficeOM.L_SetDataParametersConflict = "Navedeni parametri su neusaglašeni.";
Strings.OfficeOM.L_DataNotMatchCoercionType = "Tip navedenog objekta podataka nije kompatibilan sa trenutnom selekcijom.";
Strings.OfficeOM.L_UnsupportedEnumerationMessage = "Nabrajanje nije podržano u trenutnoj aplikaciji hosta.";
Strings.OfficeOM.L_InvalidCoercion = "Nevažeći tip promene";
Strings.OfficeOM.L_NotSupportedEventType = "Navedeni tip događaja {0} nije podržan.";
Strings.OfficeOM.L_UnsupportedDataObject = "Navedeni tip objekta podataka nije podržan.";
Strings.OfficeOM.L_GetDataIsTooLarge = "Zahtevani skup podataka je prevelik.";
Strings.OfficeOM.L_AppNameNotExist = "AppName za {0} ne postoji.";
Strings.OfficeOM.L_AddBindingFromPromptDefaultText = "Napravite selekciju.";
Strings.OfficeOM.L_MultipleNamedItemFound = "Pronađeno je više objekata sa istim imenom.";
Strings.OfficeOM.L_InvalidCellsValue = "Neki parametri ćelije imaju vrednosti koje nisu dozvoljene. Proverite vrednosti još jednom i probajte ponovo.";
Strings.OfficeOM.L_DataNotMatchBindingType = "Navedeni objekat podataka nije kompatibilan sa tipom povezivanja.";
Strings.OfficeOM.L_InvalidFormatValue = "Neki parametri formata imaju vrednosti koje nisu dozvoljene. Proverite vrednosti još jednom i probajte ponovo.";
Strings.OfficeOM.L_NotSupportedBindingType = "Navedeni tip povezivanja {0} nije podržan.";
Strings.OfficeOM.L_InitializeNotReady = "Office.js još uvek nije potpuno učitan. Pokušajte ponovo kasnije ili postarajte se da dodate vaš kôd za pokretanje na vaš Office.initialize function.";
Strings.OfficeOM.L_FormattingReminder = "Formatting Reminder";
Strings.OfficeOM.L_ShuttingDown = "Operacija nije uspela zato što podaci na serveru nisu u toku.";
Strings.OfficeOM.L_OperationNotSupported = "Operacija nije podržana.";
Strings.OfficeOM.L_DocumentReadOnly = "Zahtevana operacija nije dozvoljena u trenutnom režimu dokumenta.";
Strings.OfficeOM.L_NamedItemNotFound = "Imenovana stavka ne postoji.";
Strings.OfficeOM.L_InvalidApiCallInContext = "Nevažeći API poziv u trenutnom kontekstu.";
Strings.OfficeOM.L_InvalidGetRows = "Navedeni redovi su nevažeći.";
Strings.OfficeOM.L_CellFormatAmountBeyondLimits = "Note: The formatting sets set by a Formatting API call is suggested to be below 100.";
Strings.OfficeOM.L_SetDataIsTooLarge = "Navedeni objekat podataka je prevelik.";
Strings.OfficeOM.L_DataWriteError = "Greška u pisanju podataka";
Strings.OfficeOM.L_InvalidBindingOperation = "Operacija nevažećeg povezivanja";
Strings.OfficeOM.L_SpecifiedIdNotExist = "Navedeni ID ne postoji.";
Strings.OfficeOM.L_FunctionCallFailed = "Poziv funkcije {0} nije uspeo, kod greške: {1}.";
Strings.OfficeOM.L_DataNotMatchBindingSize = "Navedeni objekat podataka ne podudara se sa veličinom trenutne selekcije.";
Strings.OfficeOM.L_SaveSettingsError = "Greška pri čuvanju postavki";
Strings.OfficeOM.L_InvalidSetStartRowColumn = "Navedene vrednosti za početni red ili početnu kolonu nisu važeće.";
Strings.OfficeOM.L_InvalidFormat = "Greška nevažećeg formata";
Strings.OfficeOM.L_BindingNotExist = "Navedeno povezivanje ne postoji.";
Strings.OfficeOM.L_SettingNameNotExist = "Navedeno ime postavke ne postoji.";
Strings.OfficeOM.L_EventHandlerAdditionFailed = "Dodavanje rukovaoca događajem nije uspelo.";
Strings.OfficeOM.L_InvalidAPICall = "Nevažeći API poziv";
Strings.OfficeOM.L_EventRegistrationError = "Greška pri registraciji događaja";
Strings.OfficeOM.L_ElementMissing = "Nismo mogli da oblikujemo ćeliju tabele zato što nedostaju neke vrednosti parametara. Proverite parametre još jednom i probajte ponovo.";
Strings.OfficeOM.L_NonUniformPartialSetNotSupported = "Nije moguće koristiti parametre za koordinaciju sa tabelom tipa promene kada tabela sadrži objedinjene ćelije.";
Strings.OfficeOM.L_NavOutOfBound = "Operacija nije uspela zato što je indeks van opsega.";
Strings.OfficeOM.L_RedundantCallbackSpecification = "Povratni poziv ne može biti naveden i u listi argumenata i u opcionalnom objektu.";
Strings.OfficeOM.L_CustomXmlError = "Greška u prilagođenim XML.";
Strings.OfficeOM.L_SettingsAreStale = "Nije bilo moguće sačuvati postavke jer nisu u toku.";
Strings.OfficeOM.L_TooManyOptionalFunction = "višestruke opcionalne funkcije na listi parametara";
Strings.OfficeOM.L_MissingRequiredArguments = "nedostaju neki neophodni argumenti";
Strings.OfficeOM.L_NonUniformPartialGetNotSupported = "Nije moguće koristiti parametre za koordinaciju sa tabelom tipa promene kada tabela sadrži objedinjene ćelije.";
Strings.OfficeOM.L_HostError = "Greška hosta";
Strings.OfficeOM.L_OutOfRange = "Izvan opsega";
Strings.OfficeOM.L_InvalidSelectionForBindingType = "Nije moguće kreirati povezivanje sa trenutnom selekcijom i navedenim tipom povezivanja.";
Strings.OfficeOM.L_TooManyOptionalObjects = "višestruki opcionalni objekti na listi parametara";
Strings.OfficeOM.L_OperationNotSupportedOnMatrixData = "Potrebo je da izabrani sadržaj bude u formatu tabele. Oblikujte podatke u vidu tabele i probajte ponovo.";
Strings.OfficeOM.L_EventHandlerRemovalFailed = "Uklanjanje rukovaoca događajem nije uspelo.";
Strings.OfficeOM.L_BindingToMultipleSelection = "Nekontinuirane selekcije nisu podržane.";
Strings.OfficeOM.L_DataReadError = "Greška u čitanju podataka";
Strings.OfficeOM.L_InternalErrorDescription = "Došlo je do unutrašnje greške.";
Strings.OfficeOM.L_InvalidDataFormat = "Format navedenog objekta podataka nije važeći.";
Strings.OfficeOM.L_DataStale = "Podaci nisu u toku";
Strings.OfficeOM.L_GetSelectionNotSupported = "Trenutna selekcija nije podržana.";
Strings.OfficeOM.L_CellDataAmountBeyondLimits = "Note: The number of cells in a table is suggested to be below 20,000 cells.";
Strings.OfficeOM.L_InvalidTableOptionValue = "Neki tableOptions parametri imaju vrednosti koje nisu dozvoljene. Proverite vrednosti još jednom i probajte ponovo.";
Strings.OfficeOM.L_PermissionDenied = "Dozvola je odbijena";
Strings.OfficeOM.L_InvalidDataObject = "Nevažeći objekat podataka";
Strings.OfficeOM.L_SelectionCannotBound = "Nije moguće izvršiti povezivanje sa trenutnom selekcijom.";
Strings.OfficeOM.L_InvalidColumnsForBinding = "Navedene kolone su nevažeće.";
Strings.OfficeOM.L_BadSelectorString = "Niska koja je prosleđena u birač nije u ispravnom formatu ili nije podržan.";
Strings.OfficeOM.L_InvalidGetRowColumnCounts = "Navedene vrednosti za broj redova ili broj kolona nisu važeće.";
Strings.OfficeOM.L_OsfControlTypeNotSupported = "OsfControl tip nije podržan.";
Strings.OfficeOM.L_InvalidValue = "Nevažeća vrednost";
Strings.OfficeOM.L_DataNotMatchSelection = "Navedeni objekat podataka nije kompatibilan sa oblikom ili dimenzijama trenutne selekcije.";
Strings.OfficeOM.L_InternalError = "Unutrašnja greška";
Strings.OfficeOM.L_NotSupported = "Funkcija {0} nije podržana.";
Strings.OfficeOM.L_CustomXmlNodeNotFound = "Nije pronađen navedeni čvor.";
Strings.OfficeOM.L_CoercionTypeNotMatchBinding = "Navedeni tip promene nije kompatibilan sa ovim tipom povezivanja.";
Strings.OfficeOM.L_TooManyArguments = "previše argumenata";
Strings.OfficeOM.L_OperationNotSupportedOnThisBindingType = "Operacija nije podržana na ovom tipu povezivanja.";
Strings.OfficeOM.L_InValidOptionalArgument = "nevažeći opcionalni argument";
Strings.OfficeOM.L_FileTypeNotSupported = "Navedeni tip datoteke nije podržan.";
Strings.OfficeOM.L_GetDataParametersConflict = "Navedeni parametri su neusaglašeni.";
Strings.OfficeOM.L_CallbackNotAFunction = "Povratni poziv mora biti funkcija tipa, bila je tipa {0}."
|
/*!
* iCheck v1.0.1, http://git.io/arlzeA
* ===================================
* Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization
*
* (c) 2013 Damir Sultanov, http://fronteed.com
* MIT Licensed
*/
(function($) {
// Cached vars
var _iCheck = 'iCheck',
_iCheckHelper = _iCheck + '-helper',
_checkbox = 'checkbox',
_radio = 'radio',
_checked = 'checked',
_unchecked = 'un' + _checked,
_disabled = 'disabled',a
_determinate = 'determinate',
_indeterminate = 'in' + _determinate,
_update = 'update',
_type = 'type',
_click = 'click',
_touch = 'touchbegin.i touchend.i',
_add = 'addClass',
_remove = 'removeClass',
_callback = 'trigger',
_label = 'label',
_cursor = 'cursor',
_mobile = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent);
// Plugin init
$.fn[_iCheck] = function(options, fire) {
// Walker
var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]',
stack = $(),
walker = function(object) {
object.each(function() {
var self = $(this);
if (self.is(handle)) {
stack = stack.add(self);
} else {
stack = stack.add(self.find(handle));
}
});
};
// Check if we should operate with some method
if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) {
// Normalize method's name
options = options.toLowerCase();
// Find checkboxes and radio buttons
walker(this);
return stack.each(function() {
var self = $(this);
if (options == 'destroy') {
tidy(self, 'ifDestroyed');
} else {
operate(self, true, options);
}
// Fire method's callback
if ($.isFunction(fire)) {
fire();
}
});
// Customization
} else if (typeof options == 'object' || !options) {
// Check if any options were passed
var settings = $.extend({
checkedClass: _checked,
disabledClass: _disabled,
indeterminateClass: _indeterminate,
labelHover: true
}, options),
selector = settings.handle,
hoverClass = settings.hoverClass || 'hover',
focusClass = settings.focusClass || 'focus',
activeClass = settings.activeClass || 'active',
labelHover = !!settings.labelHover,
labelHoverClass = settings.labelHoverClass || 'hover',
// Setup clickable area
area = ('' + settings.increaseArea).replace('%', '') | 0;
// Selector limit
if (selector == _checkbox || selector == _radio) {
handle = 'input[type="' + selector + '"]';
}
// Clickable area limit
if (area < -50) {
area = -50;
}
// Walk around the selector
walker(this);
return stack.each(function() {
var self = $(this);
// If already customized
tidy(self);
var node = this,
id = node.id,
// Layer styles
offset = -area + '%',
size = 100 + (area * 2) + '%',
layer = {
position: 'absolute',
top: offset,
left: offset,
display: 'block',
width: size,
height: size,
margin: 0,
padding: 0,
background: '#fff',
border: 0,
opacity: 0
},
// Choose how to hide input
hide = _mobile ? {
position: 'absolute',
visibility: 'hidden'
} : area ? layer : {
position: 'absolute',
opacity: 0
},
// Get proper class
className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio,
// Find assigned labels
label = $(_label + '[for="' + id + '"]').add(self.closest(_label)),
// Check ARIA option
aria = !!settings.aria,
// Set ARIA placeholder
ariaID = _iCheck + '-' + Math.random().toString(36).substr(2,6),
// Parent & helper
parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''),
helper;
// Set ARIA "labelledby"
if (aria) {
label.each(function() {
parent += 'aria-labelledby="';
if (this.id) {
parent += this.id;
} else {
this.id = ariaID;
parent += ariaID;
}
parent += '"';
});
}
// Wrap input
parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert);
// Layer addition
helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent);
// Finalize customization
self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide);
!!settings.inheritClass && parent[_add](node.className || '');
!!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id);
parent.css('position') == 'static' && parent.css('position', 'relative');
operate(self, true, _update);
// Label events
if (label.length) {
label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) {
var type = event[_type],
item = $(this);
// Do nothing if input is disabled
if (!node[_disabled]) {
// Click
if (type == _click) {
if ($(event.target).is('a')) {
return;
}
operate(self, false, true);
// Hover state
} else if (labelHover) {
// mouseout|touchend
if (/ut|nd/.test(type)) {
parent[_remove](hoverClass);
item[_remove](labelHoverClass);
} else {
parent[_add](hoverClass);
item[_add](labelHoverClass);
}
}
if (_mobile) {
event.stopPropagation();
} else {
return false;
}
}
});
}
// Input events
self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) {
var type = event[_type],
key = event.keyCode;
// Click
if (type == _click) {
return false;
// Keydown
} else if (type == 'keydown' && key == 32) {
if (!(node[_type] == _radio && node[_checked])) {
if (node[_checked]) {
off(self, _checked);
} else {
on(self, _checked);
}
}
return false;
// Keyup
} else if (type == 'keyup' && node[_type] == _radio) {
!node[_checked] && on(self, _checked);
// Focus/blur
} else if (/us|ur/.test(type)) {
parent[type == 'blur' ? _remove : _add](focusClass);
}
});
// Helper events
helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) {
var type = event[_type],
// mousedown|mouseup
toggle = /wn|up/.test(type) ? activeClass : hoverClass;
// Do nothing if input is disabled
if (!node[_disabled]) {
// Click
if (type == _click) {
operate(self, false, true);
// Active and hover states
} else {
// State is on
if (/wn|er|in/.test(type)) {
// mousedown|mouseover|touchbegin
parent[_add](toggle);
// State is off
} else {
parent[_remove](toggle + ' ' + activeClass);
}
// Label hover
if (label.length && labelHover && toggle == hoverClass) {
// mouseout|touchend
label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass);
}
}
if (_mobile) {
event.stopPropagation();
} else {
return false;
}
}
});
});
} else {
return this;
}
};
// Do something with inputs
function operate(input, direct, method) {
var node = input[0],
state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked,
active = method == _update ? {
checked: node[_checked],
disabled: node[_disabled],
indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false'
} : node[state];
// Check, disable or indeterminate
if (/^(ch|di|in)/.test(method) && !active) {
on(input, state);
// Uncheck, enable or determinate
} else if (/^(un|en|de)/.test(method) && active) {
off(input, state);
// Update
} else if (method == _update) {
// Handle states
for (var each in active) {
if (active[each]) {
on(input, each, true);
} else {
off(input, each, true);
}
}
} else if (!direct || method == 'toggle') {
// Helper or label was clicked
if (!direct) {
input[_callback]('ifClicked');
}
// Toggle checked state
if (active) {
if (node[_type] !== _radio) {
off(input, state);
}
} else {
on(input, state);
}
}
}
// Add checked, disabled or indeterminate state
function on(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== true) {
// Toggle assigned radio buttons
if (!keep && state == _checked && node[_type] == _radio && node.name) {
var form = input.closest('form'),
inputs = 'input[name="' + node.name + '"]';
inputs = form.length ? form.find(inputs) : $(inputs);
inputs.each(function() {
if (this !== node && $(this).data(_iCheck)) {
off($(this), state);
}
});
}
// Indeterminate state
if (indeterminate) {
// Add indeterminate state
node[state] = true;
// Remove checked state
if (node[_checked]) {
off(input, _checked, 'force');
}
// Checked or disabled state
} else {
// Add checked or disabled state
if (!keep) {
node[state] = true;
}
// Remove indeterminate state
if (checked && node[_indeterminate]) {
off(input, _indeterminate, false);
}
}
// Trigger callbacks
callbacks(input, checked, state, keep);
}
// Add proper cursor
if (node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'default');
}
// Add state class
parent[_add](specific || option(input, state) || '');
// Set ARIA attribute
if (!!parent.attr('role') && !indeterminate) {
parent.attr('aria-' + (disabled ? _disabled : _checked), 'true');
}
// Remove regular state class
parent[_remove](regular || option(input, callback) || '');
}
// Remove checked, disabled or indeterminate state
function off(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== false) {
// Toggle state
if (indeterminate || !keep || keep == 'force') {
node[state] = false;
}
// Trigger callbacks
callbacks(input, checked, callback, keep);
}
// Add proper cursor
if (!node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'pointer');
}
// Remove state class
parent[_remove](specific || option(input, state) || '');
// Set ARIA attribute
if (!!parent.attr('role') && !indeterminate) {
parent.attr('aria-' + (disabled ? _disabled : _checked), 'false');
}
// Add regular state class
parent[_add](regular || option(input, callback) || '');
}
// Remove all traces
function tidy(input, callback) {
if (input.data(_iCheck)) {
// Remove everything except input
input.parent().html(input.attr('style', input.data(_iCheck).s || ''));
// Callback
if (callback) {
input[_callback](callback);
}
// Unbind events
input.off('.i').unwrap();
$(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i');
}
}
// Get some option
function option(input, state, regular) {
if (input.data(_iCheck)) {
return input.data(_iCheck).o[state + (regular ? '' : 'Class')];
}
}
// Capitalize some string
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Executable handlers
function callbacks(input, checked, callback, keep) {
if (!keep) {
if (checked) {
input[_callback]('ifToggled');
}
input[_callback]('ifChanged')[_callback]('if' + capitalize(callback));
}
}
})(window.jQuery || window.Zepto);
|
/**
* @fileoverview Enforce no accesskey attribute on element.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import { getProp, getPropValue } from 'jsx-ast-utils';
import { generateObjSchema } from '../util/schemas';
const errorMessage = 'No access key attribute allowed. Inconsistencies ' +
'between keyboard shortcuts and keyboard comments used by screenreader ' +
'and keyboard only users create a11y complications.';
const schema = generateObjSchema();
module.exports = {
meta: {
docs: {},
schema: [schema],
},
create: context => ({
JSXOpeningElement: (node) => {
const accessKey = getProp(node.attributes, 'accesskey');
const accessKeyValue = getPropValue(accessKey);
if (accessKey && accessKeyValue) {
context.report({
node,
message: errorMessage,
});
}
},
}),
};
|
/**
* API Bound Models for AngularJS
* @version v1.1.6 - 2015-01-06
* @link https://github.com/angular-platanus/restmod
* @author Ignacio Baixas <ignacio@platan.us>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
!function(a){"use strict";a.module("restmod").factory("restmod.Preload",["restmod","$q",function(b,c){function d(a,b){for(var d=[],e=0;e<a.length;e++)d.push(a[e].$resolve(b).$asPromise());return c.all(d)}function e(b,e,f){for(var g,h=[],i=0,j=b.length;j>i;i++)g=b[i][e],a.isArray(g)?h.push.apply(h,g):g&&h.push(g);if(h.length>0){var k="function"==typeof h[0].$type.$populate?h[0].$type.$populate(h,f).$asPromise():d(h,f);if(k)return k.then(function(){return h})}return c.when(h)}function f(a,b){return function(c){return e(c,a,b)}}return b.mixin(function(){this.define("Resource.$preload",function(){var a=arguments;return this.$always(function(){for(var b,d,g,h,i={},j=[],k=this.$isCollection?this:[this],l=0;l<a.length;l++){var m,n=a[l];if("object"==typeof n&&(m=n.params,n=n.path),!i[n]){b="",n=n.split("."),h=null;for(var o=0;o<n.length;o++)d=n[o],g=b+"."+d,i[g]?h=i[g]:(h=h?h.then(f(d,m)):e(k,d,m),i[g]=h);j.push(h)}}return c.all(j)})})})}])}(angular);
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('element/locale/tr-TR', ['module', 'exports'], factory);
} else if (typeof exports !== "undefined") {
factory(module, exports);
} else {
var mod = {
exports: {}
};
factory(mod, mod.exports);
global.ELEMENT.lang = global.ELEMENT.lang || {};
global.ELEMENT.lang.trTR = mod.exports;
}
})(this, function (module, exports) {
'use strict';
exports.__esModule = true;
exports.default = {
el: {
colorpicker: {
confirm: 'OK',
clear: 'Temizle'
},
datepicker: {
now: 'Şimdi',
today: 'Bugün',
cancel: 'İptal',
clear: 'Temizle',
confirm: 'OK',
selectDate: 'Tarih seç',
selectTime: 'Saat seç',
startDate: 'Başlangıç Tarihi',
startTime: 'Başlangıç Saati',
endDate: 'Bitiş Tarihi',
endTime: 'Bitiş Saati',
year: '',
month1: 'Ocak',
month2: 'Şubat',
month3: 'Mart',
month4: 'Nisan',
month5: 'Mayıs',
month6: 'Haziran',
month7: 'Temmuz',
month8: 'Ağustos',
month9: 'Eylül',
month10: 'Ekim',
month11: 'Kasım',
month12: 'Aralık',
// week: 'week',
weeks: {
sun: 'Paz',
mon: 'Pzt',
tue: 'Sal',
wed: 'Çar',
thu: 'Per',
fri: 'Cum',
sat: 'Cmt'
},
months: {
jan: 'Oca',
feb: 'Şub',
mar: 'Mar',
apr: 'Nis',
may: 'May',
jun: 'Haz',
jul: 'Tem',
aug: 'Ağu',
sep: 'Eyl',
oct: 'Eki',
nov: 'Kas',
dec: 'Ara'
}
},
select: {
loading: 'Yükleniyor',
noMatch: 'Eşleşen veri bulunamadı',
noData: 'Veri yok',
placeholder: 'Seç'
},
cascader: {
noMatch: 'Eşleşen veri bulunamadı',
placeholder: 'Seç'
},
pagination: {
goto: 'Git',
pagesize: '/page',
total: 'Toplam {total}',
pageClassifier: ''
},
messagebox: {
title: 'Mesaj',
confirm: 'OK',
cancel: 'İptal',
error: 'İllegal giriş'
},
upload: {
delete: 'Sil',
preview: 'Görüntüle',
continue: 'Devam'
},
table: {
emptyText: 'Veri yok',
confirmFilter: 'Onayla',
resetFilter: 'Reset',
clearFilter: 'Hepsi',
sumText: 'Sum' // to be translated
},
tree: {
emptyText: 'Veri yok'
},
transfer: {
noMatch: 'Eşleşen veri bulunamadı',
noData: 'Veri yok',
titles: ['List 1', 'List 2'], // to be translated
filterPlaceholder: 'Enter keyword', // to be translated
noCheckedFormat: '{total} items', // to be translated
hasCheckedFormat: '{checked}/{total} checked' // to be translated
}
}
};
module.exports = exports['default'];
});
|
/*! UIkit 2.26.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
/*
* Based on Nestable jQuery Plugin - Copyright (c) 2012 David Bushell - http://dbushell.com/
*/
(function(addon) {
var component;
if (window.UIkit) {
component = addon(UIkit);
}
if (typeof define == "function" && define.amd) {
define("uikit-nestable", ["uikit"], function(){
return component || addon(UIkit);
});
}
})(function(UI) {
"use strict";
var hasTouch = 'ontouchstart' in window,
html = UI.$html,
touchedlists = [],
$win = UI.$win,
draggingElement;
var eStart = hasTouch ? 'touchstart' : 'mousedown',
eMove = hasTouch ? 'touchmove' : 'mousemove',
eEnd = hasTouch ? 'touchend' : 'mouseup',
eCancel = hasTouch ? 'touchcancel' : 'mouseup';
UI.component('nestable', {
defaults: {
listBaseClass : 'uk-nestable',
listClass : 'uk-nestable-list',
listItemClass : 'uk-nestable-item',
dragClass : 'uk-nestable-dragged',
movingClass : 'uk-nestable-moving',
noChildrenClass : 'uk-nestable-nochildren',
emptyClass : 'uk-nestable-empty',
handleClass : '',
collapsedClass : 'uk-collapsed',
placeholderClass: 'uk-nestable-placeholder',
noDragClass : 'uk-nestable-nodrag',
group : false,
maxDepth : 10,
threshold : 20,
idlethreshold : 10,
},
boot: function() {
// adjust document scrolling
UI.$html.on('mousemove touchmove', function(e) {
if (draggingElement) {
var top = draggingElement.offset().top;
if (top < UI.$win.scrollTop()) {
UI.$win.scrollTop(UI.$win.scrollTop() - Math.ceil(draggingElement.height()/2));
} else if ( (top + draggingElement.height()) > (window.innerHeight + UI.$win.scrollTop()) ) {
UI.$win.scrollTop(UI.$win.scrollTop() + Math.ceil(draggingElement.height()/2));
}
}
});
// init code
UI.ready(function(context) {
UI.$("[data-uk-nestable]", context).each(function(){
var ele = UI.$(this);
if (!ele.data("nestable")) {
UI.nestable(ele, UI.Utils.options(ele.attr("data-uk-nestable")));
}
});
});
},
init: function() {
var $this = this;
Object.keys(this.options).forEach(function(key){
if(String(key).indexOf('Class')!=-1) {
$this.options['_'+key] = '.' + $this.options[key];
}
});
this.find(this.options._listItemClass).find(">ul").addClass(this.options.listClass);
this.checkEmptyList();
this.reset();
this.element.data('nestable-group', this.options.group || UI.Utils.uid('nestable-group'));
this.find(this.options._listItemClass).each(function() {
$this.setParent(UI.$(this));
});
this.on('click', '[data-nestable-action]', function(e) {
if ($this.dragEl || (!hasTouch && e.button !== 0)) {
return;
}
e.preventDefault();
var target = UI.$(e.currentTarget),
action = target.data('nestableAction'),
item = target.closest($this.options._listItemClass);
if (action === 'collapse') {
$this.collapseItem(item);
}
if (action === 'expand') {
$this.expandItem(item);
}
if (action === 'toggle') {
$this.toggleItem(item);
}
});
var onStartEvent = function(e) {
var handle = UI.$(e.target);
if (e.target === $this.element[0]) {
return;
}
if (handle.is($this.options._noDragClass) || handle.closest($this.options._noDragClass).length) {
return;
}
if (handle.is('[data-nestable-action]') || handle.closest('[data-nestable-action]').length) {
return;
}
if ($this.options.handleClass && !handle.hasClass($this.options.handleClass)) {
if ($this.options.handleClass) {
handle = handle.closest($this.options._handleClass);
}
}
if (!handle.length || $this.dragEl || (!hasTouch && e.button !== 0) || (hasTouch && e.touches.length !== 1)) {
return;
}
if (e.originalEvent && e.originalEvent.touches) {
e = evt.originalEvent.touches[0];
}
$this.delayMove = function(evt) {
evt.preventDefault();
$this.dragStart(e);
$this.trigger('start.uk.nestable', [$this]);
$this.delayMove = false;
};
$this.delayMove.x = parseInt(e.pageX, 10);
$this.delayMove.y = parseInt(e.pageY, 10);
$this.delayMove.threshold = $this.options.idlethreshold;
e.preventDefault();
};
var onMoveEvent = function(e) {
if (e.originalEvent && e.originalEvent.touches) {
e = e.originalEvent.touches[0];
}
if ($this.delayMove && (Math.abs(e.pageX - $this.delayMove.x) > $this.delayMove.threshold || Math.abs(e.pageY - $this.delayMove.y) > $this.delayMove.threshold)) {
if (!window.getSelection().toString()) {
$this.delayMove(e);
} else {
$this.delayMove = false;
}
}
if ($this.dragEl) {
e.preventDefault();
$this.dragMove(e);
$this.trigger('move.uk.nestable', [$this]);
}
};
var onEndEvent = function(e) {
if ($this.dragEl) {
e.preventDefault();
$this.dragStop(hasTouch ? e.touches[0] : e);
}
draggingElement = false;
$this.delayMove = false;
};
if (hasTouch) {
this.element[0].addEventListener(eStart, onStartEvent, false);
window.addEventListener(eMove, onMoveEvent, false);
window.addEventListener(eEnd, onEndEvent, false);
window.addEventListener(eCancel, onEndEvent, false);
} else {
this.on(eStart, onStartEvent);
$win.on(eMove, onMoveEvent);
$win.on(eEnd, onEndEvent);
}
},
serialize: function() {
var data,
depth = 0,
list = this,
step = function(level, depth) {
var array = [ ], items = level.children(list.options._listItemClass);
items.each(function() {
var li = UI.$(this),
item = {}, attribute,
sub = li.children(list.options._listClass);
for (var i = 0, attr, val; i < li[0].attributes.length; i++) {
attribute = li[0].attributes[i];
if (attribute.name.indexOf('data-') === 0) {
attr = attribute.name.substr(5);
val = UI.Utils.str2json(attribute.value);
item[attr] = (val || attribute.value=='false' || attribute.value=='0') ? val:attribute.value;
}
}
if (sub.length) {
item.children = step(sub, depth + 1);
}
array.push(item);
});
return array;
};
data = step(list.element, depth);
return data;
},
list: function(options) {
var data = [],
list = this,
depth = 0,
step = function(level, depth, parent) {
var items = level.children(options._listItemClass);
items.each(function(index) {
var li = UI.$(this),
item = UI.$.extend({parent_id: (parent ? parent : null), depth: depth, order: index}, li.data()),
sub = li.children(options._listClass);
data.push(item);
if (sub.length) {
step(sub, depth + 1, li.data(options.idProperty || 'id'));
}
});
};
options = UI.$.extend({}, list.options, options);
step(list.element, depth);
return data;
},
reset: function() {
this.mouse = {
offsetX : 0,
offsetY : 0,
startX : 0,
startY : 0,
lastX : 0,
lastY : 0,
nowX : 0,
nowY : 0,
distX : 0,
distY : 0,
dirAx : 0,
dirX : 0,
dirY : 0,
lastDirX : 0,
lastDirY : 0,
distAxX : 0,
distAxY : 0
};
this.moving = false;
this.dragEl = null;
this.dragRootEl = null;
this.dragDepth = 0;
this.hasNewRoot = false;
this.pointEl = null;
for (var i=0; i<touchedlists.length; i++) {
this.checkEmptyList(touchedlists[i]);
}
touchedlists = [];
},
toggleItem: function(li) {
this[li.hasClass(this.options.collapsedClass) ? "expandItem":"collapseItem"](li);
},
expandItem: function(li) {
li.removeClass(this.options.collapsedClass);
},
collapseItem: function(li) {
var lists = li.children(this.options._listClass);
if (lists.length) {
li.addClass(this.options.collapsedClass);
}
},
expandAll: function() {
var list = this;
this.find(list.options._listItemClass).each(function() {
list.expandItem(UI.$(this));
});
},
collapseAll: function() {
var list = this;
this.find(list.options._listItemClass).each(function() {
list.collapseItem(UI.$(this));
});
},
setParent: function(li) {
if (li.children(this.options._listClass).length) {
li.addClass("uk-parent");
}
},
unsetParent: function(li) {
li.removeClass('uk-parent '+this.options.collapsedClass);
li.children(this.options._listClass).remove();
},
dragStart: function(e) {
var mouse = this.mouse,
target = UI.$(e.target),
dragItem = target.closest(this.options._listItemClass),
offset = dragItem.offset();
this.placeEl = dragItem;
mouse.offsetX = e.pageX - offset.left;
mouse.offsetY = e.pageY - offset.top;
mouse.startX = mouse.lastX = offset.left;
mouse.startY = mouse.lastY = offset.top;
this.dragRootEl = this.element;
this.dragEl = UI.$('<ul></ul>').addClass(this.options.listClass + ' ' + this.options.dragClass).append(dragItem.clone());
this.dragEl.css('width', dragItem.width());
this.placeEl.addClass(this.options.placeholderClass);
draggingElement = this.dragEl;
this.tmpDragOnSiblings = [dragItem[0].previousSibling, dragItem[0].nextSibling];
UI.$body.append(this.dragEl);
this.dragEl.css({
left : offset.left,
top : offset.top
});
// total depth of dragging item
var i, depth, items = this.dragEl.find(this.options._listItemClass);
for (i = 0; i < items.length; i++) {
depth = UI.$(items[i]).parents(this.options._listClass+','+this.options._listBaseClass).length;
if (depth > this.dragDepth) {
this.dragDepth = depth;
}
}
html.addClass(this.options.movingClass);
},
dragStop: function(e) {
var el = UI.$(this.placeEl),
root = this.placeEl.parents(this.options._listBaseClass+':first');
this.placeEl.removeClass(this.options.placeholderClass);
this.dragEl.remove();
if (this.element[0] !== root[0]) {
root.trigger('change.uk.nestable',[root.data('nestable'), el, 'added']);
this.element.trigger('change.uk.nestable', [this, el, 'removed']);
} else {
this.element.trigger('change.uk.nestable',[this, el, "moved"]);
}
this.trigger('stop.uk.nestable', [this, el]);
this.reset();
html.removeClass(this.options.movingClass);
},
dragMove: function(e) {
var list, parent, prev, next, depth,
opt = this.options,
mouse = this.mouse,
maxDepth = this.dragRootEl ? this.dragRootEl.data('nestable').options.maxDepth : opt.maxDepth;
this.dragEl.css({
left : e.pageX - mouse.offsetX,
top : e.pageY - mouse.offsetY
});
// mouse position last events
mouse.lastX = mouse.nowX;
mouse.lastY = mouse.nowY;
// mouse position this events
mouse.nowX = e.pageX;
mouse.nowY = e.pageY;
// distance mouse moved between events
mouse.distX = mouse.nowX - mouse.lastX;
mouse.distY = mouse.nowY - mouse.lastY;
// direction mouse was moving
mouse.lastDirX = mouse.dirX;
mouse.lastDirY = mouse.dirY;
// direction mouse is now moving (on both axis)
mouse.dirX = mouse.distX === 0 ? 0 : mouse.distX > 0 ? 1 : -1;
mouse.dirY = mouse.distY === 0 ? 0 : mouse.distY > 0 ? 1 : -1;
// axis mouse is now moving on
var newAx = Math.abs(mouse.distX) > Math.abs(mouse.distY) ? 1 : 0;
// do nothing on first move
if (!mouse.moving) {
mouse.dirAx = newAx;
mouse.moving = true;
return;
}
// calc distance moved on this axis (and direction)
if (mouse.dirAx !== newAx) {
mouse.distAxX = 0;
mouse.distAxY = 0;
} else {
mouse.distAxX += Math.abs(mouse.distX);
if (mouse.dirX !== 0 && mouse.dirX !== mouse.lastDirX) {
mouse.distAxX = 0;
}
mouse.distAxY += Math.abs(mouse.distY);
if (mouse.dirY !== 0 && mouse.dirY !== mouse.lastDirY) {
mouse.distAxY = 0;
}
}
mouse.dirAx = newAx;
/**
* move horizontal
*/
if (mouse.dirAx && mouse.distAxX >= opt.threshold) {
// reset move distance on x-axis for new phase
mouse.distAxX = 0;
prev = this.placeEl.prev('li');
// increase horizontal level if previous sibling exists, is not collapsed, and does not have a 'no children' class
if (mouse.distX > 0 && prev.length && !prev.hasClass(opt.collapsedClass) && !prev.hasClass(opt.noChildrenClass)) {
// cannot increase level when item above is collapsed
list = prev.find(opt._listClass).last();
// check if depth limit has reached
depth = this.placeEl.parents(opt._listClass+','+opt._listBaseClass).length;
if (depth + this.dragDepth <= maxDepth) {
// create new sub-level if one doesn't exist
if (!list.length) {
list = UI.$('<ul/>').addClass(opt.listClass);
list.append(this.placeEl);
prev.append(list);
this.setParent(prev);
} else {
// else append to next level up
list = prev.children(opt._listClass).last();
list.append(this.placeEl);
}
}
}
// decrease horizontal level
if (mouse.distX < 0) {
// we cannot decrease the level if an item precedes the current one
next = this.placeEl.next(opt._listItemClass);
if (!next.length) {
// get parent ul of the list item
var parentUl = this.placeEl.closest([opt._listBaseClass, opt._listClass].join(','));
// try to get the li surrounding the ul
var surroundingLi = parentUl.closest(opt._listItemClass);
// if the ul is inside of a li (meaning it is nested)
if (surroundingLi.length) {
// we can decrease the horizontal level
surroundingLi.after(this.placeEl);
// if the previous parent ul is now empty
if (!parentUl.children().length) {
this.unsetParent(surroundingLi);
}
}
}
}
}
var isEmpty = false;
// find list item under cursor
var pointX = e.pageX - (window.pageXOffset || document.scrollLeft || 0),
pointY = e.pageY - (window.pageYOffset || document.documentElement.scrollTop);
this.pointEl = UI.$(document.elementFromPoint(pointX, pointY));
if (opt.handleClass && this.pointEl.hasClass(opt.handleClass)) {
this.pointEl = this.pointEl.closest(opt._listItemClass);
} else {
var nestableitem = this.pointEl.closest(opt._listItemClass);
if (nestableitem.length) {
this.pointEl = nestableitem;
}
}
if (this.placeEl.find(this.pointEl).length) {
return;
}
if (this.pointEl.data('nestable') && !this.pointEl.children().length) {
isEmpty = true;
this.checkEmptyList(this.pointEl);
} else if (!this.pointEl.length || !this.pointEl.hasClass(opt.listItemClass)) {
return;
}
// find parent list of item under cursor
var pointElRoot = this.element,
tmpRoot = this.pointEl.closest(this.options._listBaseClass),
isNewRoot = pointElRoot[0] != tmpRoot[0];
/**
* move vertical
*/
if (!mouse.dirAx || isNewRoot || isEmpty) {
// check if groups match if dragging over new root
if (isNewRoot && opt.group !== tmpRoot.data('nestable-group')) {
return;
} else {
touchedlists.push(pointElRoot);
}
// check depth limit
depth = this.dragDepth - 1 + this.pointEl.parents(opt._listClass+','+opt._listBaseClass).length;
if (depth > maxDepth) {
return;
}
var before = e.pageY < (this.pointEl.offset().top + this.pointEl.height() / 2);
parent = this.placeEl.parent();
if (isEmpty) {
this.pointEl.append(this.placeEl);
} else if (before) {
this.pointEl.before(this.placeEl);
} else {
this.pointEl.after(this.placeEl);
}
if (!parent.children().length) {
if (!parent.data("nestable")) this.unsetParent(parent.parent());
}
this.checkEmptyList(this.dragRootEl);
this.checkEmptyList(pointElRoot);
// parent root list has changed
if (isNewRoot) {
this.dragRootEl = tmpRoot;
this.hasNewRoot = this.element[0] !== this.dragRootEl[0];
}
}
},
checkEmptyList: function(list) {
list = list ? UI.$(list) : this.element;
if (this.options.emptyClass) {
list[!list.children().length ? 'addClass':'removeClass'](this.options.emptyClass);
}
}
});
return UI.nestable;
});
|
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
LinkedInStrategy = require('passport-linkedin').Strategy,
config = require('../config'),
users = require('../../app/controllers/users.server.controller');
module.exports = function() {
// Use linkedin strategy
passport.use(new LinkedInStrategy({
consumerKey: config.linkedin.clientID,
consumerSecret: config.linkedin.clientSecret,
callbackURL: config.linkedin.callbackURL,
passReqToCallback: true,
profileFields: ['id', 'first-name', 'last-name', 'email-address']
},
function(req, accessToken, refreshToken, profile, done) {
// Set the provider data and include tokens
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
// Create the user OAuth profile
var providerUserProfile = {
firstName: profile.name.givenName,
lastName: profile.name.familyName,
displayName: profile.displayName,
email: profile.emails[0].value,
username: profile.username,
provider: 'linkedin',
providerIdentifierField: 'id',
providerData: providerData
};
// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}
));
};
|
function override(target, key, descriptor) {
descriptor.initializer = function () {
return "lol";
};
}
var obj = {
@override
foo: "bar",
bar: "heh"
};
assert.equal(obj.foo, "lol");
assert.equal(obj.bar, "heh");
|
function pug_escape(e) {
var a = "" + e, t = pug_match_html.exec(a);
if (!t) return e;
var r, c, n, s = "";
for (r = t.index, c = 0; r < a.length; r++) {
switch (a.charCodeAt(r)) {
case 34:
n = """;
break;
case 38:
n = "&";
break;
case 60:
n = "<";
break;
case 62:
n = ">";
break;
default:
continue;
}
c !== r && (s += a.substring(c, r)), c = r + 1, s += n;
}
return c !== r ? s + a.substring(c, r) : s;
}
var pug_match_html = /["&<>]/;
function template(locals) {
var pug_html = "", pug_mixins = {}, pug_interp;
pug_html = pug_html + "<html><body>";
var friends = 1;
switch (friends) {
case 0:
pug_html = pug_html + "<p>you have no friends</p>";
break;
case 1:
pug_html = pug_html + "<p>you have a friend</p>";
break;
default:
pug_html = pug_html + "<p>you have " + pug_escape(null == (pug_interp = friends) ? "" : pug_interp) + " friends</p>";
break;
}
pug_html = pug_html + "</body></html>";
return pug_html;
}
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'stylescombo', 'hr', {
label: 'Stil',
panelTitle: 'Stilovi formatiranja',
panelTitle1: 'Block stilovi',
panelTitle2: 'Inline stilovi',
panelTitle3: 'Object stilovi'
});
|
import {lineBreakG} from "./whitespace"
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
export class Position {
constructor(line, col) {
this.line = line
this.column = col
}
offset(n) {
return new Position(this.line, this.column + n)
}
}
export class SourceLocation {
constructor(p, start, end) {
this.start = start
this.end = end
if (p.sourceFile !== null) this.source = p.sourceFile
}
}
// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.
export function getLineInfo(input, offset) {
for (let line = 1, cur = 0;;) {
lineBreakG.lastIndex = cur
let match = lineBreakG.exec(input)
if (match && match.index < offset) {
++line
cur = match.index + match[0].length
} else {
return new Position(line, offset - cur)
}
}
}
|
/*!
* # Semantic UI 2.2.10 - Embed
* http://github.com/semantic-org/semantic-ui/
*
*
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
window = (typeof window != 'undefined' && window.Math == Math)
? window
: (typeof self != 'undefined' && self.Math == Math)
? self
: Function('return this')()
;
$.fn.embed = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.embed.settings, parameters)
: $.extend({}, $.fn.embed.settings),
selector = settings.selector,
className = settings.className,
sources = settings.sources,
error = settings.error,
metadata = settings.metadata,
namespace = settings.namespace,
templates = settings.templates,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$window = $(window),
$module = $(this),
$placeholder = $module.find(selector.placeholder),
$icon = $module.find(selector.icon),
$embed = $module.find(selector.embed),
element = this,
instance = $module.data(moduleNamespace),
module
;
module = {
initialize: function() {
module.debug('Initializing embed');
module.determine.autoplay();
module.create();
module.bind.events();
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous instance of embed');
module.reset();
$module
.removeData(moduleNamespace)
.off(eventNamespace)
;
},
refresh: function() {
module.verbose('Refreshing selector cache');
$placeholder = $module.find(selector.placeholder);
$icon = $module.find(selector.icon);
$embed = $module.find(selector.embed);
},
bind: {
events: function() {
if( module.has.placeholder() ) {
module.debug('Adding placeholder events');
$module
.on('click' + eventNamespace, selector.placeholder, module.createAndShow)
.on('click' + eventNamespace, selector.icon, module.createAndShow)
;
}
}
},
create: function() {
var
placeholder = module.get.placeholder()
;
if(placeholder) {
module.createPlaceholder();
}
else {
module.createAndShow();
}
},
createPlaceholder: function(placeholder) {
var
icon = module.get.icon(),
url = module.get.url(),
embed = module.generate.embed(url)
;
placeholder = placeholder || module.get.placeholder();
$module.html( templates.placeholder(placeholder, icon) );
module.debug('Creating placeholder for embed', placeholder, icon);
},
createEmbed: function(url) {
module.refresh();
url = url || module.get.url();
$embed = $('<div/>')
.addClass(className.embed)
.html( module.generate.embed(url) )
.appendTo($module)
;
settings.onCreate.call(element, url);
module.debug('Creating embed object', $embed);
},
changeEmbed: function(url) {
$embed
.html( module.generate.embed(url) )
;
},
createAndShow: function() {
module.createEmbed();
module.show();
},
// sets new embed
change: function(source, id, url) {
module.debug('Changing video to ', source, id, url);
$module
.data(metadata.source, source)
.data(metadata.id, id)
;
if(url) {
$module.data(metadata.url, url);
}
else {
$module.removeData(metadata.url);
}
if(module.has.embed()) {
module.changeEmbed();
}
else {
module.create();
}
},
// clears embed
reset: function() {
module.debug('Clearing embed and showing placeholder');
module.remove.active();
module.remove.embed();
module.showPlaceholder();
settings.onReset.call(element);
},
// shows current embed
show: function() {
module.debug('Showing embed');
module.set.active();
settings.onDisplay.call(element);
},
hide: function() {
module.debug('Hiding embed');
module.showPlaceholder();
},
showPlaceholder: function() {
module.debug('Showing placeholder image');
module.remove.active();
settings.onPlaceholderDisplay.call(element);
},
get: {
id: function() {
return settings.id || $module.data(metadata.id);
},
placeholder: function() {
return settings.placeholder || $module.data(metadata.placeholder);
},
icon: function() {
return (settings.icon)
? settings.icon
: ($module.data(metadata.icon) !== undefined)
? $module.data(metadata.icon)
: module.determine.icon()
;
},
source: function(url) {
return (settings.source)
? settings.source
: ($module.data(metadata.source) !== undefined)
? $module.data(metadata.source)
: module.determine.source()
;
},
type: function() {
var source = module.get.source();
return (sources[source] !== undefined)
? sources[source].type
: false
;
},
url: function() {
return (settings.url)
? settings.url
: ($module.data(metadata.url) !== undefined)
? $module.data(metadata.url)
: module.determine.url()
;
}
},
determine: {
autoplay: function() {
if(module.should.autoplay()) {
settings.autoplay = true;
}
},
source: function(url) {
var
matchedSource = false
;
url = url || module.get.url();
if(url) {
$.each(sources, function(name, source) {
if(url.search(source.domain) !== -1) {
matchedSource = name;
return false;
}
});
}
return matchedSource;
},
icon: function() {
var
source = module.get.source()
;
return (sources[source] !== undefined)
? sources[source].icon
: false
;
},
url: function() {
var
id = settings.id || $module.data(metadata.id),
source = settings.source || $module.data(metadata.source),
url
;
url = (sources[source] !== undefined)
? sources[source].url.replace('{id}', id)
: false
;
if(url) {
$module.data(metadata.url, url);
}
return url;
}
},
set: {
active: function() {
$module.addClass(className.active);
}
},
remove: {
active: function() {
$module.removeClass(className.active);
},
embed: function() {
$embed.empty();
}
},
encode: {
parameters: function(parameters) {
var
urlString = [],
index
;
for (index in parameters) {
urlString.push( encodeURIComponent(index) + '=' + encodeURIComponent( parameters[index] ) );
}
return urlString.join('&');
}
},
generate: {
embed: function(url) {
module.debug('Generating embed html');
var
source = module.get.source(),
html,
parameters
;
url = module.get.url(url);
if(url) {
parameters = module.generate.parameters(source);
html = templates.iframe(url, parameters);
}
else {
module.error(error.noURL, $module);
}
return html;
},
parameters: function(source, extraParameters) {
var
parameters = (sources[source] && sources[source].parameters !== undefined)
? sources[source].parameters(settings)
: {}
;
extraParameters = extraParameters || settings.parameters;
if(extraParameters) {
parameters = $.extend({}, parameters, extraParameters);
}
parameters = settings.onEmbed(parameters);
return module.encode.parameters(parameters);
}
},
has: {
embed: function() {
return ($embed.length > 0);
},
placeholder: function() {
return settings.placeholder || $module.data(metadata.placeholder);
}
},
should: {
autoplay: function() {
return (settings.autoplay === 'auto')
? (settings.placeholder || $module.data(metadata.placeholder) !== undefined)
: settings.autoplay
;
}
},
is: {
video: function() {
return module.get.type() == 'video';
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
if($.isPlainObject(settings[name])) {
$.extend(true, settings[name], value);
}
else {
settings[name] = value;
}
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(!settings.silent && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(!settings.silent && settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
if(!settings.silent) {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
}
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if($allModules.length > 1) {
title += ' ' + '(' + $allModules.length + ')';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.embed.settings = {
name : 'Embed',
namespace : 'embed',
silent : false,
debug : false,
verbose : false,
performance : true,
icon : false,
source : false,
url : false,
id : false,
// standard video settings
autoplay : 'auto',
color : '#444444',
hd : true,
brandedUI : false,
// additional parameters to include with the embed
parameters: false,
onDisplay : function() {},
onPlaceholderDisplay : function() {},
onReset : function() {},
onCreate : function(url) {},
onEmbed : function(parameters) {
return parameters;
},
metadata : {
id : 'id',
icon : 'icon',
placeholder : 'placeholder',
source : 'source',
url : 'url'
},
error : {
noURL : 'No URL specified',
method : 'The method you called is not defined'
},
className : {
active : 'active',
embed : 'embed'
},
selector : {
embed : '.embed',
placeholder : '.placeholder',
icon : '.icon'
},
sources: {
youtube: {
name : 'youtube',
type : 'video',
icon : 'video play',
domain : 'youtube.com',
url : '//www.youtube.com/embed/{id}',
parameters: function(settings) {
return {
autohide : !settings.brandedUI,
autoplay : settings.autoplay,
color : settings.color || undefined,
hq : settings.hd,
jsapi : settings.api,
modestbranding : !settings.brandedUI
};
}
},
vimeo: {
name : 'vimeo',
type : 'video',
icon : 'video play',
domain : 'vimeo.com',
url : '//player.vimeo.com/video/{id}',
parameters: function(settings) {
return {
api : settings.api,
autoplay : settings.autoplay,
byline : settings.brandedUI,
color : settings.color || undefined,
portrait : settings.brandedUI,
title : settings.brandedUI
};
}
}
},
templates: {
iframe : function(url, parameters) {
var src = url;
if (parameters) {
src += '?' + parameters;
}
return ''
+ '<iframe src="' + src + '"'
+ ' width="100%" height="100%"'
+ ' frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
},
placeholder : function(image, icon) {
var
html = ''
;
if(icon) {
html += '<i class="' + icon + ' icon"></i>';
}
if(image) {
html += '<img class="placeholder" src="' + image + '">';
}
return html;
}
},
// NOT YET IMPLEMENTED
api : false,
onPause : function() {},
onPlay : function() {},
onStop : function() {}
};
})( jQuery, window, document );
|
// We are not going to port this
|
module.exports['crlf.http'] = [
{type: 'file', name: 'upload', filename: 'plain.txt', fixture: 'plain.txt',
sha1: 'b31d07bac24ac32734de88b3687dddb10e976872'},
];
module.exports['preamble.http'] = [
{type: 'file', name: 'upload', filename: 'plain.txt', fixture: 'plain.txt',
sha1: 'b31d07bac24ac32734de88b3687dddb10e976872'},
];
|
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
var fs = require('fs');
var path = require('path');
var properties_parser = require('properties-parser');
var AndroidManifest = require('./AndroidManifest');
var AndroidStudio = require('./AndroidStudio');
var pluginHandlers = require('./pluginHandlers');
var projectFileCache = {};
function addToPropertyList(projectProperties, key, value) {
var i = 1;
while (projectProperties.get(key + '.' + i))
i++;
projectProperties.set(key + '.' + i, value);
projectProperties.dirty = true;
}
function removeFromPropertyList(projectProperties, key, value) {
var i = 1;
var currentValue;
while ((currentValue = projectProperties.get(key + '.' + i))) {
if (currentValue === value) {
while ((currentValue = projectProperties.get(key + '.' + (i + 1)))) {
projectProperties.set(key + '.' + i, currentValue);
i++;
}
projectProperties.set(key + '.' + i);
break;
}
i++;
}
projectProperties.dirty = true;
}
function getRelativeLibraryPath (parentDir, subDir) {
var libraryPath = path.relative(parentDir, subDir);
return (path.sep == '\\') ? libraryPath.replace(/\\/g, '/') : libraryPath;
}
function AndroidProject(projectDir) {
this._propertiesEditors = {};
this._subProjectDirs = {};
this._dirty = false;
this.projectDir = projectDir;
this.platformWww = path.join(this.projectDir, 'platform_www');
this.www = path.join(this.projectDir, 'assets/www');
if(AndroidStudio.isAndroidStudioProject(projectDir) === true) {
this.www = path.join(this.projectDir, 'app/src/main/assets/www');
}
}
AndroidProject.getProjectFile = function (projectDir) {
if (!projectFileCache[projectDir]) {
projectFileCache[projectDir] = new AndroidProject(projectDir);
}
return projectFileCache[projectDir];
};
AndroidProject.purgeCache = function (projectDir) {
if (projectDir) {
delete projectFileCache[projectDir];
} else {
projectFileCache = {};
}
};
/**
* Reads the package name out of the Android Manifest file
*
* @param {String} projectDir The absolute path to the directory containing the project
*
* @return {String} The name of the package
*/
AndroidProject.prototype.getPackageName = function() {
var manifestPath = path.join(this.projectDir, 'AndroidManifest.xml');
if(AndroidStudio.isAndroidStudioProject(this.projectDir) === true) {
manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');
}
return new AndroidManifest(manifestPath).getPackageId();
};
AndroidProject.prototype.getCustomSubprojectRelativeDir = function(plugin_id, src) {
// All custom subprojects are prefixed with the last portion of the package id.
// This is to avoid collisions when opening multiple projects in Eclipse that have subprojects with the same name.
var packageName = this.getPackageName();
var lastDotIndex = packageName.lastIndexOf('.');
var prefix = packageName.substring(lastDotIndex + 1);
var subRelativeDir = path.join(plugin_id, prefix + '-' + path.basename(src));
return subRelativeDir;
};
AndroidProject.prototype.addSubProject = function(parentDir, subDir) {
var parentProjectFile = path.resolve(parentDir, 'project.properties');
var subProjectFile = path.resolve(subDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile);
// TODO: Setting the target needs to happen only for pre-3.7.0 projects
if (fs.existsSync(subProjectFile)) {
var subProperties = this._getPropertiesFile(subProjectFile);
subProperties.set('target', parentProperties.get('target'));
subProperties.dirty = true;
this._subProjectDirs[subDir] = true;
}
addToPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));
this._dirty = true;
};
AndroidProject.prototype.removeSubProject = function(parentDir, subDir) {
var parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile);
removeFromPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));
delete this._subProjectDirs[subDir];
this._dirty = true;
};
AndroidProject.prototype.addGradleReference = function(parentDir, subDir) {
var parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile);
addToPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));
this._dirty = true;
};
AndroidProject.prototype.removeGradleReference = function(parentDir, subDir) {
var parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile);
removeFromPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));
this._dirty = true;
};
AndroidProject.prototype.addSystemLibrary = function(parentDir, value) {
var parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile);
addToPropertyList(parentProperties, 'cordova.system.library', value);
this._dirty = true;
};
AndroidProject.prototype.removeSystemLibrary = function(parentDir, value) {
var parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile);
removeFromPropertyList(parentProperties, 'cordova.system.library', value);
this._dirty = true;
};
AndroidProject.prototype.write = function() {
if (!this._dirty) {
return;
}
this._dirty = false;
for (var filename in this._propertiesEditors) {
var editor = this._propertiesEditors[filename];
if (editor.dirty) {
fs.writeFileSync(filename, editor.toString());
editor.dirty = false;
}
}
};
AndroidProject.prototype._getPropertiesFile = function (filename) {
if (!this._propertiesEditors[filename]) {
if (fs.existsSync(filename)) {
this._propertiesEditors[filename] = properties_parser.createEditor(filename);
} else {
this._propertiesEditors[filename] = properties_parser.createEditor();
}
}
return this._propertiesEditors[filename];
};
AndroidProject.prototype.getInstaller = function (type) {
return pluginHandlers.getInstaller(type);
};
AndroidProject.prototype.getUninstaller = function (type) {
return pluginHandlers.getUninstaller(type);
};
/*
* This checks if an Android project is clean or has old build artifacts
*/
AndroidProject.prototype.isClean = function() {
var build_path = path.join(this.projectDir, 'build');
//If the build directory doesn't exist, it's clean
return !(fs.existsSync(build_path));
};
module.exports = AndroidProject;
|
/*!
* TableSorter 2.7.12 - Client-side table sorting with ease!
* @requires jQuery v1.2.6+
*
* Copyright (c) 2007 Christian Bach
* Examples and docs at: http://tablesorter.com
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* @type jQuery
* @name tablesorter
* @cat Plugins/Tablesorter
* @author Christian Bach/christian.bach@polyester.se
* @contributor Rob Garrison/https://github.com/Mottie/tablesorter
*/
/*jshint browser:true, jquery:true, unused:false, expr: true */
/*global console:false, alert:false */
!(function($) {
"use strict";
$.extend({
/*jshint supernew:true */
tablesorter: new function() {
var ts = this;
ts.version = "2.7.12";
ts.parsers = [];
ts.widgets = [];
ts.defaults = {
// *** appearance
theme : 'default', // adds tablesorter-{theme} to the table for styling
widthFixed : false, // adds colgroup to fix widths of columns
showProcessing : false, // show an indeterminate timer icon in the header when the table is sorted or filtered.
headerTemplate : '{content}',// header layout template (HTML ok); {content} = innerHTML, {icon} = <i/> (class from cssIcon)
onRenderTemplate : null, // function(index, template){ return template; }, (template is a string)
onRenderHeader : null, // function(index){}, (nothing to return)
// *** functionality
cancelSelection : true, // prevent text selection in the header
dateFormat : 'mmddyyyy', // other options: "ddmmyyy" or "yyyymmdd"
sortMultiSortKey : 'shiftKey', // key used to select additional columns
sortResetKey : 'ctrlKey', // key used to remove sorting on a column
usNumberFormat : true, // false for German "1.234.567,89" or French "1 234 567,89"
delayInit : false, // if false, the parsed table contents will not update until the first sort
serverSideSorting: false, // if true, server-side sorting should be performed because client-side sorting will be disabled, but the ui and events will still be used.
// *** sort options
headers : {}, // set sorter, string, empty, locked order, sortInitialOrder, filter, etc.
ignoreCase : true, // ignore case while sorting
sortForce : null, // column(s) first sorted; always applied
sortList : [], // Initial sort order; applied initially; updated when manually sorted
sortAppend : null, // column(s) sorted last; always applied
sortInitialOrder : 'asc', // sort direction on first click
sortLocaleCompare: false, // replace equivalent character (accented characters)
sortReset : false, // third click on the header will reset column to default - unsorted
sortRestart : false, // restart sort to "sortInitialOrder" when clicking on previously unsorted columns
emptyTo : 'bottom', // sort empty cell to bottom, top, none, zero
stringTo : 'max', // sort strings in numerical column as max, min, top, bottom, zero
textExtraction : 'simple', // text extraction method/function - function(node, table, cellIndex){}
textSorter : null, // use custom text sorter - function(a,b){ return a.sort(b); } // basic sort
// *** widget options
widgets: [], // method to add widgets, e.g. widgets: ['zebra']
widgetOptions : {
zebra : [ 'even', 'odd' ] // zebra widget alternating row class names
},
initWidgets : true, // apply widgets on tablesorter initialization
// *** callbacks
initialized : null, // function(table){},
// *** css class names
tableClass : 'tablesorter',
cssAsc : 'tablesorter-headerAsc',
cssChildRow : 'tablesorter-childRow', // previously "expand-child"
cssDesc : 'tablesorter-headerDesc',
cssHeader : 'tablesorter-header',
cssHeaderRow : 'tablesorter-headerRow',
cssIcon : 'tablesorter-icon', // if this class exists, a <i> will be added to the header automatically
cssInfoBlock : 'tablesorter-infoOnly', // don't sort tbody with this class name
cssProcessing : 'tablesorter-processing', // processing icon applied to header during sort/filter
// *** selectors
selectorHeaders : '> thead th, > thead td',
selectorSort : 'th, td', // jQuery selector of content within selectorHeaders that is clickable to trigger a sort
selectorRemove : '.remove-me',
// *** advanced
debug : false,
// *** Internal variables
headerList: [],
empties: {},
strings: {},
parsers: []
// deprecated; but retained for backwards compatibility
// widgetZebra: { css: ["even", "odd"] }
};
/* debuging utils */
function log(s) {
if (typeof console !== "undefined" && typeof console.log !== "undefined") {
console.log(s);
} else {
alert(s);
}
}
function benchmark(s, d) {
log(s + " (" + (new Date().getTime() - d.getTime()) + "ms)");
}
ts.benchmark = benchmark;
function getElementText(table, node, cellIndex) {
if (!node) { return ""; }
var c = table.config,
t = c.textExtraction, text = "";
if (t === "simple") {
if (c.supportsTextContent) {
text = node.textContent; // newer browsers support this
} else {
text = $(node).text();
}
} else {
if (typeof(t) === "function") {
text = t(node, table, cellIndex);
} else if (typeof(t) === "object" && t.hasOwnProperty(cellIndex)) {
text = t[cellIndex](node, table, cellIndex);
} else {
text = c.supportsTextContent ? node.textContent : $(node).text();
}
}
return $.trim(text);
}
function detectParserForColumn(table, rows, rowIndex, cellIndex) {
var i, l = ts.parsers.length,
node = false,
nodeValue = '',
keepLooking = true;
while (nodeValue === '' && keepLooking) {
rowIndex++;
if (rows[rowIndex]) {
node = rows[rowIndex].cells[cellIndex];
nodeValue = getElementText(table, node, cellIndex);
if (table.config.debug) {
log('Checking if value was empty on row ' + rowIndex + ', column: ' + cellIndex + ': ' + nodeValue);
}
} else {
keepLooking = false;
}
}
for (i = 1; i < l; i++) {
if (ts.parsers[i].is && ts.parsers[i].is(nodeValue, table, node)) {
return ts.parsers[i];
}
}
// 0 is always the generic parser (text)
return ts.parsers[0];
}
function buildParserCache(table) {
var c = table.config,
// update table bodies in case we start with an empty table
tb = c.$tbodies = c.$table.children('tbody:not(.' + c.cssInfoBlock + ')'),
rows, list, l, i, h, ch, p, parsersDebug = "";
if ( tb.length === 0) {
return c.debug ? log('*Empty table!* Not building a parser cache') : '';
}
rows = tb[0].rows;
if (rows[0]) {
list = [];
l = rows[0].cells.length;
for (i = 0; i < l; i++) {
// tons of thanks to AnthonyM1229 for working out the following selector (issue #74) to make this work in IE8!
// More fixes to this selector to work properly in iOS and jQuery 1.8+ (issue #132 & #174)
h = c.$headers.filter(':not([colspan])');
h = h.add( c.$headers.filter('[colspan="1"]') ) // ie8 fix
.filter('[data-column="' + i + '"]:last');
ch = c.headers[i];
// get column parser
p = ts.getParserById( ts.getData(h, ch, 'sorter') );
// empty cells behaviour - keeping emptyToBottom for backwards compatibility
c.empties[i] = ts.getData(h, ch, 'empty') || c.emptyTo || (c.emptyToBottom ? 'bottom' : 'top' );
// text strings behaviour in numerical sorts
c.strings[i] = ts.getData(h, ch, 'string') || c.stringTo || 'max';
if (!p) {
p = detectParserForColumn(table, rows, -1, i);
}
if (c.debug) {
parsersDebug += "column:" + i + "; parser:" + p.id + "; string:" + c.strings[i] + '; empty: ' + c.empties[i] + "\n";
}
list.push(p);
}
}
if (c.debug) {
log(parsersDebug);
}
return list;
}
/* utils */
function buildCache(table) {
var b = table.tBodies,
tc = table.config,
totalRows,
totalCells,
parsers = tc.parsers,
t, v, i, j, k, c, cols, cacheTime, colMax = [];
tc.cache = {};
// if no parsers found, return - it's an empty table.
if (!parsers) {
return tc.debug ? log('*Empty table!* Not building a cache') : '';
}
if (tc.debug) {
cacheTime = new Date();
}
// processing icon
if (tc.showProcessing) {
ts.isProcessing(table, true);
}
for (k = 0; k < b.length; k++) {
tc.cache[k] = { row: [], normalized: [] };
// ignore tbodies with class name from css.cssInfoBlock
if (!$(b[k]).hasClass(tc.cssInfoBlock)) {
totalRows = (b[k] && b[k].rows.length) || 0;
totalCells = (b[k].rows[0] && b[k].rows[0].cells.length) || 0;
for (i = 0; i < totalRows; ++i) {
/** Add the table data to main data array */
c = $(b[k].rows[i]);
cols = [];
// if this is a child row, add it to the last row's children and continue to the next row
if (c.hasClass(tc.cssChildRow)) {
tc.cache[k].row[tc.cache[k].row.length - 1] = tc.cache[k].row[tc.cache[k].row.length - 1].add(c);
// go to the next for loop
continue;
}
tc.cache[k].row.push(c);
for (j = 0; j < totalCells; ++j) {
t = getElementText(table, c[0].cells[j], j);
// allow parsing if the string is empty, previously parsing would change it to zero,
// in case the parser needs to extract data from the table cell attributes
v = parsers[j].format(t, table, c[0].cells[j], j);
cols.push(v);
if ((parsers[j].type || '').toLowerCase() === "numeric") {
colMax[j] = Math.max(Math.abs(v), colMax[j] || 0); // determine column max value (ignore sign)
}
}
cols.push(tc.cache[k].normalized.length); // add position for rowCache
tc.cache[k].normalized.push(cols);
}
tc.cache[k].colMax = colMax;
}
}
if (tc.showProcessing) {
ts.isProcessing(table); // remove processing icon
}
if (tc.debug) {
benchmark("Building cache for " + totalRows + " rows", cacheTime);
}
}
// init flag (true) used by pager plugin to prevent widget application
function appendToTable(table, init) {
var c = table.config,
b = table.tBodies,
rows = [],
c2 = c.cache,
r, n, totalRows, checkCell, $bk, $tb,
i, j, k, l, pos, appendTime;
if (!c2[0]) { return; } // empty table - fixes #206
if (c.debug) {
appendTime = new Date();
}
for (k = 0; k < b.length; k++) {
$bk = $(b[k]);
if (!$bk.hasClass(c.cssInfoBlock)) {
// get tbody
$tb = ts.processTbody(table, $bk, true);
r = c2[k].row;
n = c2[k].normalized;
totalRows = n.length;
checkCell = totalRows ? (n[0].length - 1) : 0;
for (i = 0; i < totalRows; i++) {
pos = n[i][checkCell];
rows.push(r[pos]);
// removeRows used by the pager plugin
if (!c.appender || !c.removeRows) {
l = r[pos].length;
for (j = 0; j < l; j++) {
$tb.append(r[pos][j]);
}
}
}
// restore tbody
ts.processTbody(table, $tb, false);
}
}
if (c.appender) {
c.appender(table, rows);
}
if (c.debug) {
benchmark("Rebuilt table", appendTime);
}
// apply table widgets
if (!init) { ts.applyWidget(table); }
// trigger sortend
$(table).trigger("sortEnd", table);
}
// computeTableHeaderCellIndexes from:
// http://www.javascripttoolbox.com/lib/table/examples.php
// http://www.javascripttoolbox.com/temp/table_cellindex.html
function computeThIndexes(t) {
var matrix = [],
lookup = {},
cols = 0, // determine the number of columns
trs = $(t).find('thead:eq(0), tfoot').children('tr'), // children tr in tfoot - see issue #196
i, j, k, l, c, cells, rowIndex, cellId, rowSpan, colSpan, firstAvailCol, matrixrow;
for (i = 0; i < trs.length; i++) {
cells = trs[i].cells;
for (j = 0; j < cells.length; j++) {
c = cells[j];
rowIndex = c.parentNode.rowIndex;
cellId = rowIndex + "-" + c.cellIndex;
rowSpan = c.rowSpan || 1;
colSpan = c.colSpan || 1;
if (typeof(matrix[rowIndex]) === "undefined") {
matrix[rowIndex] = [];
}
// Find first available column in the first row
for (k = 0; k < matrix[rowIndex].length + 1; k++) {
if (typeof(matrix[rowIndex][k]) === "undefined") {
firstAvailCol = k;
break;
}
}
lookup[cellId] = firstAvailCol;
cols = Math.max(firstAvailCol, cols);
// add data-column
$(c).attr({ 'data-column' : firstAvailCol }); // 'data-row' : rowIndex
for (k = rowIndex; k < rowIndex + rowSpan; k++) {
if (typeof(matrix[k]) === "undefined") {
matrix[k] = [];
}
matrixrow = matrix[k];
for (l = firstAvailCol; l < firstAvailCol + colSpan; l++) {
matrixrow[l] = "x";
}
}
}
}
t.config.columns = cols; // may not be accurate if # header columns !== # tbody columns
return lookup;
}
function formatSortingOrder(v) {
// look for "d" in "desc" order; return true
return (/^d/i.test(v) || v === 1);
}
function buildHeaders(table) {
var header_index = computeThIndexes(table), ch, $t,
h, i, t, lock, time, $tableHeaders, c = table.config;
c.headerList = [], c.headerContent = [];
if (c.debug) {
time = new Date();
}
i = c.cssIcon ? '<i class="' + c.cssIcon + '"></i>' : ''; // add icon if cssIcon option exists
$tableHeaders = $(table).find(c.selectorHeaders).each(function(index) {
$t = $(this);
ch = c.headers[index];
c.headerContent[index] = this.innerHTML; // save original header content
// set up header template
t = c.headerTemplate.replace(/\{content\}/g, this.innerHTML).replace(/\{icon\}/g, i);
if (c.onRenderTemplate) {
h = c.onRenderTemplate.apply($t, [index, t]);
if (h && typeof h === 'string') { t = h; } // only change t if something is returned
}
this.innerHTML = '<div class="tablesorter-header-inner">' + t + '</div>'; // faster than wrapInner
if (c.onRenderHeader) { c.onRenderHeader.apply($t, [index]); }
this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex];
this.order = formatSortingOrder( ts.getData($t, ch, 'sortInitialOrder') || c.sortInitialOrder ) ? [1,0,2] : [0,1,2];
this.count = -1; // set to -1 because clicking on the header automatically adds one
if (ts.getData($t, ch, 'sorter') === 'false') {
this.sortDisabled = true;
$t.addClass('sorter-false');
} else {
$t.removeClass('sorter-false');
}
this.lockedOrder = false;
lock = ts.getData($t, ch, 'lockedOrder') || false;
if (typeof(lock) !== 'undefined' && lock !== false) {
this.order = this.lockedOrder = formatSortingOrder(lock) ? [1,1,1] : [0,0,0];
}
$t.addClass( (this.sortDisabled ? 'sorter-false ' : ' ') + c.cssHeader );
// add cell to headerList
c.headerList[index] = this;
// add to parent in case there are multiple rows
$t.parent().addClass(c.cssHeaderRow);
});
if (table.config.debug) {
benchmark("Built headers:", time);
log($tableHeaders);
}
return $tableHeaders;
}
function setHeadersCss(table) {
var f, i, j, l,
c = table.config,
list = c.sortList,
css = [c.cssAsc, c.cssDesc],
// find the footer
$t = $(table).find('tfoot tr').children().removeClass(css.join(' '));
// remove all header information
c.$headers.removeClass(css.join(' '));
l = list.length;
for (i = 0; i < l; i++) {
// direction = 2 means reset!
if (list[i][1] !== 2) {
// multicolumn sorting updating - choose the :last in case there are nested columns
f = c.$headers.not('.sorter-false').filter('[data-column="' + list[i][0] + '"]' + (l === 1 ? ':last' : '') );
if (f.length) {
for (j = 0; j < f.length; j++) {
if (!f[j].sortDisabled) {
f.eq(j).addClass(css[list[i][1]]);
// add sorted class to footer, if it exists
if ($t.length) {
$t.filter('[data-column="' + list[i][0] + '"]').eq(j).addClass(css[list[i][1]]);
}
}
}
}
}
}
}
// automatically add col group, and column sizes if set
function fixColumnWidth(table) {
if (table.config.widthFixed && $(table).find('colgroup').length === 0) {
var colgroup = $('<colgroup>'),
overallWidth = $(table).width();
$(table.tBodies[0]).find("tr:first").children("td").each(function() {
colgroup.append($('<col>').css('width', parseInt(($(this).width()/overallWidth)*1000, 10)/10 + '%'));
});
$(table).prepend(colgroup);
}
}
function updateHeaderSortCount(table, list) {
var s, t, o, c = table.config,
sl = list || c.sortList;
c.sortList = [];
$.each(sl, function(i,v){
// ensure all sortList values are numeric - fixes #127
s = [ parseInt(v[0], 10), parseInt(v[1], 10) ];
// make sure header exists
o = c.headerList[s[0]];
if (o) { // prevents error if sorton array is wrong
c.sortList.push(s);
t = $.inArray(s[1], o.order); // fixes issue #167
o.count = t >= 0 ? t : s[1] % (c.sortReset ? 3 : 2);
}
});
}
function getCachedSortType(parsers, i) {
return (parsers && parsers[i]) ? parsers[i].type || '' : '';
}
// sort multiple columns
function multisort(table) { /*jshint loopfunc:true */
var dynamicExp, sortWrapper, col, mx = 0, dir = 0, tc = table.config,
sortList = tc.sortList, l = sortList.length, bl = table.tBodies.length,
sortTime, i, j, k, c, colMax, cache, lc, s, e, order, orgOrderCol;
if (tc.serverSideSorting || !tc.cache[0]) { // empty table - fixes #206
return;
}
if (tc.debug) { sortTime = new Date(); }
for (k = 0; k < bl; k++) {
colMax = tc.cache[k].colMax;
cache = tc.cache[k].normalized;
lc = cache.length;
orgOrderCol = (cache && cache[0]) ? cache[0].length - 1 : 0;
cache.sort(function(a, b) {
// cache is undefined here in IE, so don't use it!
for (i = 0; i < l; i++) {
c = sortList[i][0];
order = sortList[i][1];
// fallback to natural sort since it is more robust
s = /n/i.test(getCachedSortType(tc.parsers, c)) ? "Numeric" : "Text";
s += order === 0 ? "" : "Desc";
if (/Numeric/.test(s) && tc.strings[c]) {
// sort strings in numerical columns
if (typeof (tc.string[tc.strings[c]]) === 'boolean') {
dir = (order === 0 ? 1 : -1) * (tc.string[tc.strings[c]] ? -1 : 1);
} else {
dir = (tc.strings[c]) ? tc.string[tc.strings[c]] || 0 : 0;
}
}
var sort = $.tablesorter["sort" + s](table, a[c], b[c], c, colMax[c], dir);
if (sort) { return sort; }
}
return a[orgOrderCol] - b[orgOrderCol];
});
}
if (tc.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time", sortTime); }
}
function resortComplete($table, callback){
$table.trigger('updateComplete');
if (typeof callback === "function") {
callback($table[0]);
}
}
function checkResort($table, flag, callback) {
if (flag !== false) {
$table.trigger("sorton", [$table[0].config.sortList, function(){
resortComplete($table, callback);
}]);
} else {
resortComplete($table, callback);
}
}
/* public methods */
ts.construct = function(settings) {
return this.each(function() {
// if no thead or tbody, or tablesorter is already present, quit
if (!this.tHead || this.tBodies.length === 0 || this.hasInitialized === true) {
return (this.config && this.config.debug) ? log('stopping initialization! No thead, tbody or tablesorter has already been initialized') : '';
}
// declare
var $cell, $this = $(this), $t0 = this,
c, i, j, k = '', a, s, o, downTime,
m = $.metadata;
// initialization flag
$t0.hasInitialized = false;
// new blank config object
$t0.config = {};
// merge and extend
c = $.extend(true, $t0.config, ts.defaults, settings);
// save the settings where they read
$.data($t0, "tablesorter", c);
if (c.debug) { $.data( $t0, 'startoveralltimer', new Date()); }
// constants
c.supportsTextContent = $('<span>x</span>')[0].textContent === 'x';
c.supportsDataObject = parseFloat($.fn.jquery) >= 1.4;
// digit sort text location; keeping max+/- for backwards compatibility
c.string = { 'max': 1, 'min': -1, 'max+': 1, 'max-': -1, 'zero': 0, 'none': 0, 'null': 0, 'top': true, 'bottom': false };
// add table theme class only if there isn't already one there
if (!/tablesorter\-/.test($this.attr('class'))) {
k = (c.theme !== '' ? ' tablesorter-' + c.theme : '');
}
c.$table = $this.addClass(c.tableClass + k);
c.$tbodies = $this.children('tbody:not(.' + c.cssInfoBlock + ')');
// build headers
c.$headers = buildHeaders($t0);
// fixate columns if the users supplies the fixedWidth option
// do this after theme has been applied
fixColumnWidth($t0);
// try to auto detect column type, and store in tables config
c.parsers = buildParserCache($t0);
// build the cache for the tbody cells
// delayInit will delay building the cache until the user starts a sort
if (!c.delayInit) { buildCache($t0); }
// apply event handling to headers
// this is to big, perhaps break it out?
c.$headers
// http://stackoverflow.com/questions/5312849/jquery-find-self; andSelf() deprecated in jQuery 1.8
.find('*')[ $.fn.addBack ? 'addBack': 'andSelf' ]().filter(c.selectorSort)
.unbind('mousedown.tablesorter mouseup.tablesorter')
.bind('mousedown.tablesorter mouseup.tablesorter', function(e, external) {
// jQuery v1.2.6 doesn't have closest()
var $cell = this.tagName.match('TH|TD') ? $(this) : $(this).parents('th, td').filter(':last'), cell = $cell[0];
// only recognize left clicks
if ((e.which || e.button) !== 1) { return false; }
// set timer on mousedown
if (e.type === 'mousedown') {
downTime = new Date().getTime();
return e.target.tagName === "INPUT" ? '' : !c.cancelSelection;
}
// ignore long clicks (prevents resizable widget from initializing a sort)
if (external !== true && (new Date().getTime() - downTime > 250)) { return false; }
if (c.delayInit && !c.cache) { buildCache($t0); }
if (!cell.sortDisabled) {
// Only call sortStart if sorting is enabled
$this.trigger("sortStart", $t0);
// store exp, for speed
// $cell = $(this);
k = !e[c.sortMultiSortKey];
// get current column sort order
cell.count = e[c.sortResetKey] ? 2 : (cell.count + 1) % (c.sortReset ? 3 : 2);
// reset all sorts on non-current column - issue #30
if (c.sortRestart) {
i = cell;
c.$headers.each(function() {
// only reset counts on columns that weren't just clicked on and if not included in a multisort
if (this !== i && (k || !$(this).is('.' + c.cssDesc + ',.' + c.cssAsc))) {
this.count = -1;
}
});
}
// get current column index
i = cell.column;
// user only wants to sort on one column
if (k) {
// flush the sort list
c.sortList = [];
if (c.sortForce !== null) {
a = c.sortForce;
for (j = 0; j < a.length; j++) {
if (a[j][0] !== i) {
c.sortList.push(a[j]);
}
}
}
// add column to sort list
o = cell.order[cell.count];
if (o < 2) {
c.sortList.push([i, o]);
// add other columns if header spans across multiple
if (cell.colSpan > 1) {
for (j = 1; j < cell.colSpan; j++) {
c.sortList.push([i + j, o]);
}
}
}
// multi column sorting
} else {
// get rid of the sortAppend before adding more - fixes issue #115
if (c.sortAppend && c.sortList.length > 1) {
if (ts.isValueInArray(c.sortAppend[0][0], c.sortList)) {
c.sortList.pop();
}
}
// the user has clicked on an already sorted column
if (ts.isValueInArray(i, c.sortList)) {
// reverse the sorting direction for all tables
for (j = 0; j < c.sortList.length; j++) {
s = c.sortList[j];
o = c.headerList[s[0]];
if (s[0] === i) {
s[1] = o.order[o.count];
if (s[1] === 2) {
c.sortList.splice(j,1);
o.count = -1;
}
}
}
} else {
// add column to sort list array
o = cell.order[cell.count];
if (o < 2) {
c.sortList.push([i, o]);
// add other columns if header spans across multiple
if (cell.colSpan > 1) {
for (j = 1; j < cell.colSpan; j++) {
c.sortList.push([i + j, o]);
}
}
}
}
}
if (c.sortAppend !== null) {
a = c.sortAppend;
for (j = 0; j < a.length; j++) {
if (a[j][0] !== i) {
c.sortList.push(a[j]);
}
}
}
// sortBegin event triggered immediately before the sort
$this.trigger("sortBegin", $t0);
// setTimeout needed so the processing icon shows up
setTimeout(function(){
// set css for headers
setHeadersCss($t0);
multisort($t0);
appendToTable($t0);
}, 1);
}
});
if (c.cancelSelection) {
// cancel selection
c.$headers.each(function() {
this.onselectstart = function() {
return false;
};
});
}
// apply easy methods that trigger boundd events
$this
.unbind('sortReset update updateCell addRows sorton appendCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave '.split(' ').join('.tablesorter '))
.bind("sortReset.tablesorter", function(){
c.sortList = [];
setHeadersCss($t0);
multisort($t0);
appendToTable($t0);
})
.bind("update.tablesorter updateRows.tablesorter", function(e, resort, callback) {
// remove rows/elements before update
$this.find(c.selectorRemove).remove();
// rebuild parsers
c.parsers = buildParserCache($t0);
// rebuild the cache map
buildCache($t0);
checkResort($this, resort, callback);
})
.bind("updateCell.tablesorter", function(e, cell, resort, callback) {
$this.find(c.selectorRemove).remove();
// get position from the dom
var l, row, icell,
$tb = $this.find('tbody'),
// update cache - format: function(s, table, cell, cellIndex)
// no closest in jQuery v1.2.6 - tbdy = $tb.index( $(cell).closest('tbody') ),$row = $(cell).closest('tr');
tbdy = $tb.index( $(cell).parents('tbody').filter(':last') ),
$row = $(cell).parents('tr').filter(':last');
cell = $(cell)[0]; // in case cell is a jQuery object
// tbody may not exist if update is initialized while tbody is removed for processing
if ($tb.length && tbdy >= 0) {
row = $tb.eq(tbdy).find('tr').index( $row );
icell = cell.cellIndex;
l = c.cache[tbdy].normalized[row].length - 1;
c.cache[tbdy].row[$t0.config.cache[tbdy].normalized[row][l]] = $row;
c.cache[tbdy].normalized[row][icell] = c.parsers[icell].format( getElementText($t0, cell, icell), $t0, cell, icell );
checkResort($this, resort, callback);
}
})
.bind("addRows.tablesorter", function(e, $row, resort, callback) {
var i, rows = $row.filter('tr').length,
dat = [], l = $row[0].cells.length,
tbdy = $this.find('tbody').index( $row.closest('tbody') );
// fixes adding rows to an empty table - see issue #179
if (!c.parsers) {
c.parsers = buildParserCache($t0);
}
// add each row
for (i = 0; i < rows; i++) {
// add each cell
for (j = 0; j < l; j++) {
dat[j] = c.parsers[j].format( getElementText($t0, $row[i].cells[j], j), $t0, $row[i].cells[j], j );
}
// add the row index to the end
dat.push(c.cache[tbdy].row.length);
// update cache
c.cache[tbdy].row.push([$row[i]]);
c.cache[tbdy].normalized.push(dat);
dat = [];
}
// resort using current settings
checkResort($this, resort, callback);
})
.bind("sorton.tablesorter", function(e, list, callback, init) {
$this.trigger("sortStart", this);
// update header count index
updateHeaderSortCount($t0, list);
// set css for headers
setHeadersCss($t0);
// sort the table and append it to the dom
multisort($t0);
appendToTable($t0, init);
if (typeof callback === "function") {
callback($t0);
}
})
.bind("appendCache.tablesorter", function(e, callback, init) {
appendToTable($t0, init);
if (typeof callback === "function") {
callback($t0);
}
})
.bind("applyWidgetId.tablesorter", function(e, id) {
ts.getWidgetById(id).format($t0, c, c.widgetOptions);
})
.bind("applyWidgets.tablesorter", function(e, init) {
// apply widgets
ts.applyWidget($t0, init);
})
.bind("refreshWidgets.tablesorter", function(e, all, dontapply){
ts.refreshWidgets($t0, all, dontapply);
})
.bind("destroy.tablesorter", function(e, c, cb){
ts.destroy($t0, c, cb);
});
// get sort list from jQuery data or metadata
// in jQuery < 1.4, an error occurs when calling $this.data()
if (c.supportsDataObject && typeof $this.data().sortlist !== 'undefined') {
c.sortList = $this.data().sortlist;
} else if (m && ($this.metadata() && $this.metadata().sortlist)) {
c.sortList = $this.metadata().sortlist;
}
// apply widget init code
ts.applyWidget($t0, true);
// if user has supplied a sort list to constructor
if (c.sortList.length > 0) {
$this.trigger("sorton", [c.sortList, {}, !c.initWidgets]);
} else if (c.initWidgets) {
// apply widget format
ts.applyWidget($t0);
}
// show processesing icon
if (c.showProcessing) {
$this
.unbind('sortBegin.tablesorter sortEnd.tablesorter')
.bind('sortBegin.tablesorter sortEnd.tablesorter', function(e) {
ts.isProcessing($t0, e.type === 'sortBegin');
});
}
// initialized
$t0.hasInitialized = true;
if (c.debug) {
ts.benchmark("Overall initialization time", $.data( $t0, 'startoveralltimer'));
}
$this.trigger('tablesorter-initialized', $t0);
if (typeof c.initialized === 'function') { c.initialized($t0); }
});
};
// *** Process table ***
// add processing indicator
ts.isProcessing = function(table, toggle, $ths) {
var c = table.config,
// default to all headers
$h = $ths || $(table).find('.' + c.cssHeader);
if (toggle) {
if (c.sortList.length > 0) {
// get headers from the sortList
$h = $h.filter(function(){
// get data-column from attr to keep compatibility with jQuery 1.2.6
return this.sortDisabled ? false : ts.isValueInArray( parseFloat($(this).attr('data-column')), c.sortList);
});
}
$h.addClass(c.cssProcessing);
} else {
$h.removeClass(c.cssProcessing);
}
};
// detach tbody but save the position
// don't use tbody because there are portions that look for a tbody index (updateCell)
ts.processTbody = function(table, $tb, getIt){
var t, holdr;
if (getIt) {
$tb.before('<span class="tablesorter-savemyplace"/>');
holdr = ($.fn.detach) ? $tb.detach() : $tb.remove();
return holdr;
}
holdr = $(table).find('span.tablesorter-savemyplace');
$tb.insertAfter( holdr );
holdr.remove();
};
ts.clearTableBody = function(table) {
table.config.$tbodies.empty();
};
ts.destroy = function(table, removeClasses, callback){
if (!table.hasInitialized) { return; }
// remove all widgets
ts.refreshWidgets(table, true, true);
var $t = $(table), c = table.config,
$h = $t.find('thead:first'),
$r = $h.find('tr.' + c.cssHeaderRow).removeClass(c.cssHeaderRow),
$f = $t.find('tfoot:first > tr').children('th, td');
// remove widget added rows, just in case
$h.find('tr').not($r).remove();
// disable tablesorter
$t
.removeData('tablesorter')
.unbind('sortReset update updateCell addRows sorton appendCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave sortBegin sortEnd '.split(' ').join('.tablesorter '));
c.$headers.add($f)
.removeClass(c.cssHeader + ' ' + c.cssAsc + ' ' + c.cssDesc)
.removeAttr('data-column');
$r.find(c.selectorSort).unbind('mousedown.tablesorter mouseup.tablesorter');
// restore headers
$r.children().each(function(i){
$(this).html( c.headerContent[i] );
});
if (removeClasses !== false) {
$t.removeClass(c.tableClass + ' tablesorter-' + c.theme);
}
// clear flag in case the plugin is initialized again
table.hasInitialized = false;
if (typeof callback === 'function') {
callback(table);
}
};
// *** sort functions ***
// regex used in natural sort
ts.regex = [
/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, // chunk/tokenize numbers & letters
/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, //date
/^0x[0-9a-f]+$/i // hex
];
// Natural sort - https://github.com/overset/javascript-natural-sort
ts.sortText = function(table, a, b, col) {
if (a === b) { return 0; }
var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ],
r = ts.regex, xN, xD, yN, yD, xF, yF, i, mx;
if (a === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? -1 : 1) : -e || -1; }
if (b === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? 1 : -1) : e || 1; }
if (typeof c.textSorter === 'function') { return c.textSorter(a, b, table, col); }
// chunk/tokenize
xN = a.replace(r[0], '\\0$1\\0').replace(/\\0$/, '').replace(/^\\0/, '').split('\\0');
yN = b.replace(r[0], '\\0$1\\0').replace(/\\0$/, '').replace(/^\\0/, '').split('\\0');
// numeric, hex or date detection
xD = parseInt(a.match(r[2]),16) || (xN.length !== 1 && a.match(r[1]) && Date.parse(a));
yD = parseInt(b.match(r[2]),16) || (xD && b.match(r[1]) && Date.parse(b)) || null;
// first try and sort Hex codes or Dates
if (yD) {
if ( xD < yD ) { return -1; }
if ( xD > yD ) { return 1; }
}
mx = Math.max(xN.length, yN.length);
// natural sorting through split numeric strings and default strings
for (i = 0; i < mx; i++) {
// find floats not starting with '0', string or 0 if not defined
xF = isNaN(xN[i]) ? xN[i] || 0 : parseFloat(xN[i]) || 0;
yF = isNaN(yN[i]) ? yN[i] || 0 : parseFloat(yN[i]) || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(xF) !== isNaN(yF)) { return (isNaN(xF)) ? 1 : -1; }
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
if (typeof xF !== typeof yF) {
xF += '';
yF += '';
}
if (xF < yF) { return -1; }
if (xF > yF) { return 1; }
}
return 0;
};
ts.sortTextDesc = function(table, a, b, col) {
if (a === b) { return 0; }
var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? -1 : 1) : e || 1; }
if (b === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? 1 : -1) : -e || -1; }
if (typeof c.textSorter === 'function') { return c.textSorter(b, a, table, col); }
return ts.sortText(table, b, a);
};
// return text string value by adding up ascii value
// so the text is somewhat sorted when using a digital sort
// this is NOT an alphanumeric sort
ts.getTextValue = function(a, mx, d) {
if (mx) {
// make sure the text value is greater than the max numerical value (mx)
var i, l = a ? a.length : 0, n = mx + d;
for (i = 0; i < l; i++) {
n += a.charCodeAt(i);
}
return d * n;
}
return 0;
};
ts.sortNumeric = function(table, a, b, col, mx, d) {
if (a === b) { return 0; }
var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? -1 : 1) : -e || -1; }
if (b === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? 1 : -1) : e || 1; }
if (isNaN(a)) { a = ts.getTextValue(a, mx, d); }
if (isNaN(b)) { b = ts.getTextValue(b, mx, d); }
return a - b;
};
ts.sortNumericDesc = function(table, a, b, col, mx, d) {
if (a === b) { return 0; }
var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? -1 : 1) : e || 1; }
if (b === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? 1 : -1) : -e || -1; }
if (isNaN(a)) { a = ts.getTextValue(a, mx, d); }
if (isNaN(b)) { b = ts.getTextValue(b, mx, d); }
return b - a;
};
// used when replacing accented characters during sorting
ts.characterEquivalents = {
"a" : "\u00e1\u00e0\u00e2\u00e3\u00e4\u0105\u00e5", // áàâãäąå
"A" : "\u00c1\u00c0\u00c2\u00c3\u00c4\u0104\u00c5", // ÁÀÂÃÄĄÅ
"c" : "\u00e7\u0107\u010d", // çćč
"C" : "\u00c7\u0106\u010c", // ÇĆČ
"e" : "\u00e9\u00e8\u00ea\u00eb\u011b\u0119", // éèêëěę
"E" : "\u00c9\u00c8\u00ca\u00cb\u011a\u0118", // ÉÈÊËĚĘ
"i" : "\u00ed\u00ec\u0130\u00ee\u00ef\u0131", // íìİîïı
"I" : "\u00cd\u00cc\u0130\u00ce\u00cf", // ÍÌİÎÏ
"o" : "\u00f3\u00f2\u00f4\u00f5\u00f6", // óòôõö
"O" : "\u00d3\u00d2\u00d4\u00d5\u00d6", // ÓÒÔÕÖ
"ss": "\u00df", // ß (s sharp)
"SS": "\u1e9e", // ẞ (Capital sharp s)
"u" : "\u00fa\u00f9\u00fb\u00fc\u016f", // úùûüů
"U" : "\u00da\u00d9\u00db\u00dc\u016e" // ÚÙÛÜŮ
};
ts.replaceAccents = function(s) {
var a, acc = '[', eq = ts.characterEquivalents;
if (!ts.characterRegex) {
ts.characterRegexArray = {};
for (a in eq) {
if (typeof a === 'string') {
acc += eq[a];
ts.characterRegexArray[a] = new RegExp('[' + eq[a] + ']', 'g');
}
}
ts.characterRegex = new RegExp(acc + ']');
}
if (ts.characterRegex.test(s)) {
for (a in eq) {
if (typeof a === 'string') {
s = s.replace( ts.characterRegexArray[a], a );
}
}
}
return s;
};
// *** utilities ***
ts.isValueInArray = function(v, a) {
var i, l = a.length;
for (i = 0; i < l; i++) {
if (a[i][0] === v) {
return true;
}
}
return false;
};
ts.addParser = function(parser) {
var i, l = ts.parsers.length, a = true;
for (i = 0; i < l; i++) {
if (ts.parsers[i].id.toLowerCase() === parser.id.toLowerCase()) {
a = false;
}
}
if (a) {
ts.parsers.push(parser);
}
};
ts.getParserById = function(name) {
var i, l = ts.parsers.length;
for (i = 0; i < l; i++) {
if (ts.parsers[i].id.toLowerCase() === (name.toString()).toLowerCase()) {
return ts.parsers[i];
}
}
return false;
};
ts.addWidget = function(widget) {
ts.widgets.push(widget);
};
ts.getWidgetById = function(name) {
var i, w, l = ts.widgets.length;
for (i = 0; i < l; i++) {
w = ts.widgets[i];
if (w && w.hasOwnProperty('id') && w.id.toLowerCase() === name.toLowerCase()) {
return w;
}
}
};
ts.applyWidget = function(table, init) {
var c = table.config,
wo = c.widgetOptions,
ws = c.widgets.sort().reverse(), // ensure that widgets are always applied in a certain order
time, i, w, l = ws.length;
// make zebra last
i = $.inArray('zebra', c.widgets);
if (i >= 0) {
c.widgets.splice(i,1);
c.widgets.push('zebra');
}
if (c.debug) {
time = new Date();
}
// add selected widgets
for (i = 0; i < l; i++) {
w = ts.getWidgetById(ws[i]);
if ( w ) {
if (init === true && w.hasOwnProperty('init')) {
w.init(table, w, c, wo);
} else if (!init && w.hasOwnProperty('format')) {
w.format(table, c, wo);
}
}
}
if (c.debug) {
benchmark("Completed " + (init === true ? "initializing" : "applying") + " widgets", time);
}
};
ts.refreshWidgets = function(table, doAll, dontapply) {
var i, c = table.config,
cw = c.widgets,
w = ts.widgets, l = w.length;
// remove previous widgets
for (i = 0; i < l; i++){
if ( w[i] && w[i].id && (doAll || $.inArray( w[i].id, cw ) < 0) ) {
if (c.debug) { log( 'Refeshing widgets: Removing ' + w[i].id ); }
if (w[i].hasOwnProperty('remove')) { w[i].remove(table, c, c.widgetOptions); }
}
}
if (dontapply !== true) {
ts.applyWidget(table, doAll);
}
};
// get sorter, string, empty, etc options for each column from
// jQuery data, metadata, header option or header class name ("sorter-false")
// priority = jQuery data > meta > headers option > header class name
ts.getData = function(h, ch, key) {
var val = '', $h = $(h), m, cl;
if (!$h.length) { return ''; }
m = $.metadata ? $h.metadata() : false;
cl = ' ' + ($h.attr('class') || '');
if (typeof $h.data(key) !== 'undefined' || typeof $h.data(key.toLowerCase()) !== 'undefined'){
// "data-lockedOrder" is assigned to "lockedorder"; but "data-locked-order" is assigned to "lockedOrder"
// "data-sort-initial-order" is assigned to "sortInitialOrder"
val += $h.data(key) || $h.data(key.toLowerCase());
} else if (m && typeof m[key] !== 'undefined') {
val += m[key];
} else if (ch && typeof ch[key] !== 'undefined') {
val += ch[key];
} else if (cl !== ' ' && cl.match(' ' + key + '-')) {
// include sorter class name "sorter-text", etc
val = cl.match( new RegExp(' ' + key + '-(\\w+)') )[1] || '';
}
return $.trim(val);
};
ts.formatFloat = function(s, table) {
if (typeof(s) !== 'string' || s === '') { return s; }
// allow using formatFloat without a table; defaults to US number format
var i,
t = table && table.config ? table.config.usNumberFormat !== false :
typeof table !== "undefined" ? table : true;
if (t) {
// US Format - 1,234,567.89 -> 1234567.89
s = s.replace(/,/g,'');
} else {
// German Format = 1.234.567,89 -> 1234567.89
// French Format = 1 234 567,89 -> 1234567.89
s = s.replace(/[\s|\.]/g,'').replace(/,/g,'.');
}
if(/^\s*\([.\d]+\)/.test(s)) {
// make (#) into a negative number -> (10) = -10
s = s.replace(/^\s*\(/,'-').replace(/\)/,'');
}
i = parseFloat(s);
// return the text instead of zero
return isNaN(i) ? $.trim(s) : i;
};
ts.isDigit = function(s) {
// replace all unwanted chars and match
return isNaN(s) ? (/^[\-+(]?\d+[)]?$/).test(s.toString().replace(/[,.'"\s]/g, '')) : true;
};
}()
});
// make shortcut
var ts = $.tablesorter;
// extend plugin scope
$.fn.extend({
tablesorter: ts.construct
});
// add default parsers
ts.addParser({
id: "text",
is: function(s, table, node) {
return true;
},
format: function(s, table, cell, cellIndex) {
var c = table.config;
s = $.trim( c.ignoreCase ? s.toLocaleLowerCase() : s );
return c.sortLocaleCompare ? ts.replaceAccents(s) : s;
},
type: "text"
});
ts.addParser({
id: "currency",
is: function(s) {
return (/^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/).test((s || '').replace(/[,. ]/g,'')); // £$€¤¥¢
},
format: function(s, table) {
return ts.formatFloat(s.replace(/[^\w,. \-()]/g, ""), table);
},
type: "numeric"
});
ts.addParser({
id: "ipAddress",
is: function(s) {
return (/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/).test(s);
},
format: function(s, table) {
var i, a = s.split("."),
r = "",
l = a.length;
for (i = 0; i < l; i++) {
r += ("00" + a[i]).slice(-3);
}
return ts.formatFloat(r, table);
},
type: "numeric"
});
ts.addParser({
id: "url",
is: function(s) {
return (/^(https?|ftp|file):\/\//).test(s);
},
format: function(s) {
return $.trim(s.replace(/(https?|ftp|file):\/\//, ''));
},
type: "text"
});
ts.addParser({
id: "isoDate",
is: function(s) {
return (/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/).test(s);
},
format: function(s, table) {
return ts.formatFloat((s !== "") ? (new Date(s.replace(/-/g, "/")).getTime() || "") : "", table);
},
type: "numeric"
});
ts.addParser({
id: "percent",
is: function(s) {
return (/(\d\s?%|%\s?\d)/).test(s);
},
format: function(s, table) {
return ts.formatFloat(s.replace(/%/g, ""), table);
},
type: "numeric"
});
ts.addParser({
id: "usLongDate",
is: function(s) {
// two digit years are not allowed cross-browser
// Jan 01, 2013 12:34:56 PM or 01 Jan 2013
return (/^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i).test(s) || (/^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i).test(s);
},
format: function(s, table) {
return ts.formatFloat( (new Date(s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || ''), table);
},
type: "numeric"
});
ts.addParser({
id: "shortDate", // "mmddyyyy", "ddmmyyyy" or "yyyymmdd"
is: function(s) {
// testing for ####-##-####, so it's not perfect
return (/^(\d{1,2}|\d{4})[\/\-\,\.\s+]\d{1,2}[\/\-\.\,\s+](\d{1,2}|\d{4})$/).test(s);
},
format: function(s, table, cell, cellIndex) {
var c = table.config, ci = c.headerList[cellIndex],
format = ci.shortDateFormat;
if (typeof format === 'undefined') {
// cache header formatting so it doesn't getData for every cell in the column
format = ci.shortDateFormat = ts.getData( ci, c.headers[cellIndex], 'dateFormat') || c.dateFormat;
}
s = s.replace(/\s+/g," ").replace(/[\-|\.|\,]/g, "/");
if (format === "mmddyyyy") {
s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$1/$2");
} else if (format === "ddmmyyyy") {
s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$2/$1");
} else if (format === "yyyymmdd") {
s = s.replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/, "$1/$2/$3");
}
return ts.formatFloat( (new Date(s).getTime() || ''), table);
},
type: "numeric"
});
ts.addParser({
id: "time",
is: function(s) {
return (/^(([0-2]?\d:[0-5]\d)|([0-1]?\d:[0-5]\d\s?([AP]M)))$/i).test(s);
},
format: function(s, table) {
return ts.formatFloat( (new Date("2000/01/01 " + s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || ""), table);
},
type: "numeric"
});
ts.addParser({
id: "digit",
is: function(s) {
return ts.isDigit(s);
},
format: function(s, table) {
return ts.formatFloat(s.replace(/[^\w,. \-()]/g, ""), table);
},
type: "numeric"
});
ts.addParser({
id: "metadata",
is: function(s) {
return false;
},
format: function(s, table, cell) {
var c = table.config,
p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
return $(cell).metadata()[p];
},
type: "numeric"
});
// add default widgets
ts.addWidget({
id: "zebra",
format: function(table, c, wo) {
var $tb, $tv, $tr, row, even, time, k, l,
child = new RegExp(c.cssChildRow, 'i'),
b = c.$tbodies;
if (c.debug) {
time = new Date();
}
for (k = 0; k < b.length; k++ ) {
// loop through the visible rows
$tb = b.eq(k);
l = $tb.children('tr').length;
if (l > 1) {
row = 0;
$tv = $tb.children('tr:visible');
// revered back to using jQuery each - strangely it's the fastest method
/*jshint loopfunc:true */
$tv.each(function(){
$tr = $(this);
// style children rows the same way the parent row was styled
if (!child.test(this.className)) { row++; }
even = (row % 2 === 0);
$tr.removeClass(wo.zebra[even ? 1 : 0]).addClass(wo.zebra[even ? 0 : 1]);
});
}
}
if (c.debug) {
ts.benchmark("Applying Zebra widget", time);
}
},
remove: function(table, c, wo){
var k, $tb,
b = c.$tbodies,
rmv = (c.widgetOptions.zebra || [ "even", "odd" ]).join(' ');
for (k = 0; k < b.length; k++ ){
$tb = $.tablesorter.processTbody(table, b.eq(k), true); // remove tbody
$tb.children().removeClass(rmv);
$.tablesorter.processTbody(table, $tb, false); // restore tbody
}
}
});
})(jQuery);
|
/*!
Autosize 1.18.16
license: MIT
http://www.jacklmoore.com/autosize
*/
(function ($) {
var
defaults = {
className: 'autosizejs',
id: 'autosizejs',
append: '\n',
callback: false,
resizeDelay: 10,
placeholder: true
},
// border:0 is unnecessary, but avoids a bug in Firefox on OSX
copy = '<textarea tabindex="-1" style="position:absolute; top:-999px; left:0; right:auto; bottom:auto; border:0; padding: 0; -moz-box-sizing:content-box; -webkit-box-sizing:content-box; box-sizing:content-box; word-wrap:break-word; height:0 !important; min-height:0 !important; overflow:hidden; transition:none; -webkit-transition:none; -moz-transition:none;"/>',
// line-height is conditionally included because IE7/IE8/old Opera do not return the correct value.
typographyStyles = [
'fontFamily',
'fontSize',
'fontWeight',
'fontStyle',
'letterSpacing',
'textTransform',
'wordSpacing',
'textIndent',
'whiteSpace'
],
// to keep track which textarea is being mirrored when adjust() is called.
mirrored,
// the mirror element, which is used to calculate what size the mirrored element should be.
mirror = $(copy).data('autosize', true)[0];
// test that line-height can be accurately copied.
mirror.style.lineHeight = '99px';
if ($(mirror).css('lineHeight') === '99px') {
typographyStyles.push('lineHeight');
}
mirror.style.lineHeight = '';
$.fn.autosize = function (options) {
if (!this.length) {
return this;
}
options = $.extend({}, defaults, options || {});
if (mirror.parentNode !== document.body) {
$(document.body).append(mirror);
}
return this.each(function () {
var
ta = this,
$ta = $(ta),
maxHeight,
minHeight,
boxOffset = 0,
callback = $.isFunction(options.callback),
originalStyles = {
height: ta.style.height,
overflow: ta.style.overflow,
overflowY: ta.style.overflowY,
wordWrap: ta.style.wordWrap,
resize: ta.style.resize
},
timeout,
width = $ta.width(),
taResize = $ta.css('resize');
if ($ta.data('autosize')) {
// exit if autosize has already been applied, or if the textarea is the mirror element.
return;
}
$ta.data('autosize', true);
if ($ta.css('box-sizing') === 'border-box' || $ta.css('-moz-box-sizing') === 'border-box' || $ta.css('-webkit-box-sizing') === 'border-box'){
boxOffset = $ta.outerHeight() - $ta.height();
}
// IE8 and lower return 'auto', which parses to NaN, if no min-height is set.
minHeight = Math.max(parseFloat($ta.css('minHeight')) - boxOffset || 0, $ta.height());
$ta.css({
overflow: 'hidden',
overflowY: 'hidden',
wordWrap: 'break-word' // horizontal overflow is hidden, so break-word is necessary for handling words longer than the textarea width
});
if (taResize === 'vertical') {
$ta.css('resize','none');
} else if (taResize === 'both') {
$ta.css('resize', 'horizontal');
}
// The mirror width must exactly match the textarea width, so using getBoundingClientRect because it doesn't round the sub-pixel value.
// window.getComputedStyle, getBoundingClientRect returning a width are unsupported, but also unneeded in IE8 and lower.
function setWidth() {
var width;
var style = window.getComputedStyle ? window.getComputedStyle(ta, null) : false;
if (style) {
width = ta.getBoundingClientRect().width;
if (width === 0 || typeof width !== 'number') {
width = parseFloat(style.width);
}
$.each(['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'], function(i,val){
width -= parseFloat(style[val]);
});
} else {
width = $ta.width();
}
mirror.style.width = Math.max(width,0) + 'px';
}
function initMirror() {
var styles = {};
mirrored = ta;
mirror.className = options.className;
mirror.id = options.id;
maxHeight = parseFloat($ta.css('maxHeight'));
// mirror is a duplicate textarea located off-screen that
// is automatically updated to contain the same text as the
// original textarea. mirror always has a height of 0.
// This gives a cross-browser supported way getting the actual
// height of the text, through the scrollTop property.
$.each(typographyStyles, function(i,val){
styles[val] = $ta.css(val);
});
$(mirror).css(styles).attr('wrap', $ta.attr('wrap'));
setWidth();
// Chrome-specific fix:
// When the textarea y-overflow is hidden, Chrome doesn't reflow the text to account for the space
// made available by removing the scrollbar. This workaround triggers the reflow for Chrome.
if (window.chrome) {
var width = ta.style.width;
ta.style.width = '0px';
var ignore = ta.offsetWidth;
ta.style.width = width;
}
}
// Using mainly bare JS in this function because it is going
// to fire very often while typing, and needs to very efficient.
function adjust() {
var height, originalHeight;
if (mirrored !== ta) {
initMirror();
} else {
setWidth();
}
if (!ta.value && options.placeholder) {
// If the textarea is empty, copy the placeholder text into
// the mirror control and use that for sizing so that we
// don't end up with placeholder getting trimmed.
mirror.value = ($ta.attr("placeholder") || '');
} else {
mirror.value = ta.value;
}
mirror.value += options.append || '';
mirror.style.overflowY = ta.style.overflowY;
originalHeight = parseFloat(ta.style.height) || 0;
// Setting scrollTop to zero is needed in IE8 and lower for the next step to be accurately applied
mirror.scrollTop = 0;
mirror.scrollTop = 9e4;
// Using scrollTop rather than scrollHeight because scrollHeight is non-standard and includes padding.
height = mirror.scrollTop;
if (maxHeight && height > maxHeight) {
ta.style.overflowY = 'scroll';
height = maxHeight;
} else {
ta.style.overflowY = 'hidden';
if (height < minHeight) {
height = minHeight;
}
}
height += boxOffset;
if (Math.abs(originalHeight - height) > 1/100) {
ta.style.height = height + 'px';
// Trigger a repaint for IE8 for when ta is nested 2 or more levels inside an inline-block
mirror.className = mirror.className;
if (callback) {
options.callback.call(ta,ta);
}
$ta.trigger('autosize.resized');
}
}
function resize () {
clearTimeout(timeout);
timeout = setTimeout(function(){
var newWidth = $ta.width();
if (newWidth !== width) {
width = newWidth;
adjust();
}
}, parseInt(options.resizeDelay,10));
}
if ('onpropertychange' in ta) {
if ('oninput' in ta) {
// Detects IE9. IE9 does not fire onpropertychange or oninput for deletions,
// so binding to onkeyup to catch most of those occasions. There is no way that I
// know of to detect something like 'cut' in IE9.
$ta.on('input.autosize keyup.autosize', adjust);
} else {
// IE7 / IE8
$ta.on('propertychange.autosize', function(){
if(event.propertyName === 'value'){
adjust();
}
});
}
} else {
// Modern Browsers
$ta.on('input.autosize', adjust);
}
// Set options.resizeDelay to false if using fixed-width textarea elements.
// Uses a timeout and width check to reduce the amount of times adjust needs to be called after window resize.
if (options.resizeDelay !== false) {
$(window).on('resize.autosize', resize);
}
// Event for manual triggering if needed.
// Should only be needed when the value of the textarea is changed through JavaScript rather than user input.
$ta.on('autosize.resize', adjust);
// Event for manual triggering that also forces the styles to update as well.
// Should only be needed if one of typography styles of the textarea change, and the textarea is already the target of the adjust method.
$ta.on('autosize.resizeIncludeStyle', function() {
mirrored = null;
adjust();
});
$ta.on('autosize.destroy', function(){
mirrored = null;
clearTimeout(timeout);
$(window).off('resize', resize);
$ta
.off('autosize')
.off('.autosize')
.css(originalStyles)
.removeData('autosize');
});
// Call adjust in case the textarea already contains text.
adjust();
});
};
}(jQuery || $)); // jQuery or jQuery-like library, such as Zepto
|
YUI.add('content-editable', function (Y, NAME) {
/*jshint maxlen: 500 */
/**
* Creates a component to work with an elemment.
* @class ContentEditable
* @for ContentEditable
* @extends Y.Plugin.Base
* @constructor
* @module editor
* @submodule content-editable
*/
var Lang = Y.Lang,
YNode = Y.Node,
EVENT_CONTENT_READY = 'contentready',
EVENT_READY = 'ready',
TAG_PARAGRAPH = 'p',
BLUR = 'blur',
CONTAINER = 'container',
CONTENT_EDITABLE = 'contentEditable',
EMPTY = '',
FOCUS = 'focus',
HOST = 'host',
INNER_HTML = 'innerHTML',
KEY = 'key',
PARENT_NODE = 'parentNode',
PASTE = 'paste',
TEXT = 'Text',
USE = 'use',
ContentEditable = function() {
ContentEditable.superclass.constructor.apply(this, arguments);
};
Y.extend(ContentEditable, Y.Plugin.Base, {
/**
* Internal reference set when render is called.
* @private
* @property _rendered
* @type Boolean
*/
_rendered: null,
/**
* Internal reference to the YUI instance bound to the element
* @private
* @property _instance
* @type YUI
*/
_instance: null,
/**
* Initializes the ContentEditable instance
* @protected
* @method initializer
*/
initializer: function() {
var host = this.get(HOST);
if (host) {
host.frame = this;
}
this._eventHandles = [];
this.publish(EVENT_READY, {
emitFacade: true,
defaultFn: this._defReadyFn
});
},
/**
* Destroys the instance.
* @protected
* @method destructor
*/
destructor: function() {
new Y.EventHandle(this._eventHandles).detach();
this._container.removeAttribute(CONTENT_EDITABLE);
},
/**
* Generic handler for all DOM events fired by the Editor container. This handler
* takes the current EventFacade and augments it to fire on the ContentEditable host. It adds two new properties
* to the EventFacade called frameX and frameY which adds the scroll and xy position of the ContentEditable element
* to the original pageX and pageY of the event so external nodes can be positioned over the element.
* In case of ContentEditable element these will be equal to pageX and pageY of the container.
* @private
* @method _onDomEvent
* @param {Event.Facade} e
*/
_onDomEvent: function(e) {
var xy;
e.frameX = e.frameY = 0;
if (e.pageX > 0 || e.pageY > 0) {
if (e.type.substring(0, 3) !== KEY) {
xy = this._container.getXY();
e.frameX = xy[0];
e.frameY = xy[1];
}
}
e.frameTarget = e.target;
e.frameCurrentTarget = e.currentTarget;
e.frameEvent = e;
this.fire('dom:' + e.type, e);
},
/**
* Simple pass thru handler for the paste event so we can do content cleanup
* @private
* @method _DOMPaste
* @param {Event.Facade} e
*/
_DOMPaste: function(e) {
var inst = this.getInstance(),
data = EMPTY, win = inst.config.win;
if (e._event.originalTarget) {
data = e._event.originalTarget;
}
if (e._event.clipboardData) {
data = e._event.clipboardData.getData(TEXT);
}
if (win.clipboardData) {
data = win.clipboardData.getData(TEXT);
if (data === EMPTY) { // Could be empty, or failed
// Verify failure
if (!win.clipboardData.setData(TEXT, data)) {
data = null;
}
}
}
e.frameTarget = e.target;
e.frameCurrentTarget = e.currentTarget;
e.frameEvent = e;
if (data) {
e.clipboardData = {
data: data,
getData: function() {
return data;
}
};
} else {
e.clipboardData = null;
}
this.fire('dom:paste', e);
},
/**
* Binds DOM events and fires the ready event
* @private
* @method _defReadyFn
*/
_defReadyFn: function() {
var inst = this.getInstance(),
container = this.get(CONTAINER);
Y.each(
ContentEditable.DOM_EVENTS,
function(value, key) {
var fn = Y.bind(this._onDomEvent, this),
kfn = ((Y.UA.ie && ContentEditable.THROTTLE_TIME > 0) ? Y.throttle(fn, ContentEditable.THROTTLE_TIME) : fn);
if (!inst.Node.DOM_EVENTS[key]) {
inst.Node.DOM_EVENTS[key] = 1;
}
if (value === 1) {
if (key !== FOCUS && key !== BLUR && key !== PASTE) {
if (key.substring(0, 3) === KEY) {
//Throttle key events in IE
this._eventHandles.push(container.on(key, kfn, container));
} else {
this._eventHandles.push(container.on(key, fn, container));
}
}
}
},
this
);
inst.Node.DOM_EVENTS.paste = 1;
this._eventHandles.push(
container.on(PASTE, Y.bind(this._DOMPaste, this), container),
container.on(FOCUS, Y.bind(this._onDomEvent, this), container),
container.on(BLUR, Y.bind(this._onDomEvent, this), container)
);
inst.__use = inst.use;
inst.use = Y.bind(this.use, this);
},
/**
* Called once the content is available in the ContentEditable element and calls the final use call
* @private
* @method _onContentReady
* on the internal instance so that the modules are loaded properly.
*/
_onContentReady: function(event) {
if (!this._ready) {
this._ready = true;
var inst = this.getInstance(),
args = Y.clone(this.get(USE));
this.fire(EVENT_CONTENT_READY);
if (event) {
inst.config.doc = YNode.getDOMNode(event.target);
}
args.push(Y.bind(function() {
if (inst.EditorSelection) {
inst.EditorSelection.DEFAULT_BLOCK_TAG = this.get('defaultblock');
inst.EditorSelection.ROOT = this.get(CONTAINER);
}
this.fire(EVENT_READY);
}, this));
inst.use.apply(inst, args);
}
},
/**
* Retrieves defaultblock value from host attribute
* @private
* @method _getDefaultBlock
* @return {String}
*/
_getDefaultBlock: function() {
return this._getHostValue('defaultblock');
},
/**
* Retrieves dir value from host attribute
* @private
* @method _getDir
* @return {String}
*/
_getDir: function() {
return this._getHostValue('dir');
},
/**
* Retrieves extracss value from host attribute
* @private
* @method _getExtraCSS
* @return {String}
*/
_getExtraCSS: function() {
return this._getHostValue('extracss');
},
/**
* Get the content from the container
* @private
* @method _getHTML
* @param {String} html The raw HTML from the container.
* @return {String}
*/
_getHTML: function() {
var html, container;
if (this._ready) {
container = this.get(CONTAINER);
html = container.get(INNER_HTML);
}
return html;
},
/**
* Retrieves a value from host attribute
* @private
* @method _getHostValue
* @param {attr} The attribute which value should be returned from the host
* @return {String|Object}
*/
_getHostValue: function(attr) {
var host = this.get(HOST);
if (host) {
return host.get(attr);
}
},
/**
* Set the content of the container
* @private
* @method _setHTML
* @param {String} html The raw HTML to set to the container.
* @return {String}
*/
_setHTML: function(html) {
if (this._ready) {
var container = this.get(CONTAINER);
container.set(INNER_HTML, html);
} else {
//This needs to be wrapped in a contentready callback for the !_ready state
this.once(EVENT_CONTENT_READY, Y.bind(this._setHTML, this, html));
}
return html;
},
/**
* Set's the linked CSS on the instance.
* @private
* @method _setLinkedCSS
* @param {css} String The linkedcss value
* @return {String}
*/
_setLinkedCSS: function(css) {
if (this._ready) {
var inst = this.getInstance();
inst.Get.css(css);
} else {
//This needs to be wrapped in a contentready callback for the !_ready state
this.once(EVENT_CONTENT_READY, Y.bind(this._setLinkedCSS, this, css));
}
return css;
},
/**
* Set's the dir (language direction) attribute on the container.
* @private
* @method _setDir
* @param {value} String The language direction
* @return {String}
*/
_setDir: function(value) {
var container;
if (this._ready) {
container = this.get(CONTAINER);
container.setAttribute('dir', value);
} else {
//This needs to be wrapped in a contentready callback for the !_ready state
this.once(EVENT_CONTENT_READY, Y.bind(this._setDir, this, value));
}
return value;
},
/**
* Set's the extra CSS on the instance.
* @private
* @method _setExtraCSS
* @param {css} String The CSS style to be set as extra css
* @return {String}
*/
_setExtraCSS: function(css) {
if (this._ready) {
if (css) {
var inst = this.getInstance(),
head = inst.one('head');
if (this._extraCSSNode) {
this._extraCSSNode.remove();
}
this._extraCSSNode = YNode.create('<style>' + css + '</style>');
head.append(this._extraCSSNode);
}
} else {
//This needs to be wrapped in a contentready callback for the !_ready state
this.once(EVENT_CONTENT_READY, Y.bind(this._setExtraCSS, this, css));
}
return css;
},
/**
* Set's the language value on the instance.
* @private
* @method _setLang
* @param {value} String The language to be set
* @return {String}
*/
_setLang: function(value) {
var container;
if (this._ready) {
container = this.get(CONTAINER);
container.setAttribute('lang', value);
} else {
//This needs to be wrapped in a contentready callback for the !_ready state
this.once(EVENT_CONTENT_READY, Y.bind(this._setLang, this, value));
}
return value;
},
/**
* Called from the first YUI instance that sets up the internal instance.
* This loads the content into the ContentEditable element and attaches the contentready event.
* @private
* @method _instanceLoaded
* @param {YUI} inst The internal YUI instance bound to the ContentEditable element
*/
_instanceLoaded: function(inst) {
this._instance = inst;
this._onContentReady();
var doc = this._instance.config.doc;
if (!Y.UA.ie) {
try {
//Force other browsers into non CSS styling
doc.execCommand('styleWithCSS', false, false);
doc.execCommand('insertbronreturn', false, false);
} catch (err) {}
}
},
/**
* Validates linkedcss property
*
* @method _validateLinkedCSS
* @private
*/
_validateLinkedCSS: function(value) {
return Lang.isString(value) || Lang.isArray(value);
},
//BEGIN PUBLIC METHODS
/**
* This is a scoped version of the normal YUI.use method & is bound to the ContentEditable element
* At setup, the inst.use method is mapped to this method.
* @method use
*/
use: function() {
var inst = this.getInstance(),
args = Y.Array(arguments),
callback = false;
if (Lang.isFunction(args[args.length - 1])) {
callback = args.pop();
}
if (callback) {
args.push(function() {
callback.apply(inst, arguments);
});
}
return inst.__use.apply(inst, args);
},
/**
* A delegate method passed to the instance's delegate method
* @method delegate
* @param {String} type The type of event to listen for
* @param {Function} fn The method to attach
* @param {String, Node} cont The container to act as a delegate, if no "sel" passed, the container is assumed.
* @param {String} sel The selector to match in the event (optional)
* @return {EventHandle} The Event handle returned from Y.delegate
*/
delegate: function(type, fn, cont, sel) {
var inst = this.getInstance();
if (!inst) {
return false;
}
if (!sel) {
sel = cont;
cont = this.get(CONTAINER);
}
return inst.delegate(type, fn, cont, sel);
},
/**
* Get a reference to the internal YUI instance.
* @method getInstance
* @return {YUI} The internal YUI instance
*/
getInstance: function() {
return this._instance;
},
/**
* @method render
* @param {String/HTMLElement/Node} node The node to render to
* @return {ContentEditable}
* @chainable
*/
render: function(node) {
var args, inst, fn;
if (this._rendered) {
return this;
}
if (node) {
this.set(CONTAINER, node);
}
container = this.get(CONTAINER);
if (!container) {
container = YNode.create(ContentEditable.HTML);
Y.one('body').prepend(container);
this.set(CONTAINER, container);
}
this._rendered = true;
this._container.setAttribute(CONTENT_EDITABLE, true);
args = Y.clone(this.get(USE));
fn = Y.bind(function() {
inst = YUI();
inst.host = this.get(HOST); //Cross reference to Editor
inst.use('node-base', Y.bind(this._instanceLoaded, this));
}, this);
args.push(fn);
Y.use.apply(Y, args);
return this;
},
/**
* Set the focus to the container
* @method focus
* @param {Function} fn Callback function to execute after focus happens
* @return {ContentEditable}
* @chainable
*/
focus: function() {
this._container.focus();
return this;
},
/**
* Show the iframe instance
* @method show
* @return {ContentEditable}
* @chainable
*/
show: function() {
this._container.show();
this.focus();
return this;
},
/**
* Hide the iframe instance
* @method hide
* @return {ContentEditable}
* @chainable
*/
hide: function() {
this._container.hide();
return this;
}
},
{
/**
* The throttle time for key events in IE
* @static
* @property THROTTLE_TIME
* @type Number
* @default 100
*/
THROTTLE_TIME: 100,
/**
* The DomEvents that the frame automatically attaches and bubbles
* @static
* @property DOM_EVENTS
* @type Object
*/
DOM_EVENTS: {
click: 1,
dblclick: 1,
focusin: 1,
focusout: 1,
keydown: 1,
keypress: 1,
keyup: 1,
mousedown: 1,
mouseup: 1,
paste: 1
},
/**
* The template string used to create the ContentEditable element
* @static
* @property HTML
* @type String
*/
HTML: '<div></div>',
/**
* The name of the class (contentEditable)
* @static
* @property NAME
* @type String
*/
NAME: 'contentEditable',
/**
* The namespace on which ContentEditable plugin will reside.
*
* @property NS
* @type String
* @default 'contentEditable'
* @static
*/
NS: CONTENT_EDITABLE,
ATTRS: {
/**
* The default text direction for this ContentEditable element. Default: ltr
* @attribute dir
* @type String
*/
dir: {
lazyAdd: false,
validator: Lang.isString,
setter: '_setDir',
valueFn: '_getDir'
},
/**
* The container to set contentEditable=true or to create on render.
* @attribute container
* @type String/HTMLElement/Node
*/
container: {
setter: function(n) {
this._container = Y.one(n);
return this._container;
}
},
/**
* The string to inject as Editor content. Default '<br>'
* @attribute content
* @type String
*/
content: {
getter: '_getHTML',
lazyAdd: false,
setter: '_setHTML',
validator: Lang.isString,
value: '<br>'
},
/**
* The default tag to use for block level items, defaults to: p
* @attribute defaultblock
* @type String
*/
defaultblock: {
validator: Lang.isString,
value: TAG_PARAGRAPH,
valueFn: '_getDefaultBlock'
},
/**
* A string of CSS to add to the Head of the Editor
* @attribute extracss
* @type String
*/
extracss: {
lazyAdd: false,
setter: '_setExtraCSS',
validator: Lang.isString,
valueFn: '_getExtraCSS'
},
/**
* Set the id of the new Node. (optional)
* @attribute id
* @type String
* @writeonce
*/
id: {
writeOnce: true,
getter: function(id) {
if (!id) {
id = 'inlineedit-' + Y.guid();
}
return id;
}
},
/**
* The default language. Default: en-US
* @attribute lang
* @type String
*/
lang: {
validator: Lang.isString,
setter: '_setLang',
lazyAdd: false,
value: 'en-US'
},
/**
* An array of url's to external linked style sheets
* @attribute linkedcss
* @type String|Array
*/
linkedcss: {
setter: '_setLinkedCSS',
validator: '_validateLinkedCSS'
//value: ''
},
/**
* The Node instance of the container.
* @attribute node
* @type Node
*/
node: {
readOnly: true,
value: null,
getter: function() {
return this._container;
}
},
/**
* Array of modules to include in the scoped YUI instance at render time. Default: ['node-base', 'editor-selection', 'stylesheet']
* @attribute use
* @writeonce
* @type Array
*/
use: {
validator: Lang.isArray,
writeOnce: true,
value: ['node-base', 'editor-selection', 'stylesheet']
}
}
});
Y.namespace('Plugin');
Y.Plugin.ContentEditable = ContentEditable;
}, '@VERSION@', {"requires": ["node-base", "editor-selection", "stylesheet", "plugin"]});
|
/* jQuery.fracs 0.15.1 - http://larsjung.de/jquery-fracs/ */
(function () {
'use strict';
// Some often used references.
var $ = jQuery;
var $window = $(window);
var extend = $.extend;
var fracs = $.fracs;
var Rect = fracs.Rect;
var Viewport = fracs.Viewport;
// Outline
// -------
var defaults = {
crop: false,
duration: 0,
focusWidth: 0.5,
focusHeight: 0.5,
autoFocus: true,
styles: [{
selector: 'header,footer,section,article',
fillStyle: 'rgb(230,230,230)'
}, {
selector: 'h1,h2,h3,h4',
fillStyle: 'rgb(255,144,55)'
}],
viewportStyle: {
fillStyle: 'rgba(255,144,55,0.3)'
},
viewportDragStyle: {
fillStyle: 'rgba(255,144,55,0.5)'
},
invertViewport: false
};
// Quick and dirty.
function Outline(canvas, options, viewport) {
if (!canvas || !$.isFunction(canvas.getContext)) {
return null;
}
var context = canvas.getContext('2d');
if (!context) {
return null;
}
viewport = viewport || window;
var settings = extend({}, defaults, options);
var $canvas = $(canvas);
var width = $canvas.attr('width');
var height = $canvas.attr('height');
var $viewport = $(viewport);
var viewportObj = new Viewport(viewport);
var find = viewport === window ? function (selector) { return $(selector); } : function (selector) { return $viewport.find(selector); };
var drag = false;
var currentContentRect;
var currentViewportRect;
var currentScale;
var focusWidth;
var focusHeight;
function drawRect(rect, strokeWidth, strokeStyle, fillStyle, invert) {
if (!rect || !(strokeStyle || fillStyle)) {
return;
}
if (fillStyle) {
context.beginPath();
if (invert) {
context.rect(0, 0, currentContentRect.width, rect.top);
context.rect(0, rect.top, rect.left, rect.height);
context.rect(rect.right, rect.top, currentContentRect.width - rect.right, rect.height);
context.rect(0, rect.bottom, currentContentRect.width, currentContentRect.height - rect.bottom);
} else {
context.rect(rect.left, rect.top, rect.width, rect.height);
}
context.fillStyle = fillStyle;
context.fill();
}
if (strokeStyle) {
context.beginPath();
context.rect(rect.left, rect.top, rect.width, rect.height);
context.lineWidth = currentScale ? Math.max(strokeWidth, 0.2 / currentScale) : strokeWidth;
context.strokeStyle = strokeStyle;
context.stroke();
}
}
function drawElement(element, strokeWidth, strokeStyle, fillStyle) {
var $element = $(element);
var rect = Rect.ofElement(element);
if (!rect || rect.width <= 0 || rect.height <= 0 || $element.css('visibility') === 'hidden') {
return;
}
rect = rect.relativeTo(currentContentRect);
strokeWidth = strokeWidth === 'auto' ? parseInt($element.css('border-top-width'), 10) : strokeWidth;
strokeStyle = strokeStyle === 'auto' ? $element.css('border-top-color') : strokeStyle;
fillStyle = fillStyle === 'auto' ? $element.css('background-color') : fillStyle;
drawRect(rect, strokeWidth, strokeStyle, fillStyle);
}
function applyStyles() {
$.each(settings.styles, function (idx, style) {
find(style.selector).each(function () {
drawElement(this, style.strokeWidth, style.strokeStyle, style.fillStyle);
});
});
}
function drawViewport() {
var style = drag && settings.viewportDragStyle ? settings.viewportDragStyle : settings.viewportStyle;
drawRect(currentViewportRect, style.strokeWidth, style.strokeStyle, style.fillStyle, settings.invertViewport);
}
function draw() {
currentContentRect = Rect.ofContent(viewport);
currentViewportRect = Rect.ofViewport(viewport, true);
currentScale = Math.min(width / currentContentRect.width, height / currentContentRect.height);
if (settings.crop) {
$canvas.attr('width', currentContentRect.width * currentScale).attr('height', currentContentRect.height * currentScale);
}
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, $canvas.width(), $canvas.height());
context.scale(currentScale, currentScale);
applyStyles();
drawViewport();
}
function onDrag(event) {
var r = Rect.ofElement(canvas);
var x = (event.pageX - r.left) / currentScale - currentViewportRect.width * focusWidth;
var y = (event.pageY - r.top) / currentScale - currentViewportRect.height * focusHeight;
viewportObj.scrollTo(x, y, settings.duration);
}
function onDragEnd(event) {
drag = false;
event.preventDefault();
$canvas.css('cursor', 'pointer').removeClass('dragOn');
$('body').css('cursor', 'auto');
$window.off('mousemove', onDrag);
draw();
}
function onDragStart(event) {
var r;
if (settings.autoFocus) {
r = Rect.ofElement(canvas);
focusWidth = (((event.pageX - r.left) / currentScale) - currentViewportRect.left) / currentViewportRect.width;
focusHeight = (((event.pageY - r.top) / currentScale) - currentViewportRect.top) / currentViewportRect.height;
}
if (!settings.autoFocus || focusWidth < 0 || focusWidth > 1 || focusHeight < 0 || focusHeight > 1) {
focusWidth = settings.focusWidth;
focusHeight = settings.focusHeight;
}
drag = true;
event.preventDefault();
$canvas.css('cursor', 'crosshair').addClass('dragOn');
$('body').css('cursor', 'crosshair');
$window.on('mousemove', onDrag).one('mouseup', onDragEnd);
onDrag(event);
}
function init() {
$canvas.css('cursor', 'pointer').mousedown(onDragStart);
$viewport.on('load resize scroll', draw);
draw();
}
init();
this.redraw = draw;
}
// Register the plug-in
// ===================
// The namespace used to register the plug-in and to attach
// data to elements.
var namespace = 'fracs.outline';
// The methods are sorted in alphabetical order. All methods that do
// not provide a return value will return `this` to enable method chaining.
fracs.modplug({
// Static methods
// --------------
// These methods are accessible via `$.outline.<methodname>`.
statics: {
// Publish object constructors (for testing).
Outline: Outline
},
// Instance methods
// ----------------
// These methods are accessible via `$(selector).outline('<methodname>', ...)`.
methods: {
// ### 'outline'
// Generates a document outline in a selected canvas. Will be redrawn on every
// 'window resize` and `window scroll` event.
//
// .outline([options: OutlineOptions]): jQuery
outline: function (action, options, viewport) {
if (typeof action !== 'string') {
viewport = options;
options = action;
action = null;
}
if (viewport instanceof $) {
viewport = viewport[0];
}
if (action === 'redraw') {
return this.each(function () {
var outline = $(this).data(namespace);
if (outline) {
outline.redraw();
}
});
}
return this.each(function () {
var outline = $(this).data(namespace);
if (!outline) {
outline = new Outline(this, options, viewport);
if (outline) {
$(this).data(namespace, outline);
}
}
});
}
}
});
}());
|
/*!
* Qoopido.js library v3.5.7, 2014-10-14
* https://github.com/dlueth/qoopido.js
* (c) 2014 Dirk Lueth
* Dual licensed under MIT and GPL
*/
!function(o){window.qoopido.register("support/css/boxshadow",o,["../../support"])}(function(o){"use strict";return o.support.addTest("/css/boxshadow",function(s){o.support.supportsCssProperty("box-shadow")?s.resolve(o.support.getCssProperty("box-shadow")):s.reject()})});
|
'use strict';
var path = require('path');
var fileRe = require('filename-regex');
var win32 = process && process.platform === 'win32';
var utils = require('lazy-cache')(require);
/**
* Temporarily re-assign require to trick browserify
* into recognizing lazy-cached deps.
*/
var fn = require;
require = utils;
/**
* Lazily required module dependencies
*/
require('arr-diff', 'diff');
require('array-unique', 'unique');
require('braces');
require('expand-brackets', 'brackets');
require('extglob');
require('is-extglob');
require('is-glob', 'isGlob');
require('kind-of', 'typeOf');
require('normalize-path', 'normalize');
require('object.omit', 'omit');
require('parse-glob');
require('regex-cache', 'cache');
/**
* Get the filename of a filepath
*
* @param {String} `string`
* @return {String}
*/
utils.filename = function filename(fp) {
var seg = fp.match(fileRe());
return seg && seg[0];
};
/**
* Returns a function that returns true if the given
* pattern is the same as a given `filepath`
*
* @param {String} `pattern`
* @return {Function}
*/
utils.isPath = function isPath(pattern, opts) {
return function (fp) {
return pattern === utils.unixify(fp, opts);
};
};
/**
* Returns a function that returns true if the given
* pattern contains a `filepath`
*
* @param {String} `pattern`
* @return {Function}
*/
utils.hasPath = function hasPath(pattern, opts) {
return function (fp) {
return utils.unixify(pattern, opts).indexOf(fp) !== -1;
};
};
/**
* Returns a function that returns true if the given
* pattern matches or contains a `filepath`
*
* @param {String} `pattern`
* @return {Function}
*/
utils.matchPath = function matchPath(pattern, opts) {
var fn = (opts && opts.contains)
? utils.hasPath(pattern, opts)
: utils.isPath(pattern, opts);
return fn;
};
/**
* Returns a function that returns true if the given
* regex matches the `filename` of a file path.
*
* @param {RegExp} `re`
* @return {Boolean}
*/
utils.hasFilename = function hasFilename(re) {
return function (fp) {
var name = utils.filename(fp);
return name && re.test(name);
};
};
/**
* Coerce `val` to an array
*
* @param {*} val
* @return {Array}
*/
utils.arrayify = function arrayify(val) {
return !Array.isArray(val)
? [val]
: val;
};
/**
* Normalize all slashes in a file path or glob pattern to
* forward slashes.
*/
utils.unixify = function unixify(fp, opts) {
if (opts && opts.unixify === false) return fp;
if (opts && opts.unixify === true || win32 || path.sep === '\\') {
return utils.normalize(fp, false);
}
if (opts && opts.unescape === true) {
return fp ? fp.toString().replace(/\\(\w)/g, '$1') : '';
}
return fp;
};
/**
* Escape/unescape utils
*/
utils.escapePath = function escapePath(fp) {
return fp.replace(/[\\.]/g, '\\$&');
};
utils.unescapeGlob = function unescapeGlob(fp) {
return fp.replace(/[\\"']/g, '');
};
utils.escapeRe = function escapeRe(str) {
return str.replace(/[-[\\$*+?.#^\s{}(|)\]]/g, '\\$&');
};
/**
* Restore `require`
*/
require = fn;
/**
* Expose `utils`
*/
module.exports = utils;
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"ERANAMES": [
"Before Christ",
"Anno Domini"
],
"ERAS": [
"BC",
"AD"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"STANDALONEMONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/y HH:mm",
"shortDate": "dd/MM/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-tv",
"localeID": "en_TV",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
const Joi = require('joi');
module.exports =
{
POST_USER_SIGNUP: Joi.object().keys({
handle: Joi.string(),
password: Joi.string().regex(/^[a-zA-Z0-9]{8,128}$/).required(),
email: Joi.string().email().required()
}),
POST_USER_SIGNIN: Joi.object().keys({password: Joi.string().required(), email: Joi.string().email().required()}),
};
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Disable some ESLint rules. camelcase (some "_" in names to indicate indexed variables (like in math)), valid-jsdoc (not completed yet), no-warning-comments (some TODOs are left)
// All other warnings, errors should be resolved
/*eslint camelcase:0, valid-jsdoc:0, no-warning-comments:0 */
// Provides class sap.ui.model.odata.ODataListBinding
sap.ui.define(['jquery.sap.global', 'sap/ui/model/TreeBinding', 'sap/ui/model/ChangeReason', 'sap/ui/model/Sorter', 'sap/ui/model/FilterOperator', './odata4analytics', './BatchResponseCollector', './AnalyticalVersionInfo'],
function(jQuery, TreeBinding, ChangeReason, Sorter, FilterOperator, odata4analytics, BatchResponseCollector, AnalyticalVersionInfo) {
"use strict";
/**
* @class
* Tree binding implementation for OData entity sets with aggregate semantics.
*
* Note on the handling of different count modes:
* The AnalyticalBinding always uses the OData $inlinecount system query option to determine the total
* count of matching entities. It ignores the default count mode set in the ODataModel instance and the
* count mode specified in the binding parameters. If the default count mode is None, a warning is added
* to the log to remind the application that OData requests generated by the AnalyticalBinding will include
* a $inlinecount. If a count mode has been specified in the binding parameters, an error message will be
* logged if it is None, because the binding will still add the $inlinecount to OData requests. If a
* binding count mode is set to Request or Both, a warning will be logged to remind the application that
* the OData requests generated by the AnalyticalBinding will include a $inlinecount.
*
* @param {sap.ui.model.Model} oModel
* @param {string}
* sPath the path pointing to the tree / array that should be bound
* @param {object}
* [oContext=null] the context object for this data binding
* @param {array}
* [aSorter=null] predefined sorter/s contained in an array
* @param {array}
* [aFilters=null] predefined filter/s contained in an array
* @param {object}
* [mParameters=null] additional control parameters. Supported parameters are:
* <ul>
* <li>entitySet: if set, it explicitly specifies the entity set addressed by the last segment of the given binding path</li>
* <li>useBatchRequests: if true, multiple OData requests will be wrapped into a single batch request, wherever possible</li>
* <li>provideGrandTotals: if true, grand total values will be provided for all bound measure properties</li>
* <li>provideTotalResultSize: if true, the total number of matching entries in the bound OData entity set will be provided</li>
* <li>reloadSingleUnitMeasures: if true, the binding will check aggregated entries with multi-unit occurrences, if
* some measure properties have a unique unit and will trigger separate OData requests to fetch them</li>
* </ul>
*
* @throws Will throw an error if no analytic query result object could be determined from the bound OData entity set, either from an explicitly
* given EntitySet (via optional mParameters.entitySet argument), or by default implicitly from
* the binding path (see mandatory sPath argument).
*
* @alias sap.ui.model.analytics.AnalyticalBinding
* @extends sap.ui.model.TreeBinding
* @experimental This module is only for experimental use!
* @protected
*/
var AnalyticalBinding = TreeBinding.extend("sap.ui.model.analytics.AnalyticalBinding", /** @lends sap.ui.model.analytics.AnalyticalBinding.prototype */ {
constructor : function(oModel, sPath, oContext, aSorter, aFilters, mParameters) {
TreeBinding.call(this, oModel, sPath, oContext, aFilters, mParameters);
// attribute members for addressing the requested entity set
this.sEntitySetName = (mParameters && mParameters.entitySet) ? mParameters.entitySet : undefined;
// attribute members for maintaining aggregated OData requests
this.bArtificalRootContext = false;
this.aApplicationFilter = this._convertDeprecatedFilterObjects(aFilters);
this.aControlFilter = undefined;
this.aSorter = aSorter ? aSorter : [];
this.aMaxAggregationLevel = [];
this.aAggregationLevel = [];
this.oPendingRequests = {};
this.oPendingRequestHandle = [];
this.oGroupedRequests = {};
this.bUseBatchRequests = (mParameters && mParameters.useBatchRequests === true) ? true : false;
this.bProvideTotalSize = (mParameters && mParameters.provideTotalResultSize === false) ? false : true;
this.bProvideGrandTotals = (mParameters && mParameters.provideGrandTotals === false) ? false : true;
this.bReloadSingleUnitMeasures = (mParameters && mParameters.reloadSingleUnitMeasures === false) ? false : true;
this.bUseAcceleratedAutoExpand = (mParameters && mParameters.useAcceleratedAutoExpand === false) ? false : true;
this.bNoPaging = (mParameters && mParameters.noPaging === true) ? true : false;
// attribute members for maintaining loaded data; mapping from groupId to related information
this.iTotalSize = -1;
/* data loaded from OData service */
this.mServiceKey = {}; // keys of loaded entities belonging to group with given ID
this.mServiceLength = {}; // number of currently loaded entities
this.mServiceFinalLength = {}; // true iff all entities of group with given ID have been loaded (keys in mServiceKey)
/* consolidated view on loaded data */
this.mKeyIndex = {}; // consumer view: group entries are index positions in mServiceKey
this.mFinalLength = this.mServiceFinalLength; // true iff all entities of group with given ID have been loaded (keys in mKey)
this.mLength = {}; // number of currently loaded entities
/* locally created multi-currency entities */
this.mMultiUnitKey = {}; // keys of multi-currency entities
this.aMultiUnitLoadFactor = {}; // compensate discarded multi-unit entities by a load factor per aggregation level to increase number of loaded entities
this.bNeedsUpdate = false;
/* entity keys of loaded group Id's */
this.mEntityKey = {};
/* increased load factor due to ratio of non-multi-unit entities versus loaded entities */
// custom parameters which will be send with every request
// the custom parameters are extracted from the mParameters object, because the SmartTable does some weird things to the parameters
this.sCustomParams = this.oModel.createCustomParams({custom: this.mParameters.custom});
// attribute members for maintaining structure details requested by the binding consumer
this.oAnalyticalQueryResult = null; //will be initialized via the "initialize" function of the binding
this.aAnalyticalInfo = [];
this.mAnalyticalInfoByProperty = {};
// maintaining request to be bundled in a single $batch request
this.aBatchRequestQueue = [];
// considering different count mode settings
if (mParameters && mParameters.countMode == sap.ui.model.odata.CountMode.None) {
jQuery.sap.log.fatal("requested count mode is ignored; OData requests will include $inlinecout options");
} else if (mParameters
&& (mParameters.countMode == sap.ui.model.odata.CountMode.Request
|| mParameters.countMode == sap.ui.model.odata.CountMode.Both)) {
jQuery.sap.log.warning("default count mode is ignored; OData requests will include $inlinecout options");
} else if (this.oModel.sDefaultCountMode == sap.ui.model.odata.CountMode.Request) {
jQuery.sap.log.warning("default count mode is ignored; OData requests will include $inlinecout options");
}
// detect ODataModel version
this.iModelVersion = AnalyticalVersionInfo.getVersion(this.oModel);
if (this.iModelVersion === null) {
jQuery.sap.log.error("The AnalyticalBinding does not support Models other than sap.ui.model.odata.ODataModel version 1 or 2.");
return;
}
// list of sorted dimension names as basis for later calculations, initialized via "initialize" function
this.aAllDimensionSortedByName = null;
//Some setup steps have to be deferred, until the metadata was loaded by the model:
// - updateAnalyticalInfo, the parameters given in the constructor are kept though
// - fetch the oAnalyticalQueryResult
this.aInitialAnalyticalInfo = (mParameters == undefined ? [] : mParameters.analyticalInfo);
//this flag indicates if the analytical binding was initialized via initialize(), called either via bindAggregation or the Model
this.bInitial = true;
}
});
/**
* Setter for context
* @param {Object} oContext the new context object
*/
AnalyticalBinding.prototype.setContext = function (oContext) {
if (this.oContext !== oContext) {
this.oContext = oContext;
this.oDataState = null;
if (this.isRelative()) {
if (!this.bInitial) {
this.refresh();
}
}
}
};
/**
* Initialize binding. Fires a change if data is already available ($expand) or a refresh.
* If metadata is not yet available, do nothing, method will be called again when
* metadata is loaded.
*
* The ODataModel will call this on all bindings as soon as the metadata was loaded
*
* @public
* @name sap.ui.model.analytics.v2.AnalyticalBinding#initialize
* @function
*/
AnalyticalBinding.prototype.initialize = function() {
if (this.oModel.oMetadata && this.oModel.oMetadata.isLoaded() && this.bInitial) {
this.bInitial = false;
//first fetch the analyticalQueryResult object from the adapted Model (see ODataModelAdapter.js)
this.oAnalyticalQueryResult = this.oModel.getAnalyticalExtensions().findQueryResultByName(this._getEntitySet());
// Sanity check: If the AnalyticalQueryResult could not be retrieved, the AnalyticalBinding will not work correctly,
// and it will sooner or later break when accessing the AnalyticalQueryResult object.
if (!this.oAnalyticalQueryResult) {
throw ("Error in AnalyticalBinding - The QueryResult '" + this._getEntitySet() + "' could not be retrieved. Please check your service definition.");
}
//afterwards update the analyticalInfo with the initial parameters given in the constructor
this.updateAnalyticalInfo(this.aInitialAnalyticalInfo);
//initialize the list of sorted dimension names
this.aAllDimensionSortedByName = this.oAnalyticalQueryResult.getAllDimensionNames().concat([]).sort();
this._fireRefresh({reason: ChangeReason.Refresh});
}
return this;
};
/* *******************************
*** API - Public methods
********************************/
/**
* Gets the context for the root aggregation level representing the grand total for all bound measure properties.
*
* The context is assigned to parent group ID <code>null</code>. If the binding is configured not to provide a grand total,
* this context is empty. If data for this context is not locally available yet, an OData request will be triggered to load it.
*
* This function must be called whenever the bound set of OData entities changes, e.g., by changing selected dimensions,
* modifying filter conditions, etc.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getRootContexts
* @param {map}
* mParameters specifying how the top-most aggregation level shall be fetched. Supported parameters are:
* <ul>
* <li>numberOfExpandedLevels: number of child levels that shall be fetched automatically</li>
* <li>startIndex: index of first entry to return from parent group ID <code>"/"</code> (zero-based)</li>
* <li>length: number of entries to return at and after the given start index</li>
* <li>threshold: number of additional entries that shall be locally available in the binding for subsequent
* accesses to contexts of parent group ID <code>"/"</code> or below, if auto-expanding is selected</li>
* </ul>
* @return {array}
* Array with a single object of class sap.ui.model.Context for the root context,
* or an empty array if an OData request is pending to fetch requested contexts that are not yet locally available.
*
* @public
*/
AnalyticalBinding.prototype.getRootContexts = function(mParameters) {
if (this.bInitial) {
return [];
}
var iAutoExpandGroupsToLevel = (mParameters && mParameters.numberOfExpandedLevels ? mParameters.numberOfExpandedLevels + 1 : 1);
// this._trace_enter("API", "getRootContexts", "", mParameters, ["numberOfExpandedLevels", "startIndex","length","threshold"]); // DISABLED FOR PRODUCTION
var aRootContext = null;
var sRootContextGroupMembersRequestId = this._getRequestId(AnalyticalBinding._requestType.groupMembersQuery, {groupId: null});
// if the root context is artificial (i.e. no grand total requested), then delay its return until all other related requests have been completed
if (this.bArtificalRootContext
&& !this._cleanupGroupingForCompletedRequest(sRootContextGroupMembersRequestId)) {
// this._trace_leave("API", "getRootContexts", "delay until related requests have been completed"); // DISABLED FOR PRODUCTION
return aRootContext;
}
aRootContext = this._getContextsForParentContext(null);
if (aRootContext.length == 1) {
// this._trace_leave("API", "getRootContexts", "", aRootContext, ["length"]); // DISABLED FOR PRODUCTION
return aRootContext;
}
if (iAutoExpandGroupsToLevel <= 1) {
if (iAutoExpandGroupsToLevel == 1) {
this._considerRequestGrouping([ sRootContextGroupMembersRequestId,
this._getRequestId(AnalyticalBinding._requestType.groupMembersQuery, {groupId: "/"}) ]);
this.getNodeContexts(this.getModel().getContext("/"), {
startIndex : mParameters.startIndex,
length : mParameters.length,
threshold : mParameters.threshold,
level : 0,
numberOfExpandedLevels : 0
});
}
} else {
var aRequestId = this._prepareGroupMembersAutoExpansionRequestIds("/", mParameters.numberOfExpandedLevels);
aRequestId.push(sRootContextGroupMembersRequestId);
this._considerRequestGrouping(aRequestId);
this.getNodeContexts(this.getModel().getContext("/"), {
startIndex : mParameters.startIndex,
length : mParameters.length,
threshold : mParameters.threshold,
level : 0,
numberOfExpandedLevels : mParameters.numberOfExpandedLevels
});
/* jQuery.sap.log.fatal("not yet implemented: number of initially expanded levels may be 0 or 1, but not "
+ mParameters.numberOfExpandedLevels);
*/
}
if (aRootContext.length > 1) {
jQuery.sap.log.fatal("assertion failed: grand total represented by a single entry");
}
// this._trace_leave("API", "getRootContexts", "", aRootContext, ["length"]); // DISABLED FOR PRODUCTION
return aRootContext;
};
/**
* Gets child contexts for a specified parent context.
*
* Contexts are returned in a stable order imposed by the
* dimension property that defines this aggregation level beneath the parent context: Either a sort order has been specified for this property,
* or the entries are returned in ascending order of the values of this dimension property by default.
*
* If any of the requested data is missing, an OData request will be triggered to load it.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getNodeContexts
* @param {map}
* mParameters specifying the aggregation level for which contexts shall be fetched. Supported parameters are:
* <ul>
* <li>oContext: parent context identifying the requested group of child contexts</li>
* <li>level: level number for oContext, because it might occur at multiple levels; context with group ID <code>"/"</code> has level 0</li>
* <li>numberOfExpandedLevels: number of child levels that shall be fetched automatically</li>
* <li>startIndex: index of first child entry to return from the parent context (zero-based)</li>
* <li>length: number of entries to return; counting begins at the given start index</li>
* <li>threshold: number of additional entries that shall be locally available in the binding for subsequent
* accesses to child entries of the given parent context. </li>
* </ul>
* @return {array}
* Array containing the requested contexts of class sap.ui.model.Context, limited by the number of entries contained
* in the entity set at that aggregation level.
* The array will contain less than the requested number of contexts, if some are not locally available and an OData request is
* pending to fetch them. In this case, if the parameter numberOfExpandedLevels > 0, the array will be completely empty.
*
* @public
*/
AnalyticalBinding.prototype.getNodeContexts = function(oContext, mParameters) {
if (this.bInitial) {
return [];
}
// this._trace_enter("API", "getNodeContexts", "groupId=" + this._getGroupIdFromContext(oContext, mParameters.level), mParameters,["startIndex","length","threshold"]); // DISABLED FOR PRODUCTION
var iStartIndex, iLength, iThreshold, iLevel, iNumberOfExpandedLevels, bSupressRequest;
if (typeof mParameters == "object") {
iStartIndex = mParameters.startIndex;
iLength = mParameters.length;
iThreshold = mParameters.threshold;
iLevel = mParameters.level;
iNumberOfExpandedLevels = mParameters.numberOfExpandedLevels;
bSupressRequest = mParameters.supressRequest;
} else { // due to compatibility; can be removed if table is adapted
iStartIndex = arguments[1];
iLength = arguments[2];
iThreshold = arguments[3];
iLevel = arguments[4];
iNumberOfExpandedLevels = arguments[5];
bSupressRequest = arguments[6];
}
var aContext = this._getContextsForParentContext(oContext, iStartIndex, iLength, iThreshold, iLevel, iNumberOfExpandedLevels, bSupressRequest);
// this._trace_leave("API", "getNodeContexts", "", aContext, ["length"]); // DISABLED FOR PRODUCTION
return aContext;
};
AnalyticalBinding.prototype.ContextsAvailabilityStatus = { ALL: 2, SOME: 1, NONE: 0 };
/**
* Determines if the binding has the entries of a given aggregation level locally available.
*
* If so, no further OData request is required to fetch any of them.
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.hasAvailableNodeContexts
* @param {sap.ui.model.Context}
* oContext the parent context identifying the aggregation level.
* @param {integer}
* iLevel the level number of oContext (because the context might occur at multiple levels).
* @return {boolean}
* property of sap.ui.model.analytics.AnalyticalBinding.ContextsAvailabilityStatus,
* indicating whether all, some, or none of the entries are locally available.
* @public
*/
AnalyticalBinding.prototype.hasAvailableNodeContexts = function(oContext, iLevel) {
var sGroupId = this._getGroupIdFromContext(oContext, iLevel);
if (this._getKeys(sGroupId) != undefined) {
if (this.mFinalLength[sGroupId] == true) {
return AnalyticalBinding.prototype.ContextsAvailabilityStatus.ALL;
} else {
return AnalyticalBinding.prototype.ContextsAvailabilityStatus.SOME;
}
} else {
return AnalyticalBinding.prototype.ContextsAvailabilityStatus.NONE;
}
};
/**
* Gets the total number of contexts contained in a group, if known.
*
* For a given group, be aware that the group size might vary over time. In principle, this can happen if the
* bound set of OData entities includes measure properties with amount or quantity values. The AnalyticalBinding
* recognizes situations where the OData service returns multiple entries for a single group entry due to the fact that a
* measure property cannot be aggregated properly, because an amount exists in multiple currencies or a quantity exists
* in multiple units. In such situations, the AnalyticalBinding substitutes these entries by a single representative, and
* the group size gets reduced by the count of duplicate entries. Finally, since the Binding does not always fetch all children of
* a group at once, but only a page with a certain range, such size changes might happen after every page access.
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getGroupSize
* @param {sap.ui.model.Context}
* oContext the parent context identifying the requested group of child contexts.
* @param {integer}
* iLevel the level number of oContext (because the context might occur at multiple levels)
* @return {integer}
* The currently known group size, or -1, if not yet determined
* @public
*/
AnalyticalBinding.prototype.getGroupSize = function(oContext, iLevel) {
if (oContext === undefined) {
return 0; // API robustness
}
var sGroupId = this._getGroupIdFromContext(oContext, iLevel);
return this.mFinalLength[sGroupId] ? this.mLength[sGroupId] : -1;
};
/**
* Gets the total number of entities in the bound OData entity set.
*
* Counting takes place at the lowest aggregation level defined by the possible value combinations for the complete set of
* dimension properties included in the bound entity set. This means that intermediate aggregate entities with
* sub-totals at higher aggregation levels are not counted.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getTotalSize
* @return {integer}
* the total number of addressed entities in the OData entity set
*
* @public
*/
AnalyticalBinding.prototype.getTotalSize = function() {
if (!this.bProvideTotalSize) {
jQuery.sap.log.fatal("total size of result explicitly turned off, but getter invoked");
}
return +this.iTotalSize;
};
/**
* Determines if the contexts in a specified group have further children. If so,
* any of these group contexts can be a parent context of a nested sub-group in
* a subsequent aggregation level.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.hasChildren
* @param {sap.ui.model.Context}
* oContext the parent context identifying the requested group of child contexts.
* @param {map}
* mParameters The only supported parameter is level as the level number of oContext (because the context might occur at multiple levels)
* @return {boolean}
* true if and only if the contexts in the specified group have further children.
* @public
*/
AnalyticalBinding.prototype.hasChildren = function(oContext, mParameters) {
if (oContext === undefined) {
return false; // API robustness
}
if (oContext == null) {
return true;
}
var iContextLevel = mParameters.level;
if (iContextLevel == 0) {
return true;
}
if (this.aAggregationLevel.length < iContextLevel) {
return false;
}
// children exist if it is not the rightmost grouped column or there is at least one further level with an ungrouped groupable column.
return jQuery.inArray(this.aAggregationLevel[iContextLevel - 1], this.aMaxAggregationLevel) < this.aMaxAggregationLevel.length - 1;
};
/**
* Determines if any of the properties included in the bound OData entity set is a measure property.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.hasMeasures
* @return {boolean}
* true if and only one or more properties are measure properties.
*
* @public
*/
AnalyticalBinding.prototype.hasMeasures = function() {
var bHasMeasures = false;
for (var p in this.oMeasureDetailsSet) {
if (this.oMeasureDetailsSet.hasOwnProperty(p)) {
bHasMeasures = true;
break;
}
}
return bHasMeasures;
};
/**
* Gets details about the dimension properties included in the bound OData entity set.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getDimensionDetails
* @return {map}
* details for every dimension property addressed by its name. The details object provides these properties: name of the dimension,
* keyPropertyName for the name of the property holding the dimension key, textPropertyName for the name of the property holding the
* text for the dimension, aAttributeName listing all properties holding dimension attributes, grouped as indicator whether or not this
* dimension is currently grouped, and analyticalInfo, which contains the binding information for this dimension passed from the
* AnalyticalBinding's consumer via call to function updateAnalyticalInfo.
*
* @public
*/
AnalyticalBinding.prototype.getDimensionDetails = function() {
return this.oDimensionDetailsSet;
};
/**
* Gets details about the measure properties included in the bound OData entity set.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getMeasureDetails
* @return {map}
* details for every measure property addressed by its name. The details object provides these properties: name of the measure,
* rawValuePropertyName for the name of the property holding the raw value, unitPropertyName for the name of the property holding the related
* value unit or currency, if any, and analyticalInfo, which contains the binding information for this measure passed from the
* AnalyticalBinding's consumer via call to function updateAnalyticalInfo.
*
* @public
*/
AnalyticalBinding.prototype.getMeasureDetails = function() {
return this.oMeasureDetailsSet;
};
/**
* Determines if the binding has been configured to provide a grand total for the selected measure properties.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.providesGrandTotal
* @return {boolean}
* true if and only if the binding provides a context for the grand totals of all selected measure properties.
*
* @public
*/
AnalyticalBinding.prototype.providesGrandTotal = function() {
return this.bProvideGrandTotals;
};
/**
* Gets the metadata of a property with a given name.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getProperty
* @param {string}
* sPropertyName The property name.
* @return {object}
* OData metadata of this property or null if it does not exist.
* @public
*/
AnalyticalBinding.prototype.getProperty = function(sPropertyName) {
if (this.bInitial) {
return {};
}
return this.oAnalyticalQueryResult.getEntityType().findPropertyByName(sPropertyName);
};
/**
* Gets the names of the filterable properties in the bound OData entity set.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getFilterablePropertyNames
* @returns {array}
* names of properties that can be filtered.
*
* @public
*/
AnalyticalBinding.prototype.getFilterablePropertyNames = function() {
if (this.bInitial) {
return [];
}
return this.oAnalyticalQueryResult.getEntityType().getFilterablePropertyNames();
};
/**
* Gets the names of the sortable properties in the bound OData entity set.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getSortablePropertyNames
* @returns {array}
* names of properties that can be used for sorting the result entities.
*
* @public
*/
AnalyticalBinding.prototype.getSortablePropertyNames = function() {
if (this.bInitial) {
return [];
}
return this.oAnalyticalQueryResult.getEntityType().getSortablePropertyNames();
};
/**
* Gets the label of a property with a given name.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getPropertyLabel
* @param {string}
* sPropertyName The property name.
* @returns {string}
* The label maintained for this property or null if it does not exist.
*
* @public
*/
AnalyticalBinding.prototype.getPropertyLabel = function(sPropertyName) {
if (this.bInitial) {
return "";
}
return this.oAnalyticalQueryResult.getEntityType().getLabelOfProperty(sPropertyName);
};
/**
* Gets the label of a property with a given name.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getPropertyHeading
* @param {string}
* sPropertyName The property name.
* @returns {string}
* The heading maintained for this property or null if it does not exist.
*
* @public
*/
AnalyticalBinding.prototype.getPropertyHeading = function(sPropertyName) {
if (this.bInitial) {
return "";
}
return this.oAnalyticalQueryResult.getEntityType().getHeadingOfProperty(sPropertyName);
};
/**
* Gets the quick info of a property with a given name.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getPropertyQuickInfo
* @param {string}
* sPropertyName The property name.
* @returns {string}
* The quick info maintained for this property or null if it does not exist.
*
* @public
*/
AnalyticalBinding.prototype.getPropertyQuickInfo = function(sPropertyName) {
if (this.bInitial) {
return "";
}
return this.oAnalyticalQueryResult.getEntityType().getQuickInfoOfProperty(sPropertyName);
};
/**
* Determines if a given name refers to a measure property
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.isMeasure
* @param {string}
* sPropertyName The property name.
* @return {boolean}
* true if and only if the bound OData entity set includes a measure property with this name.
*
* @public
*/
AnalyticalBinding.prototype.isMeasure = function(sPropertyName) {
return jQuery.inArray(sPropertyName, this.aMeasureName) !== -1;
};
/**
* Sets filters for matching only a subset of the entities in the bound OData entity set.
*
* Invoking this function resets the state of the binding. Subsequent data requests such as calls to getNodeContexts() will
* need to trigger OData requests in order to fetch the data that are in line with these filters.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.filter
* @param {sap.ui.model.Filter[]|sap.ui.model.Filter}
* aFilter an Array of sap.ui.model.Filter objects or a single Filter instance.
* @param {sap.ui.model.FilterType}
* [sFilterType=sap.ui.model.FilterType.Control] Type of the filter which should be adjusted.
* @return {sap.ui.model.analytics.AnalyticalBinding}
* returns <code>this</code> to facilitate method chaining
*
* @public
*/
AnalyticalBinding.prototype.filter = function(aFilter, sFilterType) {
//ensure at least an empty array, so the later validation of odata4analytics.js does not fail
if (!aFilter) {
aFilter = [];
}
// wrap filter argument in an array if it's a single instance
if (aFilter instanceof sap.ui.model.Filter) {
aFilter = [aFilter];
}
aFilter = this._convertDeprecatedFilterObjects(aFilter);
if (sFilterType == sap.ui.model.FilterType.Application) {
this.aApplicationFilter = aFilter;
} else {
this.aControlFilter = aFilter;
}
this.iTotalSize = -1; // invalidate last row counter
this._abortAllPendingRequests();
this.resetData();
this._fireRefresh({
reason : ChangeReason.Filter
});
return this;
};
/**
* Sets sorters for retrieving the entities in the bound OData entity set in a specific order.
*
* Invoking this function resets the state of the binding. Subsequent data requests such as calls to getNodeContexts() will
* need to trigger OData requests in order to fetch the data that are in line with these sorters.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.sort
* @param {sap.ui.model.Sorter|array}
* aSorter an sorter object or an array of sorter objects which define the sort order.
* @return {sap.ui.model.analytics.AnalyticalBinding}
* returns <code>this</code> to facilitate method chaining.
*
* @public
*/
AnalyticalBinding.prototype.sort = function(aSorter) {
if (aSorter instanceof Sorter) {
aSorter = [ aSorter ];
}
this.aSorter = aSorter ? aSorter : [];
this._abortAllPendingRequests();
this.resetData(undefined, {reason: ChangeReason.Sort});
this._fireRefresh({
reason : ChangeReason.Sort
});
return this;
};
/**
* Gets a printable name for a group.
*
* The printable name follows the pattern is <code><label>:<key-value>[-<text-value>]</code>,
* where <code>label</code> is the label of the dimension property used at the aggregation level for the group,
* <code>key-value</code> is the key value of that dimension for the group, and <code>text-value</code> is the
* value of the associated text property, if it is also used in the binding.
*
* Whenever a formatter function has been defined for a column displaying the key or text of this dimension, the return value
* of this function is applied for the group name instead of the respective key or text value.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getGroupName
* @param {sap.ui.model.Context}
* oContext the parent context identifying the requested group.
* @param {integer}
* iLevel the level number of oContext (because the context might occur at multiple levels)
* @return {string} a printable name for the group.
* @public
*/
AnalyticalBinding.prototype.getGroupName = function(oContext, iLevel) {
if (oContext === undefined) {
return ""; // API robustness
}
var sGroupProperty = this.aAggregationLevel[iLevel - 1],
oDimension = this.oAnalyticalQueryResult.findDimensionByPropertyName(sGroupProperty),
fValueFormatter = this.mAnalyticalInfoByProperty[sGroupProperty].formatter,
sPropertyValue = oContext.getProperty(sGroupProperty),
oTextProperty, sFormattedPropertyValue, sGroupName;
if (oDimension && this.oDimensionDetailsSet[sGroupProperty].textPropertyName) {
oTextProperty = oDimension.getTextProperty();
}
var sTextProperty, sTextPropertyValue, fTextValueFormatter;
if (oTextProperty) {
sTextProperty = oDimension.getTextProperty().name;
fTextValueFormatter = this.mAnalyticalInfoByProperty[sTextProperty].formatter;
sTextPropertyValue = oContext.getProperty(sTextProperty);
}
if (!oTextProperty) {
sFormattedPropertyValue = fValueFormatter ? fValueFormatter(sPropertyValue) : sPropertyValue;
sGroupName = ((oDimension.getLabelText()) ? oDimension.getLabelText() + ': ' : '') + sFormattedPropertyValue;
} else {
sFormattedPropertyValue = fValueFormatter ? fValueFormatter(sPropertyValue, sTextPropertyValue) : sPropertyValue;
sGroupName = ((oDimension.getLabelText()) ? oDimension.getLabelText() + ': ' : '') + sFormattedPropertyValue;
var sFormattedTextPropertyValue = fTextValueFormatter ? fTextValueFormatter(sTextPropertyValue, sPropertyValue) : sTextPropertyValue;
if (sFormattedTextPropertyValue) {
sGroupName += ' - ' + sFormattedTextPropertyValue;
}
}
return sGroupName;
};
/**
* Updates the binding's structure with new analytical information.
*
* Analytical information is the mapping of UI columns to properties in the bound OData entity set. Every column object contains
* the name of the bound property and in addition:
* <ol>
* <li>A column bound to a dimension property has further boolean properties:
* <ul>
* <li>grouped: dimension will be used for building groups</li>
* <li>visible: if the column is visible, values for the related property will be fetched from the OData service</li>
* <li>inResult: if the column is not visible, but declared to be part of the result, values for the related property
* will also be fetched from the OData service</li>
* </ul>
* </li>
* <li>A column bound to a measure property has further boolean properties:
* <ul>
* <li>total: totals and sub-totals will be provided for the measure at all aggregation levels</li>
* </ul>
* </li>
* </ol>
*
* Invoking this function resets the state of the binding and subsequent data requests such as calls to getNodeContexts() will
* need to trigger OData requests in order to fetch the data that are in line with this analytical information.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.updateAnalyticalInfo
* @param {array}
* aColumns an array with objects holding the analytical information for every column, from left to right.
* @public
*/
AnalyticalBinding.prototype.updateAnalyticalInfo = function(aColumns) {
if (!this.oModel.oMetadata || !this.oModel.oMetadata.isLoaded() || this.bInitial) {
this.aInitialAnalyticalInfo = aColumns;
return;
}
// parameter is an array with elements whose structure is defined by sap.ui.analytics.model.AnalyticalTable.prototype._getColumnInformation()
var oPreviousDimensionDetailsSet = this.oDimensionDetailsSet;
this.mAnalyticalInfoByProperty = {}; // enable associative access to analytical update information
this.aMaxAggregationLevel = []; // names of all dimensions referenced by any column
this.aAggregationLevel = []; // names of all currently grouped dimensions
this.aMeasureName = []; // names of all measures referenced by any column
if (this.iAnalyticalInfoVersionNumber == undefined) {
this.iAnalyticalInfoVersionNumber = 1;
} else if (this.iAnalyticalInfoVersionNumber > 999) {
this.iAnalyticalInfoVersionNumber = 1;
} else {
this.iAnalyticalInfoVersionNumber = this.iAnalyticalInfoVersionNumber + 1;
}
this.oMeasureDetailsSet = {}; // properties with structure {rawValueProperty,unitProperty,formattedValueProperty}
this.oDimensionDetailsSet = {}; // properties with structure {name,keyProperty,textProperty,aAttributeName}
// process column settings for dimensions and measures part of the result or visible
for (var i = 0; i < aColumns.length; i++) {
// determine requested aggregation level from columns representing dimension-related properties
var oDimension = this.oAnalyticalQueryResult.findDimensionByPropertyName(aColumns[i].name);
if (oDimension && (aColumns[i].inResult == true || aColumns[i].visible == true)) {
aColumns[i].dimensionPropertyName = oDimension.getName();
var oDimensionDetails = this.oDimensionDetailsSet[oDimension.getName()];
if (!oDimensionDetails) {
oDimensionDetails = {};
oDimensionDetails.name = oDimension.getName();
oDimensionDetails.aAttributeName = [];
oDimensionDetails.grouped = false;
this.oDimensionDetailsSet[oDimension.getName()] = oDimensionDetails;
this.aMaxAggregationLevel.push(oDimensionDetails.name);
if (aColumns[i].grouped == true) {
this.aAggregationLevel.push(oDimensionDetails.name);
}
}
if (aColumns[i].grouped == true) {
if (jQuery.inArray(oDimension.getName(), this.getSortablePropertyNames()) == -1) {
jQuery.sap.log.fatal("property " + oDimension.getName() + " must be sortable in order to be used as grouped dimension");
}
oDimensionDetails.grouped = true;
}
if (oDimension.getName() == aColumns[i].name) {
oDimensionDetails.keyPropertyName = aColumns[i].name;
}
var oTextProperty = oDimension.getTextProperty();
if (oTextProperty && oTextProperty.name == aColumns[i].name) {
oDimensionDetails.textPropertyName = aColumns[i].name;
}
if (oDimension.findAttributeByName(aColumns[i].name)) {
oDimensionDetails.aAttributeName.push(aColumns[i].name);
}
oDimensionDetails.analyticalInfo = aColumns[i];
}
// determine necessary measure details from columns visualizing measure-related properties
var oMeasure = this.oAnalyticalQueryResult.findMeasureByPropertyName(aColumns[i].name);
if (oMeasure && (aColumns[i].inResult == true || aColumns[i].visible == true)) {
aColumns[i].measurePropertyName = oMeasure.getName();
var oMeasureDetails = this.oMeasureDetailsSet[oMeasure.getName()];
if (!oMeasureDetails) {
oMeasureDetails = {};
oMeasureDetails.name = oMeasure.getName();
this.oMeasureDetailsSet[oMeasure.getName()] = oMeasureDetails;
this.aMeasureName.push(oMeasureDetails.name);
}
if (oMeasure.getRawValueProperty().name == aColumns[i].name) {
oMeasureDetails.rawValuePropertyName = aColumns[i].name;
}
var oFormattedValueProperty = oMeasure.getFormattedValueProperty();
if (oFormattedValueProperty && oFormattedValueProperty.name == aColumns[i].name) {
oMeasureDetails.formattedValuePropertyName = aColumns[i].name;
}
oMeasureDetails.analyticalInfo = aColumns[i];
}
this.mAnalyticalInfoByProperty[aColumns[i].name] = aColumns[i];
}
// finalize measure information with unit properties also being part of the table
for ( var measureName in this.oMeasureDetailsSet) {
var oUnitProperty = this.oAnalyticalQueryResult.findMeasureByName(measureName).getUnitProperty();
if (oUnitProperty) {
this.oMeasureDetailsSet[measureName].unitPropertyName = oUnitProperty.name;
}
}
// check if any dimension has been added or removed. If so, invalidate the total size
var compileDimensionNames = function (oDimensionDetailsSet) {
var aName = [];
for (var oDimDetails in oDimensionDetailsSet)
aName.push(oDimDetails.name);
return aName.sort().join(";");
};
if (compileDimensionNames(oPreviousDimensionDetailsSet) != compileDimensionNames(this.oDimensionDetailsSet)) {
this.iTotalSize = -1;
}
// remember column settings for later reference
this.aAnalyticalInfo = aColumns;
// reset attributes holding previously loaded data
this.resetData();
this.bNeedsUpdate = false;
};
/**
* Gets the analytical information for a column with a given name.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getAnalyticalInfoForColumn
* @param sColumnName the column name.
* @return {object}
* analytical information for the column; see {@link #updateAnalyticalInfo}
* for an explanation of the object structure
* @public
*/
AnalyticalBinding.prototype.getAnalyticalInfoForColumn = function(sColumnName) {
return this.mAnalyticalInfoByProperty[sColumnName];
};
/**
* Loads child contexts of multiple groups.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.loadGroups
* @param {map}
* mGroupIdRanges specifies index ranges of child contexts to be loaded for multiple groups identified by their ID. A group index range is
* given by an object consisting of startIndex, length, threshold. For every group ID, the map holds an array of such range objects.
*
* @public
*/
AnalyticalBinding.prototype.loadGroups = function(mGroupIdRanges) {
var aGroupId = [];
for ( var sGroupId in mGroupIdRanges) {
aGroupId.push(sGroupId);
// clean up existing loaded data for the given group ID
this._resetData(sGroupId);
var aGroupIdRange = mGroupIdRanges[sGroupId];
for (var i = 0; i < aGroupIdRange.length; i++) {
var oGroupIdRange = aGroupIdRange[i];
// force reload of every requested index range for the given group ID
this._getContextsForParentGroupId(sGroupId, oGroupIdRange.startIndex, oGroupIdRange.length,
oGroupIdRange.threshold);
}
// TODO check current code works, but it would be more natural if this _considerRequestGrouping would be outside of this loop
var aRequestId = [];
for (var j = -1, sGroupId2; (sGroupId2 = aGroupId[++j]) !== undefined; ) {
aRequestId.push(this._getRequestId(AnalyticalBinding._requestType.groupMembersQuery, {groupId: sGroupId2}));
}
this._considerRequestGrouping(aRequestId);
}
};
/**
* Gets analytical metadata for the bound OData entity set.
*
* @function
* @name sap.ui.model.analytics.AnalyticalBinding.prototype.getAnalyticalQueryResult
* @return {sap.ui.model.analytics.odata4analytics.QueryResult} analytical metadata for the bound OData entity set
* @public
*/
AnalyticalBinding.prototype.getAnalyticalQueryResult = function() {
return this.oAnalyticalQueryResult;
};
/********************************
*** Private section follows
********************************/
/**
* Enumeration of request types implemented for the analytical binding.
* Every type <T> is implemented with the two methods prepare<T>Request and process<T>Response, names in proper upper camel case notation.
* @private
*/
AnalyticalBinding._requestType = {
groupMembersQuery : 1, // members of a named group G identified by its path /G1/G2/G3/.../G/
totalSizeQuery : 2, // total number of entities in result matching all specified filter conditions
groupMembersAutoExpansionQuery : 3, // all members residing in a group or sub group w.r.t. a given group ID
levelMembersQuery : 4, // members of a given level
reloadMeasuresQuery : 5 // measures of a certain entry
};
AnalyticalBinding._artificialRootContextGroupId = "artificialRootContext";
/**
* @private
*/
AnalyticalBinding.prototype._getContextsForParentContext = function(oParentContext, iStartIndex, iLength,
iThreshold, iLevel, iNumberOfExpandedLevels, bSupressRequest) {
if (oParentContext === undefined) {
return []; // API robustness
}
if (oParentContext && oParentContext.getPath() == "/" + AnalyticalBinding._artificialRootContextGroupId) {
// special case for artificial root contexts: adjust context to point to the real path
oParentContext = this.getModel().getContext("/");
}
var sParentGroupId = this._getGroupIdFromContext(oParentContext, iLevel);
return this._getContextsForParentGroupId(sParentGroupId, iStartIndex, iLength, iThreshold, iNumberOfExpandedLevels, bSupressRequest);
};
/**
* @private
*/
AnalyticalBinding.prototype._getContextsForParentGroupId = function(sParentGroupId, iStartIndex, iLength,
iThreshold, iNumberOfExpandedLevels, bSupressRequest) {
if (sParentGroupId === undefined) {
return []; // API robustness
}
// Set default values if start index, threshold, length or number of expanded levels are not defined
if (!iStartIndex) {
iStartIndex = 0;
}
if (!iLength) {
iLength = this.oModel.iSizeLimit;
}
if (this.mFinalLength[sParentGroupId] && this.mLength[sParentGroupId] < iStartIndex + iLength) {
iLength = this.mLength[sParentGroupId] - iStartIndex;
if (iLength < 0) {
jQuery.sap.log.fatal("invalid start index greater than total group length passed");
}
}
if (!iThreshold) {
iThreshold = 0;
}
if (!iNumberOfExpandedLevels) {
iNumberOfExpandedLevels = 0;
}
if (sParentGroupId == null) {
if (iNumberOfExpandedLevels > 0) {
jQuery.sap.log.fatal("invalid request to determine nodes of root context");
return null;
}
} else {
if (this._getGroupIdLevel(sParentGroupId) >= this.aAggregationLevel.length && iNumberOfExpandedLevels > 0) {
jQuery.sap.log.fatal("invalid request to determine nodes of context with group ID " + sParentGroupId);
return null;
}
if (this._getGroupIdLevel(sParentGroupId) + iNumberOfExpandedLevels > this.aAggregationLevel.length) {
// need to adjust number of levels to expand
iNumberOfExpandedLevels = this.aAggregationLevel.length - this._getGroupIdLevel(sParentGroupId) - 1;
}
}
var aContext = [], bLoadContexts, oGroupSection, oGroupExpansionFirstMissingMember, missingMemberCount;
var iAggregationLevel = sParentGroupId == null ? 0 : this._getGroupIdLevel(sParentGroupId) + 1;
if (!this.aMultiUnitLoadFactor[iAggregationLevel]) {
this.aMultiUnitLoadFactor[iAggregationLevel] = 1;
}
var bGroupLevelAutoExpansionIsActive = iNumberOfExpandedLevels > 0 && sParentGroupId != null;
if (bGroupLevelAutoExpansionIsActive) {
var iMinRequiredLevel = this._getGroupIdLevel(sParentGroupId);
var iAutoExpandGroupsToLevel = iMinRequiredLevel + iNumberOfExpandedLevels;
var bDataAvailable = true;
if (!bSupressRequest) {
oGroupExpansionFirstMissingMember = this._calculateRequiredGroupExpansion(sParentGroupId, iAutoExpandGroupsToLevel, iStartIndex, iLength + iThreshold);
bDataAvailable = oGroupExpansionFirstMissingMember.groupId_Missing == null;
// the following line further reliefs the condition to load data by just looking at the sub-tree
bDataAvailable = bDataAvailable
// first missing member is in a different upper level sub-tree, e.g. sParentGroupId: /A/B/C groupId_Missing: /A/X
|| oGroupExpansionFirstMissingMember.groupId_Missing.length < sParentGroupId.length
// first missing member is in a different lower level sub-tree, e.g. sParentGroupId: /A/B groupId_Missing: /A/C/D
|| oGroupExpansionFirstMissingMember.groupId_Missing.substring(0, sParentGroupId.length) != sParentGroupId;
}
if (bDataAvailable) {
aContext = this._getLoadedContextsForGroup(sParentGroupId, iStartIndex, iLength);
} else {
missingMemberCount = iLength + iThreshold;
}
bLoadContexts = !bDataAvailable;
// finally adjust the number of entities to be loaded by the load factor (after(!) all calculations have been made)
missingMemberCount = Math.ceil(missingMemberCount * this.aMultiUnitLoadFactor[iAggregationLevel]);
} else { // no automatic expansion of group levels
aContext = this._getLoadedContextsForGroup(sParentGroupId, iStartIndex, iLength, bSupressRequest);
bLoadContexts = false;
if (!bSupressRequest) {
oGroupSection = this._calculateRequiredGroupSection(sParentGroupId, iStartIndex, iLength, iThreshold, aContext);
var bPreloadContexts = oGroupSection.length > 0 && iLength < oGroupSection.length;
bLoadContexts = (aContext.length != iLength
&& !(this.mFinalLength[sParentGroupId] && aContext.length >= this.mLength[sParentGroupId] - iStartIndex))
|| bPreloadContexts;
// finally adjust the number of entities to be loaded by the load factor (after(!) all calculations have been made)
oGroupSection.length = Math.ceil(oGroupSection.length * this.aMultiUnitLoadFactor[iAggregationLevel]);
}
}
if (!bLoadContexts) {
// all data available so no request will be issued that might be related to some group of requests
this._cleanupGroupingForCompletedRequest(this._getRequestId(AnalyticalBinding._requestType.groupMembersQuery, {groupId: sParentGroupId}));
}
// check if metadata are already available
var bExecuteRequest = false;
if (this.oModel.getServiceMetadata()) {
// If rows are missing send a request
if (bLoadContexts) {
var bNeedTotalSize = this.bProvideTotalSize && this.iTotalSize == -1 && !this._isRequestPending(this._getRequestId(AnalyticalBinding._requestType.totalSizeQuery));
bExecuteRequest = true;
var aMembersRequestId;
if (this.bUseBatchRequests) {
if (bGroupLevelAutoExpansionIsActive) {
aMembersRequestId = this._prepareGroupMembersAutoExpansionRequestIds(sParentGroupId, iNumberOfExpandedLevels);
for (var i = -1, sRequestId; (sRequestId = aMembersRequestId[++i]) !== undefined; ) {
if (this._isRequestPending(sRequestId)) {
bExecuteRequest = false;
break;
}
}
if (bExecuteRequest) {
this.aBatchRequestQueue.push([ AnalyticalBinding._requestType.groupMembersAutoExpansionQuery, sParentGroupId, oGroupExpansionFirstMissingMember, missingMemberCount, iNumberOfExpandedLevels ]);
}
} else { // ! bGroupLevelAutoExpansionIsActive
bExecuteRequest = !this._isRequestPending(this._getRequestId(AnalyticalBinding._requestType.groupMembersQuery, {groupId: sParentGroupId}));
if (bExecuteRequest) {
this.aBatchRequestQueue.push([ AnalyticalBinding._requestType.groupMembersQuery, sParentGroupId, oGroupSection.startIndex, oGroupSection.length ]);
aMembersRequestId = [ this._getRequestId(AnalyticalBinding._requestType.groupMembersQuery, {groupId: sParentGroupId}) ];
}
}
if (bExecuteRequest && bNeedTotalSize) {
aMembersRequestId.push(this._getRequestId(AnalyticalBinding._requestType.totalSizeQuery));
this._considerRequestGrouping(aMembersRequestId);
this.aBatchRequestQueue.push([ AnalyticalBinding._requestType.totalSizeQuery ]);
}
if (bExecuteRequest) {
if (sParentGroupId == null) { // root node is requested, so discard all not received responses, because the entire table must be set up from scratch
this._abortAllPendingRequests();
}
Promise.resolve().then(AnalyticalBinding.prototype._processRequestQueue.bind(this));
}
} else { // ! bUseBatchRequests
var oMemberRequestDetails;
if (bGroupLevelAutoExpansionIsActive) {
aMembersRequestId = this._prepareGroupMembersAutoExpansionRequestIds(sParentGroupId, iNumberOfExpandedLevels);
for (var j = -1, sMemberRequestId; (sMemberRequestId = aMembersRequestId[++j]) !== undefined; ) {
if (this._isRequestPending(sMemberRequestId)) {
bExecuteRequest = false;
break;
}
}
if (bExecuteRequest) {
oMemberRequestDetails = this._prepareGroupMembersAutoExpansionQueryRequest(AnalyticalBinding._requestType.groupMembersAutoExpansionQuery, sParentGroupId, oGroupExpansionFirstMissingMember, missingMemberCount, iNumberOfExpandedLevels);
}
} else { // ! bGroupLevelAutoExpansionIsActive
bExecuteRequest = !this._isRequestPending(this._getRequestId(AnalyticalBinding._requestType.groupMembersQuery, {groupId: sParentGroupId}));
if (bExecuteRequest) {
oMemberRequestDetails = this._prepareGroupMembersQueryRequest(AnalyticalBinding._requestType.groupMembersQuery, sParentGroupId, oGroupSection.startIndex, oGroupSection.length);
aMembersRequestId = [ oMemberRequestDetails.sRequestId ];
}
}
if (bExecuteRequest) {
if (sParentGroupId == null) { // root node is requested, so discard all not received responses, because the entire table must be set up from scratch
this._abortAllPendingRequests();
}
this._executeQueryRequest(oMemberRequestDetails);
if (bNeedTotalSize && !oMemberRequestDetails.bIsFlatListRequest) {
aMembersRequestId.push(this._getRequestId(AnalyticalBinding._requestType.totalSizeQuery));
this._considerRequestGrouping(aMembersRequestId);
this._executeQueryRequest(this._prepareTotalSizeQueryRequest(AnalyticalBinding._requestType.totalSizeQuery));
}
}
}
}
}
return aContext;
};
AnalyticalBinding.prototype._processRequestQueue = function(aRequestQueue) {
// if no argument is given: use the shared member aBatchRequestQueue
if (aRequestQueue === undefined || aRequestQueue === null) {
//safety check: empty array fallback in case the "global" batch queue is not defined yet
aRequestQueue = this.aBatchRequestQueue || [];
}
// step out if the request queue is still empty after our previous checks
if (aRequestQueue.length == 0) {
return;
}
var aRequestDetails = [];
var bFoundFlatListRequest = false;
var i, oRequestDetails, aRequestQueueEntry;
// create request objects: process group member requests first to detect flat list requests
for (i = -1; (aRequestQueueEntry = aRequestQueue[++i]) !== undefined;) {
if (aRequestQueueEntry[0] == AnalyticalBinding._requestType.groupMembersQuery) { // request type is at array index 0
oRequestDetails = AnalyticalBinding.prototype._prepareGroupMembersQueryRequest.apply(this, aRequestQueueEntry);
bFoundFlatListRequest = bFoundFlatListRequest || oRequestDetails.bIsFlatListRequest;
aRequestDetails.push(oRequestDetails);
}
}
// create request objects for all other request types
for (i = -1; (aRequestQueueEntry = aRequestQueue[++i]) !== undefined;) {
oRequestDetails = null;
switch (aRequestQueueEntry[0]) { // different request types
case AnalyticalBinding._requestType.groupMembersQuery:
continue; // handled above
case AnalyticalBinding._requestType.totalSizeQuery:
if (!bFoundFlatListRequest) {
oRequestDetails = AnalyticalBinding.prototype._prepareTotalSizeQueryRequest.apply(this, aRequestQueueEntry);
aRequestDetails.push(oRequestDetails);
}
break;
case AnalyticalBinding._requestType.groupMembersAutoExpansionQuery:
oRequestDetails = AnalyticalBinding.prototype._prepareGroupMembersAutoExpansionQueryRequest.apply(this, aRequestQueueEntry);
for (var j = -1, oLevelMembersRequestDetails; (oLevelMembersRequestDetails = oRequestDetails.aGroupMembersAutoExpansionRequestDetails[++j]) !== undefined; ) {
aRequestDetails.push(oLevelMembersRequestDetails);
}
break;
case AnalyticalBinding._requestType.reloadMeasuresQuery: {
var aReloadMeasureRequestDetails = aRequestQueueEntry[1];
for (var k = -1, oReloadMeasureRequestDetails; (oReloadMeasureRequestDetails = aReloadMeasureRequestDetails[++k]) !== undefined; ) {
aRequestDetails.push(oReloadMeasureRequestDetails);
}
break;
}
default:
jQuery.sap.log.fatal("unhandled request type " + aRequestQueue[i][0]);
continue;
}
}
// execute them either directly in case of a single request or via a batch request
if (aRequestDetails.length > 1) {
this._executeBatchRequest(aRequestDetails);
} else {
this._executeQueryRequest(aRequestDetails[0]);
}
// clean up request queue after processing, if it is based on the shared member request queue
if (aRequestQueue === this.aBatchRequestQueue) {
this.aBatchRequestQueue = [];
}
};
/** *************************************************************** */
/**
* @private
*/
AnalyticalBinding.prototype._prepareGroupMembersQueryRequest = function(iRequestType, sGroupId, iStartIndex, iLength) {
var aGroupId = [];
// (0) set up analytical OData request object
var oAnalyticalQueryRequest = new odata4analytics.QueryResultRequest(this.oAnalyticalQueryResult);
oAnalyticalQueryRequest.setResourcePath(this._getResourcePath());
oAnalyticalQueryRequest.getSortExpression().clear();
// (1) analyze aggregation level of sGroupId
// indexes to elements of this.aMaxAggregationLevel marking begin and end of the requested child level
var iChildGroupFromLevel = 0, iChildGroupToLevel = -1;
if (sGroupId) {
aGroupId = this._getGroupIdComponents(sGroupId);
iChildGroupFromLevel = iChildGroupToLevel = aGroupId.length;
var iUngroupedParentLevelCount = 0;
// determine offset for child level (depends on grouped column property of higher aggregation levels)
// Ex: Assume aMaxAggregationLevel with (G=grouped,U=ungrouped): [ G1 U1 U2 G2 U3 U4 G3 F5 F6 ... ]
// For sGroupId = "G1/G2", initial iChildGroupFromLevel is 2. The following loop will increment it to 4
// and consequently point to U3
for (var j = 0, iLevel = 0; j < iChildGroupFromLevel; iLevel++) {
if (this.oDimensionDetailsSet[this.aMaxAggregationLevel[iLevel]].grouped == false) {
++iUngroupedParentLevelCount;
} else {
++j;
}
}
// adjust child levels by number of ungrouped parent levels!
iChildGroupFromLevel = iChildGroupToLevel = iChildGroupFromLevel + iUngroupedParentLevelCount;
// determine index range for aggregation levels included in child level
// (rule: take all lower levels up to and including the first grouped level; G3 in above example
if (this.aMaxAggregationLevel.length > 0) {
while (this.oDimensionDetailsSet[this.aMaxAggregationLevel[iChildGroupToLevel]].grouped == false) {
if (++iChildGroupToLevel == this.aMaxAggregationLevel.length) {
break;
}
}
}
}
// (2) determine if the sub groups will effectively represent leafs (relevant for un-"total"ed columns, see below)
var bIsLeafGroupsRequest = iChildGroupToLevel >= this.aMaxAggregationLevel.length - 1;
// (3) set aggregation level for child nodes
var aAggregationLevel = this.aMaxAggregationLevel.slice(0, iChildGroupToLevel + 1);
oAnalyticalQueryRequest.setAggregationLevel(aAggregationLevel);
for (var i = 0; i < aAggregationLevel.length; i++) {
// specify components requested for this level (key, text, attributes)
var oDimensionDetails = this.oDimensionDetailsSet[aAggregationLevel[i]];
// as we combine the key and text in the group header we also need the text!
var bIncludeText = (oDimensionDetails.textPropertyName != undefined);
oAnalyticalQueryRequest.includeDimensionKeyTextAttributes(oDimensionDetails.name, // bIncludeKey: No, always needed!
true, bIncludeText, oDimensionDetails.aAttributeName);
// define a default sort order in case no sort criteria have been provided externally
if (oDimensionDetails.grouped) {
oAnalyticalQueryRequest.getSortExpression().addSorter(aAggregationLevel[i], odata4analytics.SortOrder.Ascending);
}
}
// (4) set filter
var oFilterExpression = oAnalyticalQueryRequest.getFilterExpression();
oFilterExpression.clear();
if (this.aApplicationFilter) {
oFilterExpression.addUI5FilterConditions(this.aApplicationFilter);
}
if (this.aControlFilter) {
oFilterExpression.addUI5FilterConditions(this.aControlFilter);
}
if (iChildGroupFromLevel >= 1) {
for (var k = 0, l = aGroupId.length; k < l; k++) {
oFilterExpression.removeConditions(this.aAggregationLevel[k]);
oFilterExpression.addCondition(this.aAggregationLevel[k], FilterOperator.EQ, aGroupId[k]);
}
}
// (5) set measures as requested per column
var bIncludeRawValue;
var bIncludeFormattedValue;
var bIncludeUnitProperty;
var oMeasureDetails;
var aSelectedUnitPropertyName = [];
if (sGroupId != null || this.bProvideGrandTotals) {
// select measures if the requested group is not the root context i.e. the grand totals row, or grand totals shall be determined
oAnalyticalQueryRequest.setMeasures(this.aMeasureName);
for ( var sMeasureName in this.oMeasureDetailsSet) {
oMeasureDetails = this.oMeasureDetailsSet[sMeasureName];
if (!bIsLeafGroupsRequest && this.mAnalyticalInfoByProperty[sMeasureName].total == false) {
bIncludeRawValue = false;
bIncludeFormattedValue = false;
bIncludeUnitProperty = false;
} else {
bIncludeRawValue = (oMeasureDetails.rawValuePropertyName != undefined);
bIncludeFormattedValue = (oMeasureDetails.formattedValuePropertyName != undefined);
bIncludeUnitProperty = (oMeasureDetails.unitPropertyName != undefined);
if (bIncludeUnitProperty) {
// remember unit property together with using measure raw value property for response analysis in success handler
if (jQuery.inArray(oMeasureDetails.unitPropertyName, aSelectedUnitPropertyName) == -1) {
aSelectedUnitPropertyName.push(oMeasureDetails.unitPropertyName);
}
}
}
oAnalyticalQueryRequest.includeMeasureRawFormattedValueUnit(oMeasureDetails.name, bIncludeRawValue,
bIncludeFormattedValue, bIncludeUnitProperty);
}
// exclude those unit properties from the selected that are included in the current aggregation level
for (var n in aAggregationLevel) {
var iMatchingIndex;
if ((iMatchingIndex = jQuery.inArray(aAggregationLevel[n], aSelectedUnitPropertyName)) != -1) {
aSelectedUnitPropertyName.splice(iMatchingIndex, 1);
}
}
}
// (6) set sort order
var oSorter = oAnalyticalQueryRequest.getSortExpression();
for (var m = 0; m < this.aSorter.length; m++) {
if (this.aSorter[m]) {
oSorter.addSorter(this.aSorter[m].sPath, this.aSorter[m].bDescending ? odata4analytics.SortOrder.Descending : odata4analytics.SortOrder.Ascending);
}
}
// (7) set result page boundaries
if (iLength == 0) {
jQuery.sap.log.fatal("unhandled case: load 0 entities of sub group");
}
var oKeyIndexMapping = this._getKeyIndexMapping(sGroupId, iStartIndex);
if (!this.bNoPaging) {
oAnalyticalQueryRequest.setResultPageBoundaries(oKeyIndexMapping.iServiceKeyIndex + 1, oKeyIndexMapping.iServiceKeyIndex + iLength);
}
// (8) request result entity count
oAnalyticalQueryRequest.setRequestOptions(null, !this.mFinalLength[sGroupId]);
return {
iRequestType : iRequestType,
sRequestId : this._getRequestId(AnalyticalBinding._requestType.groupMembersQuery, {groupId: sGroupId}),
oAnalyticalQueryRequest : oAnalyticalQueryRequest,
sGroupId : sGroupId,
aSelectedUnitPropertyName : aSelectedUnitPropertyName,
aAggregationLevel : aAggregationLevel,
bIsFlatListRequest : bIsLeafGroupsRequest && iChildGroupFromLevel == 0,
bIsLeafGroupsRequest : bIsLeafGroupsRequest,
iStartIndex : iStartIndex,
iLength : iLength,
oKeyIndexMapping : oKeyIndexMapping
};
};
/**
* @private
*/
AnalyticalBinding.prototype._prepareTotalSizeQueryRequest = function(iRequestType) {
// (0) set up analytical OData request object
var oAnalyticalQueryRequest = new odata4analytics.QueryResultRequest(this.oAnalyticalQueryResult);
oAnalyticalQueryRequest.setResourcePath(this._getResourcePath());
// (1) set aggregation level
oAnalyticalQueryRequest.setAggregationLevel(this.aMaxAggregationLevel);
oAnalyticalQueryRequest.setMeasures([]);
// (2) set filter
var oFilterExpression = oAnalyticalQueryRequest.getFilterExpression();
oFilterExpression.clear();
if (this.aApplicationFilter) {
oFilterExpression.addUI5FilterConditions(this.aApplicationFilter);
}
if (this.aControlFilter) {
oFilterExpression.addUI5FilterConditions(this.aControlFilter);
}
// (2) fetch no data
oAnalyticalQueryRequest.setRequestOptions(null, null, true);
// (3) request result entity count
oAnalyticalQueryRequest.setRequestOptions(null, true);
return {
iRequestType : iRequestType,
sRequestId : this._getRequestId(AnalyticalBinding._requestType.totalSizeQuery),
oAnalyticalQueryRequest : oAnalyticalQueryRequest
};
};
/**
* @private
*/
AnalyticalBinding.prototype._prepareGroupMembersAutoExpansionQueryRequest = function(iRequestType, sGroupId, oGroupExpansionFirstMissingMember, iLength, iNumberOfExpandedLevels) {
var that = this;
// local helper function for creating filter expressions for all group level requests
/*
* Let G be the group ID for the root for the first missing member, e.g. G = /A/B/C/D/.../W/X/, and (optional) startIndex_Missing > 0 for the children of X.
* Let P_1, P_2, ... be the properties for the different grouping levels.
* Then, for every level l, 1 <= l <= iAutoExpandGroupsToLevel, the filter expression
* is // every such expression is an instance of aLevelFilterCondition, see in code below
* [0] ( P_1 = A and P_2 = B and .. P_l >= X )
* [1] or ( P_1 = A and P_2 = B and .. P_(l-1) > W ) // every such line is an instance of aIntermediateLevelFilterCondition, see in code below
* ...
* [N] or ( P_1 > A )
* assuming that P_1, P_2, ... are all to be sorted in ascending order. For any deviation, replace > with <.
*
* Additional rules considered:
* (R1) For every auto-expand level with a higher number than the level of the first missing member,
* the strict comparison (< or >) has to include equality (<= or >=) to match all needed members of these deep levels.
* (R2) If startIndex_Missing > 0, then the R1 does not apply. here,
* (R2.1) the strict comparison (< or >) must be replaced by equality (=)
* (R2.2) the partial filter expression for every auto-expand level with a higher number than the level of the first missing member
* must be extended by a condition P_Y > Y, where Y is the child of X at position startIndex_Missing - 1,
* and P_Y is the property for this grouping level.
*/
var prepareLevelFilterExpressions = function(oGroupExpansionFirstMissingMember, iAutoExpandGroupsToLevel) {
var aFilterArray = [];
if (oGroupExpansionFirstMissingMember.groupId_Missing == null) {
jQuery.sap.log.fatal("missing group Id not present");
return aFilterArray;
}
var aGroupIdComponents_Missing = that._getGroupIdComponents(oGroupExpansionFirstMissingMember.groupId_Missing);
var iGroupIdLevel_Missing = aGroupIdComponents_Missing.length;
if (iGroupIdLevel_Missing > iAutoExpandGroupsToLevel) {
jQuery.sap.log.fatal("the given group ID is too deep for requested level for auto expansion");
return aFilterArray;
}
// create template for every term of the filter expression
var aTemplateFilter = [];
for (var i = 0; i < iGroupIdLevel_Missing; i++) {
var sGroupProperty = that.aAggregationLevel[i];
var sValue = aGroupIdComponents_Missing[i];
var sFilterOperator = that._getFilterOperatorMatchingPropertySortOrder(sGroupProperty);
aTemplateFilter[i] = new sap.ui.model.Filter(sGroupProperty, sFilterOperator, sValue);
}
// if first missing member start within a partially loaded group, an extra condition will be needed below
var oFirstMissingMemberStartIndexLastKnownFilterCondition = null;
if (oGroupExpansionFirstMissingMember.startIndex_Missing > 0) {
var oFirstMissingMemberStartIndexLastKnownGroupContextKey = that._getKey(oGroupExpansionFirstMissingMember.groupId_Missing,
oGroupExpansionFirstMissingMember.startIndex_Missing - 1);
var oFirstMissingMemberStartIndexLastKnownObject = that.oModel.getObject("/" + oFirstMissingMemberStartIndexLastKnownGroupContextKey);
var sFirstMissingMemberStartIndexAggregationLevel = that.aAggregationLevel[iGroupIdLevel_Missing];
var sFirstMissingMemberStartIndexLastKnownValue = oFirstMissingMemberStartIndexLastKnownObject
[sFirstMissingMemberStartIndexAggregationLevel];
oFirstMissingMemberStartIndexLastKnownFilterCondition = new sap.ui.model.Filter(sFirstMissingMemberStartIndexAggregationLevel,
that._getFilterOperatorMatchingPropertySortOrder(sFirstMissingMemberStartIndexAggregationLevel, false),
sFirstMissingMemberStartIndexLastKnownValue);
}
// now create the filter expressions (filter object arrays) for every group level to be requested
for (var iLevel = 0; iLevel < iAutoExpandGroupsToLevel; iLevel++) {
var aLevelFilterCondition = [];
var iNumberOfIntermediateLevelConditions = Math.min(iGroupIdLevel_Missing, iLevel + 1);
for (var iIntermediateLevel = 0; iIntermediateLevel < iNumberOfIntermediateLevelConditions; iIntermediateLevel++) {
var aIntermediateLevelFilterCondition = [];
var iNumberOfLevelConditions = Math.min(iGroupIdLevel_Missing, iIntermediateLevel + 1);
var bAddExtraConditionForFirstMissingMemberStartIndexLastKnown =
oGroupExpansionFirstMissingMember.startIndex_Missing > 0;
for (var iLevelCondition = 0; iLevelCondition < iNumberOfLevelConditions; iLevelCondition++) {
// create filter condition from template
var oFilterCondition = new sap.ui.model.Filter("x", sap.ui.model.FilterOperator.EQ, "x");
oFilterCondition = jQuery.extend(true, oFilterCondition, aTemplateFilter[iLevelCondition]);
if (iNumberOfLevelConditions > 1 && iLevelCondition < iNumberOfLevelConditions - 1) {
oFilterCondition.sOperator = sap.ui.model.FilterOperator.EQ;
}
if (iLevelCondition == iGroupIdLevel_Missing - 1
&& iLevel > iGroupIdLevel_Missing - 1
&& !bAddExtraConditionForFirstMissingMemberStartIndexLastKnown) { // rule (R1)
if (oFilterCondition.sOperator == sap.ui.model.FilterOperator.GT) {
oFilterCondition.sOperator = sap.ui.model.FilterOperator.GE;
} else { // it must be LT
oFilterCondition.sOperator = sap.ui.model.FilterOperator.LE;
}
}
aIntermediateLevelFilterCondition.push(oFilterCondition);
}
// create the instance for ( P_1 = A and P_2 = B and .. P_(l-1) > W )
if (aIntermediateLevelFilterCondition.length > 0) {
aLevelFilterCondition.push(new sap.ui.model.Filter(aIntermediateLevelFilterCondition, true));
// add an extra intermediate filter condition to reflect start position at oGroupExpansionFirstMissingMember.startIndex_Missing
if (iLevel > iGroupIdLevel_Missing - 1
&& iIntermediateLevel == iGroupIdLevel_Missing - 1
&& bAddExtraConditionForFirstMissingMemberStartIndexLastKnown) { // rule (R2)
// create a copy of the constructed intermediate filter condition
var aStartIndexFilterCondition = [];
for (var j = 0; j < aIntermediateLevelFilterCondition.length; j++) {
var oConditionCopy = new sap.ui.model.Filter("x", sap.ui.model.FilterOperator.EQ, "x");
oConditionCopy = jQuery.extend(true, oConditionCopy, aIntermediateLevelFilterCondition[j]);
aStartIndexFilterCondition.push(oConditionCopy);
}
aStartIndexFilterCondition[iGroupIdLevel_Missing - 1].sOperator = sap.ui.model.FilterOperator.EQ; // (R2.1)
aStartIndexFilterCondition.push(oFirstMissingMemberStartIndexLastKnownFilterCondition); // (R2.2)
aLevelFilterCondition.push(new sap.ui.model.Filter(aStartIndexFilterCondition, true));
break;
}
}
}
// create the entire filter expression
if (aLevelFilterCondition.length > 0) {
aFilterArray[iLevel] = new sap.ui.model.Filter(aLevelFilterCondition, false);
} else {
aFilterArray[iLevel] = null;
}
}
return aFilterArray;
};
// local helper function for requesting members of a given level (across groups) - copied from _prepareGroupMembersQueryRequest & adapted
var prepareLevelMembersQueryRequest = function(iRequestType, sGroupId, iLevel, oGroupContextFilter,
iStartIndex, iLength, bAvoidLengthUpdate, bUseStartIndexForSkip) {
// (1) set up analytical OData request object
var oAnalyticalQueryRequest = new odata4analytics.QueryResultRequest(that.oAnalyticalQueryResult);
oAnalyticalQueryRequest.setResourcePath(that._getResourcePath());
oAnalyticalQueryRequest.getSortExpression().clear();
// (2) analyze aggregation level of sGroupId
// indexes to elements of this.aMaxAggregationLevel marking begin and end of the requested child level
var iChildGroupFromLevel = 0, iChildGroupToLevel = -1;
iChildGroupFromLevel = iChildGroupToLevel = iLevel - 1;
var iUngroupedParentLevelCount = 0;
// determine offset for child level (depends on grouped column property of higher aggregation levels)
// Ex: Assume aMaxAggregationLevel with (G=grouped,U=ungrouped): [ G1 U1 U2 G2 U3 U4 G3 F5 F6 ... ]
// For sGroupId = "G1/G2", initial iChildGroupFromLevel is 2. The following loop will increment it to 4
// and consequently point to U3
for (var i = 0, iParentLevel = 0; i < iChildGroupFromLevel; iParentLevel++) {
if (that.oDimensionDetailsSet[that.aMaxAggregationLevel[iParentLevel]].grouped == false) {
++iUngroupedParentLevelCount;
} else {
++i;
}
}
// adjust child levels by number of ungrouped parent levels!
iChildGroupFromLevel = iChildGroupToLevel = iChildGroupFromLevel + iUngroupedParentLevelCount;
// determine index range for aggregation levels included in child level
// (rule: take all lower levels up to and including the first grouped level; G3 in above example
if (that.aMaxAggregationLevel.length > 0) {
while (that.oDimensionDetailsSet[that.aMaxAggregationLevel[iChildGroupToLevel]].grouped == false) {
if (++iChildGroupToLevel == that.aMaxAggregationLevel.length) {
break;
}
}
}
// determine if the sub groups will effectively represent leafs (relevant for un-"total"ed columns, see below)
var bIsLeafGroupsRequest = iChildGroupToLevel >= that.aMaxAggregationLevel.length - 1;
// (3) set aggregation level for child nodes
var aAggregationLevel = that.aMaxAggregationLevel.slice(0, iChildGroupToLevel + 1);
oAnalyticalQueryRequest.setAggregationLevel(aAggregationLevel);
for (var l = 0; l < aAggregationLevel.length; l++) {
var oDimensionDetails = that.oDimensionDetailsSet[aAggregationLevel[l]];
var bIncludeText = (oDimensionDetails.textPropertyName != undefined);
oAnalyticalQueryRequest.includeDimensionKeyTextAttributes(oDimensionDetails.name, // bIncludeKey: No, always needed!
true, bIncludeText, oDimensionDetails.aAttributeName);
// define a default sort order in case no sort criteria have been provided externally
if (oDimensionDetails.grouped) {
oAnalyticalQueryRequest.getSortExpression().addSorter(aAggregationLevel[l], odata4analytics.SortOrder.Ascending);
}
}
// (4) set filter
var oFilterExpression = oAnalyticalQueryRequest.getFilterExpression();
oFilterExpression.clear();
if (that.aApplicationFilter) {
oFilterExpression.addUI5FilterConditions(that.aApplicationFilter);
}
if (that.aControlFilter) {
oFilterExpression.addUI5FilterConditions(that.aControlFilter);
}
if (oGroupContextFilter) {
oFilterExpression.addUI5FilterConditions([oGroupContextFilter]);
}
// (5) set measures as requested per column
var bIncludeRawValue;
var bIncludeFormattedValue;
var bIncludeUnitProperty;
var oMeasureDetails;
var aSelectedUnitPropertyName = [];
// select measures if the requested group is not the root context i.e. the grand totals row, or grand totals shall be determined
oAnalyticalQueryRequest.setMeasures(that.aMeasureName);
for ( var sMeasureName in that.oMeasureDetailsSet) {
oMeasureDetails = that.oMeasureDetailsSet[sMeasureName];
if (!bIsLeafGroupsRequest && that.mAnalyticalInfoByProperty[sMeasureName].total == false) {
bIncludeRawValue = false;
bIncludeFormattedValue = false;
bIncludeUnitProperty = false;
} else {
bIncludeRawValue = (oMeasureDetails.rawValuePropertyName != undefined);
bIncludeFormattedValue = (oMeasureDetails.formattedValuePropertyName != undefined);
bIncludeUnitProperty = (oMeasureDetails.unitPropertyName != undefined);
if (bIncludeUnitProperty) {
// remember unit property together with using measure raw value property for response analysis in success handler
if (jQuery.inArray(oMeasureDetails.unitPropertyName, aSelectedUnitPropertyName) == -1) {
aSelectedUnitPropertyName.push(oMeasureDetails.unitPropertyName);
}
}
}
oAnalyticalQueryRequest.includeMeasureRawFormattedValueUnit(oMeasureDetails.name, bIncludeRawValue,
bIncludeFormattedValue, bIncludeUnitProperty);
}
// exclude those unit properties from the selected that are included in the current aggregation level
for ( var j in aAggregationLevel) {
var iMatchingIndex;
if ((iMatchingIndex = jQuery.inArray(aAggregationLevel[j], aSelectedUnitPropertyName)) != -1) {
aSelectedUnitPropertyName.splice(iMatchingIndex, 1);
}
}
// (6) set sort order
var oSorter = oAnalyticalQueryRequest.getSortExpression();
for (var k = 0; k < that.aSorter.length; k++) {
if (that.aSorter[k]) {
oSorter.addSorter(that.aSorter[k].sPath, that.aSorter[k].bDescending ? odata4analytics.SortOrder.Descending : odata4analytics.SortOrder.Ascending);
}
}
// (7) set result page boundaries
if (iLength == 0) {
jQuery.sap.log.fatal("unhandled case: load 0 entities of sub group");
}
var iEffectiveStartIndex = iStartIndex;
if (!bUseStartIndexForSkip) {
iEffectiveStartIndex = 0; // and the skip-value is encoded in the filter expression; still the start index is relevant and kept (see below) for booking the result entries
} else {
// when bUseStartIndexForSkip is set and no filter conditions are given, the top level must also be paged
// calculate the number of loaded entries per level
var iServiceLengthForGroupIdMissing = 0;
for (var sGID in that.mServiceKey) {
if (sGID.split("/").length === iLevel + 1) {
iServiceLengthForGroupIdMissing += that.mServiceKey[sGID].length;
}
}
iEffectiveStartIndex = Math.max(iEffectiveStartIndex, iServiceLengthForGroupIdMissing);
}
if (!that.bNoPaging) {
oAnalyticalQueryRequest.setResultPageBoundaries(iEffectiveStartIndex + 1, iLength);
}
return {
iRequestType : iRequestType,
sRequestId : null, // set by caller
oAnalyticalQueryRequest : oAnalyticalQueryRequest,
iLevel : iLevel,
aSelectedUnitPropertyName : aSelectedUnitPropertyName,
aAggregationLevel : aAggregationLevel,
bIsFlatListRequest : bIsLeafGroupsRequest,
bIsLeafGroupsRequest : bIsLeafGroupsRequest,
iStartIndex : iStartIndex,
iLength : iLength,
bAvoidLengthUpdate : bAvoidLengthUpdate
};
};
// function implementation starts here
var aGroupMembersAutoExpansionRequestDetails = [];
var aRequestId = [];
if (!oGroupExpansionFirstMissingMember) {
jQuery.sap.log.fatal("no first missing group member specified");
}
var iAutoExpandGroupsToLevel = this._getGroupIdLevel(sGroupId) + iNumberOfExpandedLevels + 1;
var aGroupIdComponents_Missing = that._getGroupIdComponents(oGroupExpansionFirstMissingMember.groupId_Missing);
var iGroupIdLevel_Missing = aGroupIdComponents_Missing.length;
var aFilterArray = prepareLevelFilterExpressions(oGroupExpansionFirstMissingMember, iAutoExpandGroupsToLevel);
var sGroupIdAtLevel;
for (var iLevel = 1; iLevel <= iAutoExpandGroupsToLevel; iLevel++) {
var iStartIndex;
// determine start index
if (iLevel >= iGroupIdLevel_Missing + 2) {
iStartIndex = 0;
sGroupIdAtLevel = undefined;
} else if (iLevel == iGroupIdLevel_Missing + 1) {
iStartIndex = oGroupExpansionFirstMissingMember.startIndex_Missing;
sGroupIdAtLevel = oGroupExpansionFirstMissingMember.groupId_Missing;
} else if (iGroupIdLevel_Missing > 0) {
if (iLevel == iGroupIdLevel_Missing) {
sGroupIdAtLevel = oGroupExpansionFirstMissingMember.groupId_Missing;
} else {
sGroupIdAtLevel = this._getGroupIdAncestors(oGroupExpansionFirstMissingMember.groupId_Missing, -(iGroupIdLevel_Missing - iLevel))[0];
}
var sGroupIdAtParentLevel = this._getGroupIdAncestors(oGroupExpansionFirstMissingMember.groupId_Missing, -(iGroupIdLevel_Missing - iLevel + 1))[0];
if (!sGroupIdAtParentLevel) {
jQuery.sap.log.fatal("failed to determine group id at parent level; group ID = " + sGroupId + ", level = " + iLevel);
}
iStartIndex = this._findKeyIndex(sGroupIdAtParentLevel, this.mEntityKey[sGroupIdAtLevel]);
if (iStartIndex == -1) {
jQuery.sap.log.fatal("failed to determine position of value " + sGroupIdAtLevel + " in group " + sGroupIdAtParentLevel);
}
sGroupIdAtLevel = sGroupIdAtParentLevel;
iStartIndex++; // point to first missing position
}
// determine other parameters of the request
var iLengthForLevel = iLength > iLevel ? Math.ceil((iLength - iLevel) / (iAutoExpandGroupsToLevel - iLevel + 1)) : iLength;
var oLevelFilter = aFilterArray[iLevel - 1];
if (this.bUseAcceleratedAutoExpand) {
var oLevelMembersRequestDetails = prepareLevelMembersQueryRequest(AnalyticalBinding._requestType.levelMembersQuery, sGroupId,
iLevel, oLevelFilter, iStartIndex, iLengthForLevel, false, oLevelFilter == null ? true : false); // rem: bUseStartIndexForSkip==false, because it is encoded in the filter condition
oLevelMembersRequestDetails.sGroupId_Missing_AtLevel = sGroupIdAtLevel; // also remember group ID at the current level; needed for processing responses
oLevelMembersRequestDetails.sRequestId = this._getRequestId(AnalyticalBinding._requestType.levelMembersQuery, { groupId: sGroupId, level: iLevel });
aGroupMembersAutoExpansionRequestDetails.push(oLevelMembersRequestDetails);
aRequestId.push(oLevelMembersRequestDetails.sRequestId);
} else if (oLevelFilter && oLevelFilter.aFilters.length > 0) {
if (!oLevelFilter._bMultiFilter || oLevelFilter.bAnd) { // TODO remove this test once impl got mature to get rid of access to internal member; it is a consistency check if break-up will deliver expected results...
jQuery.sap.log.fatal("level filter in wrong shape; cannot break it up");
}
for (var i = 0; i < oLevelFilter.aFilters.length; i++) { // break up level filter into its tuple filters combined with logical OR
var oTupleFilter = oLevelFilter.aFilters[i];
var oLevelMembersRequestDetails2 = prepareLevelMembersQueryRequest(AnalyticalBinding._requestType.levelMembersQuery, sGroupId,
iLevel, oTupleFilter, iStartIndex, iLengthForLevel, false, oLevelFilter == null ? true : false); // rem: bUseStartIndexForSkip==false, because it is encoded in the filter condition
oLevelMembersRequestDetails2.sGroupId_Missing_AtLevel = sGroupIdAtLevel; // also remember group ID at the current level; needed for processing responses
oLevelMembersRequestDetails2.sRequestId = this._getRequestId(AnalyticalBinding._requestType.levelMembersQuery, { groupId: sGroupId, level: iLevel, tupleIndex: i });
aGroupMembersAutoExpansionRequestDetails.push(oLevelMembersRequestDetails2);
aRequestId.push(oLevelMembersRequestDetails2.sRequestId);
}
} else { // no level filter given, so no need to break up anything, hence a single request is sufficient for this level
var oLevelMembersRequestDetails3 = prepareLevelMembersQueryRequest(AnalyticalBinding._requestType.levelMembersQuery, sGroupId,
iLevel, null /*oLevelFilter*/, iStartIndex, iLengthForLevel, false, oLevelFilter == null ? true : false); // rem: bUseStartIndexForSkip==false, because it is encoded in the filter condition
oLevelMembersRequestDetails3.sGroupId_Missing_AtLevel = sGroupIdAtLevel; // also remember group ID at the current level; needed for processing responses
oLevelMembersRequestDetails3.sRequestId = this._getRequestId(AnalyticalBinding._requestType.levelMembersQuery, { groupId: sGroupId, level: iLevel });
aGroupMembersAutoExpansionRequestDetails.push(oLevelMembersRequestDetails3);
aRequestId.push(oLevelMembersRequestDetails3.sRequestId);
}
}
return {
iRequestType : iRequestType,
aRequestId : aRequestId,
aGroupMembersAutoExpansionRequestDetails : aGroupMembersAutoExpansionRequestDetails,
sGroupId : sGroupId,
iLength : iLength
};
};
/**
* @private
*/
AnalyticalBinding.prototype._prepareReloadMeasurePropertiesQueryRequest = function(iRequestType, oGroupMembersRequestDetails, oMultiUnitRepresentative) {
// build OData request based on given request details
// (1) set up analytical OData request object
var oAnalyticalQueryRequest = new odata4analytics.QueryResultRequest(this.oAnalyticalQueryResult);
oAnalyticalQueryRequest.setResourcePath(this._getResourcePath());
oAnalyticalQueryRequest.getSortExpression().clear();
// (2) set aggregation level
var aAggregationLevel = oGroupMembersRequestDetails.aAggregationLevel;
oAnalyticalQueryRequest.setAggregationLevel(aAggregationLevel);
var bIsLeafGroupsRequest = oGroupMembersRequestDetails.bIsLeafGroupsRequest;
// (3) set filter
var oFilterExpression = oAnalyticalQueryRequest.getFilterExpression();
oFilterExpression.clear();
if (this.aApplicationFilter) {
oFilterExpression.addUI5FilterConditions(this.aApplicationFilter);
}
if (this.aControlFilter) {
oFilterExpression.addUI5FilterConditions(this.aControlFilter);
}
// add conditions for aggregated dimension key
var aAggregationDimensionKeyFilter = [];
for (var i = 0; i < aAggregationLevel.length; i++) {
var oFilter = new sap.ui.model.Filter(aAggregationLevel[i], sap.ui.model.FilterOperator.EQ, oMultiUnitRepresentative.oEntry[aAggregationLevel[i]]);
aAggregationDimensionKeyFilter.push(oFilter);
}
oFilterExpression.addUI5FilterConditions(aAggregationDimensionKeyFilter);
// (4) set measures as requested per column
var bIncludeRawValue;
var bIncludeFormattedValue;
var bIncludeUnitProperty;
var oMeasureDetails;
var aSelectedUnitPropertyName = [];
// consider only those mentioned in oMultiUnitRepresentative.aReloadMeasurePropertyName
oAnalyticalQueryRequest.setMeasures(oMultiUnitRepresentative.aReloadMeasurePropertyName);
for ( var sMeasureName in this.oMeasureDetailsSet) {
oMeasureDetails = this.oMeasureDetailsSet[sMeasureName];
if (jQuery.inArray(oMeasureDetails.name, oMultiUnitRepresentative.aReloadMeasurePropertyName) == -1) {
continue;
}
if (!bIsLeafGroupsRequest && this.mAnalyticalInfoByProperty[sMeasureName].total == false) {
bIncludeRawValue = false;
bIncludeFormattedValue = false;
bIncludeUnitProperty = false;
} else {
bIncludeRawValue = (oMeasureDetails.rawValuePropertyName != undefined);
bIncludeFormattedValue = (oMeasureDetails.formattedValuePropertyName != undefined);
bIncludeUnitProperty = (oMeasureDetails.unitPropertyName != undefined);
if (bIncludeUnitProperty) {
// remember unit property together with using measure raw value property for response analysis in success handler
if (jQuery.inArray(oMeasureDetails.unitPropertyName, aSelectedUnitPropertyName) == -1) {
aSelectedUnitPropertyName.push(oMeasureDetails.unitPropertyName);
}
}
}
oAnalyticalQueryRequest.includeMeasureRawFormattedValueUnit(oMeasureDetails.name, bIncludeRawValue,
bIncludeFormattedValue, bIncludeUnitProperty);
}
// exclude those unit properties from the selected that are included in the current aggregation level
for ( var j in aAggregationLevel) {
var iMatchingIndex;
if ((iMatchingIndex = jQuery.inArray(aAggregationLevel[j], aSelectedUnitPropertyName)) != -1) {
aSelectedUnitPropertyName.splice(iMatchingIndex, 1);
}
}
return {
iRequestType : iRequestType,
sRequestId : this._getRequestId(AnalyticalBinding._requestType.reloadMeasuresQuery, {multiUnitEntryKey: this.oModel.getKey(oMultiUnitRepresentative.oEntry)}),
oAnalyticalQueryRequest : oAnalyticalQueryRequest,
aSelectedUnitPropertyName : aSelectedUnitPropertyName,
aAggregationLevel : aAggregationLevel,
oMultiUnitRepresentative : oMultiUnitRepresentative
};
};
/**
* @private
*/
AnalyticalBinding.prototype._prepareGroupMembersAutoExpansionRequestIds = function(sGroupId, iNumberOfExpandedLevels) {
// intention of this function is to encapsulate the knowledge about steps to be taken
// for creating request IDs for all relevant requests
var iMinRequiredLevel = this._getGroupIdLevel(sGroupId) + 1;
var iAutoExpandGroupsToLevel = iMinRequiredLevel + iNumberOfExpandedLevels;
var aRequestId = [];
for (var iLevel = iMinRequiredLevel; iLevel <= iAutoExpandGroupsToLevel; iLevel++) {
aRequestId.push(this._getRequestId(AnalyticalBinding._requestType.levelMembersQuery, { groupId: sGroupId, level: iLevel }));
}
return aRequestId;
};
/**
* @private
*/
AnalyticalBinding.prototype._getQueryODataRequestOptions = function(oAnalyticalQueryRequest, mParameters) {
mParameters = mParameters || {};
try {
oAnalyticalQueryRequest.getFilterExpression().checkValidity(); // fails if false
} catch (e) {
jQuery.sap.log.fatal("filter expression is not valid", e.toString());
return undefined;
}
var sSelect = oAnalyticalQueryRequest.getURIQueryOptionValue("$select");
var sFilter = oAnalyticalQueryRequest.getURIQueryOptionValue("$filter");
var sOrderBy = oAnalyticalQueryRequest.getURIQueryOptionValue("$orderby");
var sSkip = oAnalyticalQueryRequest.getURIQueryOptionValue("$skip");
var sTop = oAnalyticalQueryRequest.getURIQueryOptionValue("$top");
var sInlineCount = oAnalyticalQueryRequest.getURIQueryOptionValue("$inlinecount");
if (this.mParameters && this.mParameters["filter"]) {
sFilter += "and (" + this.mParameters["filter"] + ")";
}
// construct OData request option parameters
var aParam = [];
if (sSelect !== null) {
aParam.push("$select=" + sSelect);
}
if (sFilter !== null) {
aParam.push("$filter=" + sFilter);
}
if (sOrderBy !== null) {
aParam.push("$orderby=" + sOrderBy);
}
if (sSkip !== null) {
aParam.push("$skip=" + sSkip);
}
if (sTop !== null) {
aParam.push("$top=" + sTop);
}
if (sInlineCount !== null) {
aParam.push("$inlinecount=" + sInlineCount);
}
//encode if necessary
if (mParameters.encode === true) {
for (var i = 0; i < aParam.length; i++) {
aParam[i] = aParam[i].replace(/\ /g, "%20");
}
}
return aParam;
};
/**
* @private
*/
AnalyticalBinding.prototype._executeBatchRequest = function(aRequestDetails) {
var iCurrentAnalyticalInfoVersion = this.iAnalyticalInfoVersionNumber;
var that = this;
var aBatchQueryRequest = [], aExecutedRequestDetails = [];
function triggerDataReceived() {
that.fireDataReceived({__simulateAsyncAnalyticalBinding: true});
}
// Batch Response Handling for ODataModel V2
var oResponseCollector = new BatchResponseCollector();
//Sucess handler called by the ODataModel for each batch sub-request
function fnSingleBatchSucess(oData, oResponse) {
oResponseCollector.success(oResponse);
}
//same as with success
function fnSingleBatchError(oData, oResponse) {
oResponseCollector.error(oResponse || oData);
}
//create sub-requests for all defined requestDetails
for (var i = -1, oRequestDetails; (oRequestDetails = aRequestDetails[++i]) !== undefined;) {
var oAnalyticalQueryRequest = oRequestDetails.oAnalyticalQueryRequest, sGroupId = oRequestDetails.sGroupId;
if (oAnalyticalQueryRequest.getURIQueryOptionValue("$select") == null) {
// no dimensions and no measures requested, so create an artificial empty root context (synonym for the regular "/")
this.fireDataRequested({__simulateAsyncAnalyticalBinding: true}); // simulate the async behavior
// perform all steps of fct fnSuccess (w/o calling it, b/c its argument is some data object and not a context
sGroupId = null;
this.mServiceLength[sGroupId] = this.mLength[sGroupId] = 1;
this.mServiceFinalLength[sGroupId] = true;
this._setServiceKey(this._getKeyIndexMapping(sGroupId, 0), AnalyticalBinding._artificialRootContextGroupId);
this.bNeedsUpdate = true;
// simulate the async behavior, dataRequested and dataReceived have to be fired in pairs
setTimeout(triggerDataReceived);
this.bArtificalRootContext = true;
// return immediately - no need to load data...
continue;
}
var sPath = oAnalyticalQueryRequest.getURIToQueryResultEntries();
//ensure absolute path if no context is set
if (!this.oContext && sPath[0] !== "/") {
sPath = "/" + sPath;
}
/*
* This might be needed, as soon as the AnalyticalBinding can handle relative binding
* @see odata4analytics -> getRequestURi... and _getResourcePath -> enforces always an absolute path
* else if (this.oContext && sPath[0] === "/") {
sPath = sPath.substring(1);
}*/
if (!this._isRequestPending(oRequestDetails.sRequestId)) {
/* side note: the check for a pending request is repeated at this point (first check occurs in _getContextsForParentGroupId),
because the logic executed for a call to the binding API may yield to identical OData requests in a single batch.
Since _processRequestQueue, and hence also _executeBatchRequest are executed asynchronously, this method is the first place
where the set of all operations included in the batch request becomes known and this condition can be checked. */
this._registerNewRequest(oRequestDetails.sRequestId);
if (this.iModelVersion === AnalyticalVersionInfo.V1) {
//V1 - use createBatchOperation
aBatchQueryRequest.push(this.oModel.createBatchOperation(sPath.replace(/\ /g, "%20"), "GET"));
}else if (this.iModelVersion === AnalyticalVersionInfo.V2) {
var aUrlParameters = this._getQueryODataRequestOptions(oAnalyticalQueryRequest, {encode: true});
if (this.sCustomParams) {
aUrlParameters.push(this.sCustomParams);
}
//V2 - use read()
var oRequestHandle = this.oModel.read(sPath.replace(/\ /g, "%20"), {
success: fnSingleBatchSucess, // relays the success to the BatchResponseCollector
error: fnSingleBatchError,
context: this.oContext,
urlParameters: aUrlParameters
});
aBatchQueryRequest.push(oRequestHandle);
}
aExecutedRequestDetails.push(oRequestDetails);
}
}
//var iRequestHandleId = this._getIdForNewRequestHandle();
if (aBatchQueryRequest.length > 0) {
jQuery.sap.log.debug("AnalyticalBinding: executing batch request with " + aExecutedRequestDetails.length + " operations");
// this._trace_message("ReqExec", "submitting batch with " + aExecutedRequestDetails.length + " operations");
var oBatchRequestHandle;
var iRequestHandleId = this._getIdForNewRequestHandle();
// fire events to indicate sending of a new request
this.fireDataRequested();
if (this.iModelVersion === AnalyticalVersionInfo.V1) {
this.oModel.addBatchReadOperations(aBatchQueryRequest);
oBatchRequestHandle = this.oModel.submitBatch(fnSuccess, fnError, true, true);
this.oModel.fireRequestSent({url : this.oModel.sServiceUrl + "/$batch", type : "POST", async : true,
info: "",
infoObject : {}
});
} else {
// fake a uniform request handle, so the original code works with the v2 ODataModel
// the v2 model does not return an overall request handle for the batch request
oBatchRequestHandle = {
abort: function() {
//relay the abort call to all sub-requests created by v2.ODataModel.read()
for (var iRequestIndex = 0; iRequestIndex < aBatchQueryRequest.length; iRequestIndex++) {
aBatchQueryRequest[iRequestIndex].abort();
}
}
};
// The response collector keeps track of all returned requests and
// calls the original success/error handlers after all batch responses have returned
oResponseCollector.setup({
executedRequests: aExecutedRequestDetails,
binding: this,
success: fnSuccess,
error: fnError
});
}
this._registerNewRequestHandle(iRequestHandleId, oBatchRequestHandle);
}
function fnSuccess(oData, response) {
that._deregisterHandleOfCompletedRequest(iRequestHandleId);
if (aExecutedRequestDetails.length != oData.__batchResponses.length) {
jQuery.sap.log.fatal("assertion failed: received " + oData.__batchResponses.length
+ " responses for " + aExecutedRequestDetails.length + " read operations in the batch request");
}
if (iCurrentAnalyticalInfoVersion != that.iAnalyticalInfoVersionNumber) {
// discard responses for outdated analytical infos
for (var j = -1, sRequestId; (sRequestId = aExecutedRequestDetails[++j].sRequestId) !== undefined;) {
that._deregisterCompletedRequest(sRequestId);
that._cleanupGroupingForCompletedRequest(sRequestId);
}
return;
}
for (var k = 0; k < oData.__batchResponses.length; k++) {
if (oData.__batchResponses[k].data != undefined) {
switch (aExecutedRequestDetails[k].iRequestType) {
case AnalyticalBinding._requestType.groupMembersQuery:
that._processGroupMembersQueryResponse(aExecutedRequestDetails[k], oData.__batchResponses[k].data);
break;
case AnalyticalBinding._requestType.totalSizeQuery:
that._processTotalSizeQueryResponse(aExecutedRequestDetails[k], oData.__batchResponses[k].data);
break;
case AnalyticalBinding._requestType.levelMembersQuery:
that._processLevelMembersQueryResponse(aExecutedRequestDetails[k], oData.__batchResponses[k].data);
break;
case AnalyticalBinding._requestType.reloadMeasuresQuery:
that._processReloadMeasurePropertiesQueryResponse(aExecutedRequestDetails[k], oData.__batchResponses[k].data);
break;
default:
jQuery.sap.log.fatal("invalid request type " + aExecutedRequestDetails[k].iRequestType);
continue;
}
}
that._deregisterCompletedRequest(aExecutedRequestDetails[k].sRequestId);
that._cleanupGroupingForCompletedRequest(aExecutedRequestDetails[k].sRequestId);
}
// determine the logical success status: true iff all operations succeeded
var bOverallSuccess = true;
var aBatchErrors;
// raise event here since there is no separate fnCompleted handler for batch requests
that.fireDataReceived({data: oData});
//check for possible V1 errors
var oV1Errors = {};
if (that.iModelVersion === AnalyticalVersionInfo.V1) {
// retrieve the errors from the model and reset the success flag
aBatchErrors = that.oModel._getBatchErrors(oData);
if (aBatchErrors.length > 0) {
bOverallSuccess = false;
oV1Errors = that.oModel._handleError(aBatchErrors[0]);
}
// fire event to indicate completion of request
that.oModel.fireRequestCompleted({url : response.requestUri, type : "POST", async : true,
info: "",
infoObject : {},
success: bOverallSuccess,
errorobject: bOverallSuccess ? {} : oV1Errors
});
}
// notify all bindings of the model that the data has been changed!
// e.g. controls in the rows need to be updated as well
// fire only the change event is not sufficient for other bindings
if (bOverallSuccess) {
that.oModel.checkUpdate();
}
}
function fnError (oError) {
// in case the error is triggered by an aborted request, don't cleanup the handle queue, as it is already cleaned-up by the abort call.
if (oError && oError.statusText != "abort") {
that._deregisterHandleOfCompletedRequest(iRequestHandleId);
for (var j = -1, oExecutedRequestDetails; (oExecutedRequestDetails = aExecutedRequestDetails[++j]) !== undefined;) {
that._deregisterCompletedRequest(oExecutedRequestDetails.sRequestId);
that._cleanupGroupingForCompletedRequest(oExecutedRequestDetails.sRequestId);
}
}
if (iCurrentAnalyticalInfoVersion != that.iAnalyticalInfoVersionNumber) {
// discard responses for outdated analytical infos
return;
}
var oV1Error = oError;
if (that.iModelVersion === AnalyticalVersionInfo.V1) {
oV1Error = that.oModel._handleError(oError);
}
// fire event to indicate completion of request
that.oModel.fireRequestCompleted({url : "", type : "POST", async : true,
info: "",
infoObject : {},
success: false,
errorobject: oV1Error});
// fire event to indicate request failure
that.oModel.fireRequestFailed(oV1Error);
that.fireDataReceived();
}
};
/**
* @private
*/
AnalyticalBinding.prototype._executeQueryRequest = function(oRequestDetails) {
if (oRequestDetails.iRequestType == AnalyticalBinding._requestType.groupMembersAutoExpansionQuery) {
// handle auto-expanding requests that are actually a bundle of multiple requests, one per level
for (var i = -1, oAnalyticalQueryRequest2; (oAnalyticalQueryRequest2 = oRequestDetails.aGroupMembersAutoExpansionRequestDetails[++i]) !== undefined; ) {
this._executeQueryRequest(oAnalyticalQueryRequest2);
}
return;
}
var iCurrentAnalyticalInfoVersion = this.iAnalyticalInfoVersionNumber;
var oAnalyticalQueryRequest = oRequestDetails.oAnalyticalQueryRequest, sGroupId = oRequestDetails.sGroupId;
// determine relevant request query options
var sPath = oAnalyticalQueryRequest.getURIToQueryResultEntitySet();
var aParam = this._getQueryODataRequestOptions(oAnalyticalQueryRequest);
if (!aParam) {
// parameters could not be determined correctly
return;
}
var that = this;
if (oAnalyticalQueryRequest.getURIQueryOptionValue("$select") == null) {
// no dimensions and no measures requested, so create an artificial empty root context (synonym for the regular "/")
this.fireDataRequested({__simulateAsyncAnalyticalBinding: true}); // simulate the async behavior
// perform all steps of fct fnSuccess (w/o calling it, b/c its argument is some data object and not a context
sGroupId = null;
this.mServiceLength[sGroupId] = this.mLength[sGroupId] = 1;
this.mServiceFinalLength[sGroupId] = true;
this._setServiceKey(this._getKeyIndexMapping(sGroupId, 0), AnalyticalBinding._artificialRootContextGroupId);
this.bNeedsUpdate = true;
// simulate the async behavior for the root context in case of having no sums (TODO: reconsider!)
setTimeout(function() {
if (that._cleanupGroupingForCompletedRequest(oRequestDetails.sRequestId)) {
that.fireDataReceived({__simulateAsyncAnalyticalBinding: true});
}
});
this.bArtificalRootContext = true;
// return immediately - no need to load data...
return;
}
this._registerNewRequest(oRequestDetails.sRequestId);
// execute the request and use the metadata if available
this.fireDataRequested();
for (var j = 0; j < aParam.length; j++) {
aParam[j] = aParam[j].replace(/\ /g, "%20");
}
jQuery.sap.log.debug("AnalyticalBinding: executing query request");
var iRequestHandleId = this._getIdForNewRequestHandle();
if (this.iModelVersion === AnalyticalVersionInfo.V1) {
//trigger data loading, the request handle is registered during the fnHandleUpdate callback, used by the V1 model
this.oModel._loadData(sPath, aParam, fnSuccess, fnError, false, fnUpdateHandle, fnCompleted);
} else {
if (this.sCustomParams) {
aParam.push(this.sCustomParams);
}
var oRequestHandle = this.oModel.read(sPath, {
success: fnSuccess,
error: fnError,
context: this.oContext,
urlParameters: aParam
});
//the handle has to be registered here, because the V2 model does not support an fnHandleUpdate callback anymore
that._registerNewRequestHandle(iRequestHandleId, oRequestHandle);
}
function fnSuccess(oData) {
that._deregisterHandleOfCompletedRequest(iRequestHandleId);
if (iCurrentAnalyticalInfoVersion != that.iAnalyticalInfoVersionNumber) {
// discard responses for outdated analytical infos
that._deregisterCompletedRequest(oRequestDetails.sRequestId);
return;
}
switch (oRequestDetails.iRequestType) {
case AnalyticalBinding._requestType.groupMembersQuery:
that._processGroupMembersQueryResponse(oRequestDetails, oData);
break;
case AnalyticalBinding._requestType.totalSizeQuery:
that._processTotalSizeQueryResponse(oRequestDetails, oData);
break;
case AnalyticalBinding._requestType.levelMembersQuery:
that._processLevelMembersQueryResponse(oRequestDetails, oData);
break;
case AnalyticalBinding._requestType.reloadMeasuresQuery:
that._processReloadMeasurePropertiesQueryResponse(oRequestDetails, oData);
break;
default:
jQuery.sap.log.fatal("invalid request type " + oRequestDetails.iRequestType);
break;
}
that._deregisterCompletedRequest(oRequestDetails.sRequestId);
// with ODataModel V2, the completed function is not called by the model anymore
// the correct moment to clean up is after the success handler
// the error handler takes care of this itself
if (that.iModelVersion === AnalyticalVersionInfo.V2) {
fnCompleted(oData);
}
}
function fnCompleted(oData) {
if (iCurrentAnalyticalInfoVersion != that.iAnalyticalInfoVersionNumber) {
// discard responses for outdated analytical infos
return;
}
if (that._cleanupGroupingForCompletedRequest(oRequestDetails.sRequestId)) {
that.fireDataReceived({data: oData});
}
}
function fnError(oError) {
// in case the error is triggered by an aborted request, don't cleanup the request-handle queue, as it is already cleaned-up by the abort call
if (oError && oError.statusText == "abort") {
that.fireDataReceived();
return;
}
that._deregisterHandleOfCompletedRequest(iRequestHandleId);
that._deregisterCompletedRequest(oRequestDetails.sRequestId);
that._cleanupGroupingForCompletedRequest(oRequestDetails.sRequestId);
if (iCurrentAnalyticalInfoVersion != that.iAnalyticalInfoVersionNumber) {
// discard responses for outdated analytical infos
return;
}
that.fireDataReceived();
}
function fnUpdateHandle(oRequestHandle) {
that._registerNewRequestHandle(iRequestHandleId, oRequestHandle);
}
};
/**
* @private
*/
AnalyticalBinding.prototype._abortAllPendingRequests = function() {
this._abortAllPendingRequestsByHandle();
this._clearAllPendingRequests();
};
/**
* @private
*/
AnalyticalBinding.prototype._processGroupMembersQueryResponse = function(oRequestDetails, oData) {
var sGroupId = oRequestDetails.sGroupId,
aSelectedUnitPropertyName = oRequestDetails.aSelectedUnitPropertyName,
aAggregationLevel = oRequestDetails.aAggregationLevel,
iStartIndex = oRequestDetails.oKeyIndexMapping.iIndex,
iServiceStartIndex = oRequestDetails.oKeyIndexMapping.iServiceKeyIndex,
iLength = oRequestDetails.iLength,
oKeyIndexMapping = oRequestDetails.oKeyIndexMapping,
iGroupMembersLevel = sGroupId == null ? 0 : this._getGroupIdLevel(sGroupId) + 1;
var bUnitCheckRequired = (aSelectedUnitPropertyName.length > 0);
var sPreviousEntryDimensionKeyString, sDimensionKeyString;
var iFirstMatchingEntryIndex;
var iDiscardedEntriesCount = 0;
var bLastServiceKeyWasNew;
var oReloadMeasuresRequestDetails, aReloadMeasuresRequestDetails = [];
// this._trace_enter("ReqExec", "_processGroupMembersQueryResponse", "groupId=" + oRequestDetails.sGroupId, { startIndex: iStartIndex, serviceStartIndex: iServiceStartIndex, length: iLength, resultCount: oData.__count, resultLength: oData.results.length }, ["startIndex","serviceStartIndex","length","resultCount","resultLength"]); // DISABLED FOR PRODUCTION
// entry at start position may be a multi-unit entry w.r.t. entry at position before
// prepare merging with this preceding entry
var iODataResultsLength = oData.results.length;
var aPreviousEntryServiceKey = this._getServiceKeys(sGroupId, oKeyIndexMapping.iIndex - 1);
sPreviousEntryDimensionKeyString = undefined;
if (aPreviousEntryServiceKey && aPreviousEntryServiceKey.length > 0) { // copy previous service keys to results for homogeneous processing below
for (var i = 0, len = aPreviousEntryServiceKey.length; i < len; i++) {
oData.results[i - len] = this.oModel.getObject("/" + aPreviousEntryServiceKey[i]);
}
var oEntry2 = oData.results[-aPreviousEntryServiceKey.length];
sPreviousEntryDimensionKeyString = "";
for (var j = 0; j < aAggregationLevel.length; j++) {
sPreviousEntryDimensionKeyString += oEntry2[aAggregationLevel[j]] + "|";
}
}
// special case: previous entry gets merged with the first loaded entry/ies
// if there was a single preceding entity that was not yet a multi-unit entry, count it!
// (on the opposite, if there were multiple, hence multi-unit entries, they were counted already when they got loaded)
// Therefore, in order to count it, the bLastServiceKeyWasNew flag is set accordingly
bLastServiceKeyWasNew = aPreviousEntryServiceKey && aPreviousEntryServiceKey.length == 1;
// process loaded data, collect contexts and handle multi-unit occurrences; oKeyIndexMapping points to the current insert positions for key indexes and service keys
for (var h = 0; h < iODataResultsLength; h++) {
var oEntry = oData.results[h];
if (bUnitCheckRequired) {
// perform check to detect multiple returned entries for a single group level instance; duplicates are detected by having the same dimension keys
sDimensionKeyString = "";
for (var g = 0; g < aAggregationLevel.length; g++) {
sDimensionKeyString += oEntry[aAggregationLevel[g]] + "|";
}
if (sPreviousEntryDimensionKeyString == sDimensionKeyString) {
if (iFirstMatchingEntryIndex === undefined) {
if (h == 0) { // adjust indexes such that the entry at position before is covered
iFirstMatchingEntryIndex = -aPreviousEntryServiceKey.length;
oKeyIndexMapping.iServiceKeyIndex -= aPreviousEntryServiceKey.length - 1; // must point to the second entry with the same dimension key
// // this._trace_debug_if(aPreviousEntryServiceKey.length > 1,"one or more loaded entries will get merged with preceding multi-unit entry");
} else {
iFirstMatchingEntryIndex = h - 1;
}
}
var iDeviatingUnitPropertyNameIndex = -1, oPreviousEntry = oData.results[h - 1];
for (var k = 0; k < aSelectedUnitPropertyName.length; k++) {
if (oPreviousEntry[aSelectedUnitPropertyName[k]] != oEntry[aSelectedUnitPropertyName[k]]) {
iDeviatingUnitPropertyNameIndex = k; // aggregating dimensions are all the same, entries only differ in currency
break;
}
}
if (iDeviatingUnitPropertyNameIndex == -1) {
// this._trace_debug_if(true, "assertion failed: no deviating units found for result entries " + (h - 1) + " and " + h);
jQuery.sap.log.fatal("assertion failed: no deviating units found for result entries " + (h - 1) + " and " + h);
}
}
if ((sPreviousEntryDimensionKeyString != sDimensionKeyString || h == iODataResultsLength - 1)
&& iFirstMatchingEntryIndex !== undefined) { // after sequence of identical entries or if processing the last result entry (the set iFirstMatchingEntryIndex indicates the multi-unit case)
/* multi-unit verification: remember if a multi-unit occurrence is found */
/*start code block*
this.bFoundMU = true;
*end code block*/
// collect all related result entries for this multi-unit entity and set the keys
var aMultiUnitEntry = [];
for (var l = iFirstMatchingEntryIndex; l < h; l++) {
aMultiUnitEntry.push(oData.results[l]);
}
if (sPreviousEntryDimensionKeyString == sDimensionKeyString) {
aMultiUnitEntry.push(oData.results[h]);
}
// determine all deviating unit properties
var aDeviatingUnitPropertyName = [];
for (var m = 0; m < aSelectedUnitPropertyName.length; m++) {
var sUnitPropertyName = aSelectedUnitPropertyName[m];
for (var o = 1; o < aMultiUnitEntry.length; o++) {
if (aMultiUnitEntry[o - 1][sUnitPropertyName] != aMultiUnitEntry[o][sUnitPropertyName]) {
aDeviatingUnitPropertyName.push(sUnitPropertyName);
break;
}
}
}
// create a multi-unit repr. (includes a corresponding multi-unit entity)
var oMultiUnitRepresentative = this._createMultiUnitRepresentativeEntry(sGroupId, oData.results[iFirstMatchingEntryIndex], aSelectedUnitPropertyName, aDeviatingUnitPropertyName, oRequestDetails.bIsFlatListRequest);
if (oMultiUnitRepresentative.aReloadMeasurePropertyName.length > 0) {
oReloadMeasuresRequestDetails = this._prepareReloadMeasurePropertiesQueryRequest(AnalyticalBinding._requestType.reloadMeasuresQuery, oRequestDetails, oMultiUnitRepresentative);
// only schedule reloadMeasure requests if there is something to select -> it might be that some measure could be reloaded, but the column
// might not be totaled (yet might be visible/inResult)
// BCP: 1570786546
if (oReloadMeasuresRequestDetails.oAnalyticalQueryRequest && oReloadMeasuresRequestDetails.oAnalyticalQueryRequest.getURIQueryOptionValue("$select") != null) {
aReloadMeasuresRequestDetails.push(oReloadMeasuresRequestDetails);
}
}
var iNewServiceKeyCount = this._setAdjacentMultiUnitKeys(oKeyIndexMapping, oMultiUnitRepresentative, aMultiUnitEntry);
// update number of discarded entities
var iMultiUnitEntryDiscardedEntriesCount;
if (oMultiUnitRepresentative.bIsNewEntry) {
iMultiUnitEntryDiscardedEntriesCount = aMultiUnitEntry.length - 1;
} else {
iMultiUnitEntryDiscardedEntriesCount = iNewServiceKeyCount;
}
if (bLastServiceKeyWasNew) {
bLastServiceKeyWasNew = false;
}
if (iMultiUnitEntryDiscardedEntriesCount < 0) {
// this._trace_debug_if(iDiscardedEntriesCount < 0, "assertion failed: iDiscardedEntriesCount must be non-negative");
jQuery.sap.log.fatal("assertion failed: iDiscardedEntriesCount must be non-negative");
}
iDiscardedEntriesCount += iMultiUnitEntryDiscardedEntriesCount;
/* multi-unit verification: remember multi-unit key */
/*start code block*
this.bNewMUKey = oMultiUnitRepresentative.bIsNewEntry;
*end code block*/
// adjust mEntityKey for detected and handled multi-unit situation
var sMultiUnitKey = this.oModel._getKey(oMultiUnitRepresentative.oEntry);
var oMultiUnitContext = this.oModel.getContext('/' + sMultiUnitKey);
this._getGroupIdFromContext(oMultiUnitContext, iGroupMembersLevel);
this.mEntityKey[sEntryGroupId] = sMultiUnitKey;
// reset multi-unit indicator
iFirstMatchingEntryIndex = undefined;
// add current entry if it has different key combination
if (sPreviousEntryDimensionKeyString != sDimensionKeyString) {
bLastServiceKeyWasNew = this._setServiceKey(oKeyIndexMapping, this.oModel._getKey(oEntry));
}
} else if (sPreviousEntryDimensionKeyString != sDimensionKeyString) {
bLastServiceKeyWasNew = this._setServiceKey(oKeyIndexMapping, this.oModel._getKey(oEntry));
}
/* multi-unit verification: remember if differend dimensions are involved - needed for correct index calculation */
/*start code block*
this.bDiffDims = (sPreviousEntryDimensionKeyString != sDimensionKeyString);
*end code block*/
sPreviousEntryDimensionKeyString = sDimensionKeyString;
} else {
this._setServiceKey(oKeyIndexMapping, this.oModel._getKey(oEntry));
}
// remember mapping between entry key and group Id
if (!oRequestDetails.bIsLeafGroupsRequest) {
var sLastEntryKey = this._getKey(sGroupId, oKeyIndexMapping.iIndex - 1),
sEntryGroupId = this._getGroupIdFromContext(this.oModel.getContext('/' + sLastEntryKey), iGroupMembersLevel);
/* during development only
if (this.mEntityKey[sEntryGroupId]) {
if (this.mEntityKey[sEntryGroupId] != sLastEntryKey)
// Such errors will occur in case repeated calls for same groups with providers returned unstable entity keys
// E.g., HANA/XS does not provide stable keys. As s
// As soon as repetitive calls are avoided, such errors will vanish as well
jQuery.sap.log.debug("unstable keys detected: group ID " + sEntryGroupId + " does not have a unique entity key");
}
*/
this.mEntityKey[sEntryGroupId] = sLastEntryKey;
}
/* multi-unit verification: collect the cumulated number of discarded entries in a separate member array for analysis --- see below */
/*start code block*
if (this.aDiscCount === undefined) {
this.aDiscCount = [];
this.aCheckDiscCount = [];
}
if (h == 0) {
this.aDiscCount = [];
this.aCheckDiscCount = [];
}
if (this.bFoundMU) {
if (this.bDiffDims) {
this.aDiscCount[oKeyIndexMapping.iIndex - 2] = iDiscardedEntriesCount;
this.aDiscCount[oKeyIndexMapping.iIndex - 1] = iDiscardedEntriesCount;
this.aCheckDiscCount[oKeyIndexMapping.iIndex - 2] = this.bNewMUKey;
} else {
this.aDiscCount[oKeyIndexMapping.iIndex - 1] = iDiscardedEntriesCount;
this.aCheckDiscCount[oKeyIndexMapping.iIndex - 1] = this.bNewMUKey;
}
this.bFoundMU = false;
this.bDiffDims = false;
this.bNewMUKey = false;
} else {
this.aDiscCount[oKeyIndexMapping.iIndex - 1] = iDiscardedEntriesCount;
}
*end code block*/
}
/* multi-unit verification: perform check between created service indexes and count of discarded service entities */
/*start code block*
* eslint-disable no-debugger, no-unused-vars, no-empty *
for (var chkIndex = iStartIndex, iMaxIndex = oKeyIndexMapping.iIndex - 1; chkIndex <= iMaxIndex; chkIndex++) {
if (! this.aCheckDiscCount[chkIndex]) {
continue;
}
var iKeyIndex = this.mKeyIndex[sGroupId][chkIndex];
var iDiscCountAtChkIndex = this.aDiscCount[chkIndex];
var iDiscCountAtBefore = this.aDiscCount[chkIndex - 1] !== undefined ? this.aDiscCount[chkIndex - 1] : 0;
if (iKeyIndex >= 0) {
// this._trace_debug_if(iDiscCountAtChkIndex - iDiscCountAtBefore != 0, "assertion failed: disc count == 0 at key index = " + (chkIndex));
} else {
if (iKeyIndex == "ZERO") {
iKeyIndex = 0;
}
var iNextKeyIndex = this.mKeyIndex[sGroupId][chkIndex + 1];
if (iNextKeyIndex !== undefined) {
var iDistanceToNextKeyIndex = Math.abs(iNextKeyIndex) - Math.abs(iKeyIndex);
// this._trace_debug_if(iDistanceToNextKeyIndex - 1 != iDiscCountAtChkIndex - iDiscCountAtBefore, "assertion failed: disc count exp = " + (iDistanceToNextKeyIndex - 1) + ", but got " + (iDiscCountAtChkIndex - iDiscCountAtBefore) + " at key index = " + (chkIndex));
} else {
var cnt = 0, ii = Math.abs(iKeyIndex);
while (this.mServiceKey[sGroupId][ii++] !== undefined) {
cnt++;
}
// this._trace_debug_if(cnt - 1 != iDiscCountAtChkIndex - iDiscCountAtBefore, "assertion failed: disc count exp = " + (cnt - 1) + ", but got " + (iDiscCountAtChkIndex - iDiscCountAtBefore) + " at key index = " + (chkIndex));
}
}
}
* eslint-enable no-debugger *
*end code block*/
// if any new requests have been created for reloading single-unit measures, execute and group them to get a single update event for them
var aReloadMeasureRequestId = [];
if (this.bReloadSingleUnitMeasures && aReloadMeasuresRequestDetails.length > 0) {
if (this.bUseBatchRequests) {
this.aBatchRequestQueue.push([AnalyticalBinding._requestType.reloadMeasuresQuery, aReloadMeasuresRequestDetails]);
Promise.resolve().then(AnalyticalBinding.prototype._processRequestQueue.bind(this));
} else {
for (var q = 0; q < aReloadMeasuresRequestDetails.length; q++){
var oReloadMeasuresRequestDetails2 = aReloadMeasuresRequestDetails[q];
this._executeQueryRequest(oReloadMeasuresRequestDetails2);
}
}
for (var p = 0; p < aReloadMeasuresRequestDetails.length; p++){
var oReloadMeasuresRequestDetails3 = aReloadMeasuresRequestDetails[p];
aReloadMeasureRequestId.push(oReloadMeasuresRequestDetails3.sRequestId);
}
this._considerRequestGrouping(aReloadMeasureRequestId);
}
// cleanup results entry array from added previous entry
if (aPreviousEntryServiceKey && aPreviousEntryServiceKey.length > 0) {
for (var r = 0, len2 = aPreviousEntryServiceKey.length; r < len2; r++) {
delete oData.results[r - len2];
}
}
// if unit check is required, then merge loaded data with already available data occuring directly after the new data
if (bUnitCheckRequired) {
iDiscardedEntriesCount += this._mergeLoadedKeyIndexWithSubsequentIndexes(oKeyIndexMapping, aAggregationLevel, aSelectedUnitPropertyName, oRequestDetails.bIsFlatListRequest);
}
// this._trace_message("ReqExec", "", { servicelengthBefore: this.mServiceLength[sGroupId], lengthBefore: this.mLength[sGroupId], discardedEntriesCount: iDiscardedEntriesCount}, ["servicelengthBefore", "lengthBefore", "discardedEntriesCount"]);
// update group length
if (!oRequestDetails.bAvoidLengthUpdate) {
var bNewLengthSet = false;
if (oData.__count) {
this.mServiceLength[sGroupId] = parseInt(oData.__count, 10);
this.mLength[sGroupId] = this.mServiceLength[sGroupId] - iDiscardedEntriesCount;
this.mFinalLength[sGroupId] = true;
if (oRequestDetails.bIsFlatListRequest) {
this.iTotalSize = oData.__count;
}
bNewLengthSet = true;
}
// if we got data and the results + startindex is larger than the length we just apply this value to the length
if (this.mServiceLength[sGroupId] < iServiceStartIndex + iODataResultsLength) {
this.mServiceLength[sGroupId] = iServiceStartIndex + iODataResultsLength;
this.mLength[sGroupId] = iStartIndex + iODataResultsLength - iDiscardedEntriesCount;
this.mFinalLength[sGroupId] = false;
}
// if less entries are returned than have been requested set length accordingly
if (iODataResultsLength < iLength || iLength === undefined) {
this.mServiceLength[sGroupId] = iServiceStartIndex + iODataResultsLength;
this.mLength[sGroupId] = iStartIndex + oKeyIndexMapping.iIndex - iStartIndex;
this.mFinalLength[sGroupId] = true;
bNewLengthSet = true;
}
// check if there are any results at all
if (iODataResultsLength == 0) {
this.mLength[sGroupId] = this.mServiceLength[sGroupId] = 0;
this.mFinalLength[sGroupId] = true;
bNewLengthSet = true;
}
if (!bNewLengthSet && this.mLength[sGroupId] !== undefined && iDiscardedEntriesCount > 0) {
this.mLength[sGroupId] -= iDiscardedEntriesCount;
}
}
// this._trace_message("ReqExec", "", { servicelengthAfter: this.mServiceLength[sGroupId], lengthAfter: this.mLength[sGroupId]}, ["servicelengthAfter", "lengthAfter"]);
this.bNeedsUpdate = true;
if (iDiscardedEntriesCount > 0) { // update load factor if entries have been discarded
// If all loaded entries have been discarded, we have the following situation:
// the last multi-unit entry was previously loaded with another data page, and thus it can happen, that all response entries
// will have to be discarded, since there already is a virtual multi-unit entry created.
// In this case we keep the last known load-factor stable.
if (oData.results.length - iDiscardedEntriesCount > 0) {
this.aMultiUnitLoadFactor[aAggregationLevel.length] = oData.results.length / (oData.results.length - iDiscardedEntriesCount);
}
if (this.aMultiUnitLoadFactor[aAggregationLevel.length] < 1.5) { // avoid too small factors
this.aMultiUnitLoadFactor[aAggregationLevel.length] = 2;
}
}
// #TH
jQuery.sap.log.info("MultiUnit Situation in Group (" + sGroupId + "), discarded: " + iDiscardedEntriesCount + ", load-factor is now: " + this.aMultiUnitLoadFactor[aAggregationLevel.length]);
// this._trace_debug_if(this.iMultiUnitLoadFactor < 1, "load factor cannot be lower than 1!");
/* multi-unit verification: check length of loaded data with colected cumulated discarded counts */
/*start code block*
this._checkLength(sGroupId, iStartIndex);
*end code block*/
// this._trace_leave("ReqExec", "_processGroupMembersQueryResponse", "", { lastLoadedIndex: oKeyIndexMapping.iIndex - 1, lastLoadedServiceIndex: oKeyIndexMapping.iServiceKeyIndex - 1, discardedEntriesCount: iDiscardedEntriesCount, multiUnitLoadFactor: this.aMultiUnitLoadFactor[aAggregationLevel.length] }, ["lastLoadedIndex","lastLoadedServiceIndex","discardedEntriesCount","multiUnitLoadFactor"]); // DISABLED FOR PRODUCTION
};
/* multi-unit verification: check length of loaded data with colected cumulated discarded counts */
/*start code block*
* eslint-disable no-debugger *
AnalyticalBinding.prototype._checkLength = function(sGroupId, iStartIndex) {
var aKeyIndex = this.mKeyIndex[sGroupId];
var count = this.mServiceLength[sGroupId];
for (var i = iStartIndex, iMaxIndex = this.aDiscCount.length; i < iMaxIndex; i++) {
if (! this.aCheckDiscCount[i]) {
continue;
}
if (aKeyIndex[i] < 0 || aKeyIndex[i] == "ZERO") {
var aServiceKey = this._getServiceKeys(sGroupId, i);
// this._trace_debug_if(!aServiceKey, "failed: no service keys found!?");
var iDiscCountAtChkIndex = this.aDiscCount[i];
var iDiscCountAtBefore = this.aDiscCount[i - 1] !== undefined ? this.aDiscCount[i - 1] : 0;
// this._trace_debug_if(iDiscCountAtChkIndex - iDiscCountAtBefore != aServiceKey.length - 1, "mismatch: entry at pos " + (i) + " has " + (aServiceKey.length - 1) + " service keys, but discCount is " + (iDiscCountAtChkIndex - iDiscCountAtBefore));
count -= aServiceKey.length - 1; // useless..., because we do not check from 0, but from startIndex
}
}
};
* eslint-enable no-debugger *
*end code block*/
/**
* @private
*/
AnalyticalBinding.prototype._processTotalSizeQueryResponse = function(oRequestDetails, oData) {
if (oData.__count == undefined) {
jQuery.sap.log.fatal("missing entity count in query result");
return;
}
this.iTotalSize = oData.__count;
};
/**
* @private
*/
AnalyticalBinding.prototype._processLevelMembersQueryResponse = function(oRequestDetails, oData) {
// local helper function to transform a block of entries in the level response to a response for a particular parent group
var that = this;
var sPreviousParentGroupId, aParentGroupODataResult;
var processSingleGroupFromLevelSubset = function (bProcessFirstLoadedGroup, bIncompleteGroupMembersSet) {
// transform the subset for processing as group members query response
var oGroupMembersRequestDetails = {
iRequestType : AnalyticalBinding._requestType.groupMembersQuery,
sRequestId : that._getRequestId(AnalyticalBinding._requestType.groupMembersQuery, {groupId: sPreviousParentGroupId}),
oAnalyticalQueryRequest : oRequestDetails.oAnalyticalQueryRequest,
sGroupId : sPreviousParentGroupId,
aSelectedUnitPropertyName : oRequestDetails.aSelectedUnitPropertyName,
aAggregationLevel : oRequestDetails.aAggregationLevel,
bIsFlatListRequest : oRequestDetails.bIsFlatListRequest,
bIsLeafGroupsRequest : oRequestDetails.bIsLeafGroupsRequest,
iStartIndex : bProcessFirstLoadedGroup ? oRequestDetails.iStartIndex : 0,
iLength : oRequestDetails.iLength,
bAvoidLengthUpdate : oRequestDetails.bAvoidLengthUpdate
}; // note that the keyIndexMapping is still missing; added later after handling of special cases
// special handling for the first group contained in this level load if it starts a new group
if (bProcessFirstLoadedGroup
&& oRequestDetails.iStartIndex > 0
&& (oRequestDetails.sGroupId_Missing_AtLevel != oGroupMembersRequestDetails.sGroupId
|| that._getKeys(oGroupMembersRequestDetails.sGroupId) === undefined)) {
// pendant to bIncompleteGroupMembersSet: set the finalLength of the previous group
var sParentGroupId = that._getParentGroupId(oGroupMembersRequestDetails.sGroupId);
var iPositionInParentGroup = that._findKeyIndex(sParentGroupId, that.mEntityKey[oGroupMembersRequestDetails.sGroupId]);
if (iPositionInParentGroup == -1) {
jQuery.sap.log.fatal("assertion failed: failed to determine position of " + oGroupMembersRequestDetails.sGroupId + " in group " + sParentGroupId);
}
if (iPositionInParentGroup > 0 && that._getKey(sParentGroupId, iPositionInParentGroup - 1) !== undefined) {
var sPreviousGroupMemberKey = that._getKey(sParentGroupId, iPositionInParentGroup - 1);
var sPreviousGroupId = that._getGroupIdFromContext(that.oModel.getContext('/' + sPreviousGroupMemberKey),
that._getGroupIdLevel(oGroupMembersRequestDetails.sGroupId));
// only for development - if (that.mFinalLength[sPreviousGroupId]) jQuery.sap.log.fatal("assertion failed that final length of previous group id is false");
// the final length of the previous must be set to true
that.mFinalLength[sPreviousGroupId] = true;
// and iStartIndex must be reset to 0, because a new group starts
oGroupMembersRequestDetails.iStartIndex = 0;
}
}
// special handling for the last group contained in this level load
if (bIncompleteGroupMembersSet) {
// this will force the next call of _processGroupMembersQueryResponse() below to maintain the partial length
oGroupMembersRequestDetails.iLength = aParentGroupODataResult.length;
}
oGroupMembersRequestDetails.oKeyIndexMapping = that._getKeyIndexMapping(oGroupMembersRequestDetails.sGroupId, oGroupMembersRequestDetails.iStartIndex);
var oParentGroupOData = jQuery.extend(true, {}, oData);
oParentGroupOData.results = aParentGroupODataResult;
that._processGroupMembersQueryResponse(oGroupMembersRequestDetails, oParentGroupOData);
};
// function implementation starts here
if (oData.results.length == 0) {
return;
}
// Collecting contexts
sPreviousParentGroupId = this._getGroupIdFromContext( // setup for loop
this.oModel.getContext("/" + this.oModel._getKey(oData.results[0])), oRequestDetails.iLevel - 1);
aParentGroupODataResult = [];
var bProcessFirstLoadedGroup = true;
for (var i = 0; i < oData.results.length; i++) {
// partition the result into several subsets each of which has a common parent group Id
var oEntry = oData.results[i];
var oContext = this.oModel.getContext("/" + this.oModel._getKey(oData.results[i]));
var sParentGroupId = this._getGroupIdFromContext(oContext, oRequestDetails.iLevel - 1);
if (sPreviousParentGroupId == sParentGroupId) {
aParentGroupODataResult.push(oEntry);
if (i < oData.results.length - 1) {
continue;
}
}
processSingleGroupFromLevelSubset(bProcessFirstLoadedGroup,
oData.results.length == oRequestDetails.iLength && i == oData.results.length - 1);
// setup for processing next parent group
bProcessFirstLoadedGroup = false;
if (sPreviousParentGroupId != sParentGroupId) {
aParentGroupODataResult = [ oEntry ];
}
sPreviousParentGroupId = sParentGroupId;
}
// process remaining left over (can happen if results contains more than one entry and group ID switches on last entry)
if (oData.results.length > 1 && aParentGroupODataResult.length == 1) {
processSingleGroupFromLevelSubset(bProcessFirstLoadedGroup, oData.results.length == oRequestDetails.iLength);
}
};
/**
* @private
*/
AnalyticalBinding.prototype._processReloadMeasurePropertiesQueryResponse = function(oRequestDetails, oData) {
var oMultiUnitRepresentative = oRequestDetails.oMultiUnitRepresentative;
var sMultiUnitEntryKey = this.oModel.getKey(oMultiUnitRepresentative.oEntry);
// this._trace_enter("ReqExec", "_processReloadMeasurePropertiesQueryResponse", "multi-unit key=" + sMultiUnitEntryKey); // DISABLED FOR PRODUCTION
if (oData.results.length != 1) {
// this._trace_debug_if(true, "assertion failed: more than one entity for reloaded measure properties of entity with key " + sMultiUnitEntryKey);
jQuery.sap.log.fatal("assertion failed: more than one entity for reloaded measure properties of entity with key " + sMultiUnitEntryKey);
return;
}
var oReloadedEntry = oData.results[0];
var oMultiUnitEntry = this.oModel.getObject("/" + sMultiUnitEntryKey);
if (!oMultiUnitEntry) {
jQuery.sap.log.fatal("assertion failed: no entity found with key " + sMultiUnitEntryKey);
return;
}
var aMeasureName = oMultiUnitRepresentative.aReloadMeasurePropertyName;
for (var i = 0; i < aMeasureName.length; i++) {
// this._trace_debug_if(oReloadedEntry[aMeasureName[i]] === undefined || oReloadedEntry[aMeasureName[i]] == "", "no value for reloaded measure property");
oMultiUnitEntry[aMeasureName[i]] = oReloadedEntry[aMeasureName[i]];
}
// this._trace_leave("ReqExec", "_processReloadMeasurePropertiesQueryResponse", "measures=" + oMultiUnitRepresentative.aReloadMeasurePropertyName.join()); // DISABLED FOR PRODUCTION
};
/** *************************************************************** */
/**
* @private
*/
AnalyticalBinding.prototype._getLoadedContextsForGroup = function(sGroupId, iStartIndex, iLength, bFetchAll) {
var aContext = [], oContext, fKey = this._getKeys(sGroupId), sKey;
if (!fKey) {
return aContext;
}
if (!iStartIndex) {
iStartIndex = 0;
}
if (!iLength) {
iLength = this.oModel.iSizeLimit;
//if the length is known, do not use the size limit of the model, but the known length
if (this.mFinalLength[sGroupId]) { // && this.mLength[sGroupId] < iLength) {
iLength = this.mLength[sGroupId];
}
}
if (bFetchAll) {
i = iStartIndex || 0;
sKey = fKey(i);
while (sKey) {
oContext = this.oModel.getContext('/' + sKey);
aContext.push(oContext);
i++;
sKey = fKey(i);
}
return aContext;
}
// Loop through known data and check whether we already have all rows loaded
for (var i = iStartIndex; i < iStartIndex + iLength; i++) {
sKey = fKey(i);
if (!sKey) {
break;
}
oContext = this.oModel.getContext('/' + sKey);
aContext.push(oContext);
}
return aContext;
};
/**
* @private
*/
AnalyticalBinding.prototype._calculateRequiredGroupSection = function(sGroupId, iStartIndex, iLength, iThreshold, aContext) {
// implementation copied from ODataListBinding; name changed here, because analytical binding comprises more calculations
var iSectionLength, iSectionStartIndex, iPreloadedSubsequentIndex, iPreloadedPreviousIndex, iRemainingEntries, oSection = {}, fKey = this._getKeys(sGroupId), sKey;
iSectionStartIndex = iStartIndex;
iSectionLength = 0;
// check which data exists before startindex; If all necessary data is loaded iPreloadedPreviousIndex stays undefined
if (!fKey) {
iPreloadedPreviousIndex = iStartIndex;
iPreloadedSubsequentIndex = iStartIndex + iLength;
} else {
for (var i = iStartIndex - 1; i >= Math.max(iStartIndex - iThreshold, 0); i--) {
sKey = fKey(i);
if (!sKey) {
iPreloadedPreviousIndex = i + 1;
break;
}
}
// check which data is already loaded after startindex; If all necessary data is loaded iPreloadedSubsequentIndex stays undefined
for (var j = iStartIndex + iLength; j < iStartIndex + iLength + iThreshold; j++) {
sKey = fKey(j);
if (!sKey) {
iPreloadedSubsequentIndex = j;
break;
}
}
}
// calculate previous remaining entries
iRemainingEntries = iStartIndex - iPreloadedPreviousIndex;
if (iPreloadedPreviousIndex && iStartIndex > iThreshold && iRemainingEntries < iThreshold) {
if (aContext.length !== iLength) {
iSectionStartIndex = iStartIndex - iThreshold;
} else {
iSectionStartIndex = iPreloadedPreviousIndex - iThreshold;
}
iSectionLength = iThreshold;
}
// prevent startIndex from getting out of bounds
// FIX for BCP(1570041982)
// If the startIndex is negative, the $skip value will also be negative, and the length might also be bigger than necessary
iSectionStartIndex = Math.max(iSectionStartIndex, 0);
// No negative preload needed; move startindex if we already have some data
if (iSectionStartIndex === iStartIndex) {
iSectionStartIndex += aContext.length;
}
//read the rest of the requested data
if (aContext.length !== iLength) {
iSectionLength += iLength - aContext.length;
}
//calculate subsequent remaining entries
iRemainingEntries = iPreloadedSubsequentIndex - iStartIndex - iLength;
if (iRemainingEntries == 0) {
iSectionLength += iThreshold;
}
if (iPreloadedSubsequentIndex && iRemainingEntries < iThreshold && iRemainingEntries > 0) {
//check if we need to load previous entries; If not we can move the startindex
// changed the ">=" to ">", because a fix was not migrated, see commit #455622
// FIX for BCP(1570041982)
if (iSectionStartIndex > iStartIndex) {
iSectionStartIndex = iPreloadedSubsequentIndex;
iSectionLength += iThreshold;
}
}
//check final length and adapt sectionLength if needed.
if (this.mFinalLength[sGroupId] && this.mLength[sGroupId] < (iSectionLength + iSectionStartIndex)) {
iSectionLength = this.mLength[sGroupId] - iSectionStartIndex;
}
oSection.startIndex = iSectionStartIndex;
oSection.length = iSectionLength;
// this._trace(sGroupId, "calculateSection:\tstart = " + iSectionStartIndex + "\tlength = " + iSectionLength); // DISABLED FOR PRODUCTION
return oSection;
};
/**
* Searches for missing members in the sub groups and subsequent siblings and ancestors of the given sGroupId
* @returns {Object} Either { groupId_Missing, startIndex_Missing, length_Missing }
* expressing the number (length_Missing) of missing contexts starting in group (groupId_Missing)
* at position (startIndex_Missing) using depth-first traversal of loaded data,
* or { null, length_Missing } if all groups starting with the given ID (sGroupId) and all subsequent are
* completely loaded and still (length_Missing) further members are missing, which cannot be fulfilled by loading data.
* Special case: { null, 0 } denotes that everything is loaded for the requested length.
* @private
*/
AnalyticalBinding.prototype._calculateRequiredGroupExpansion = function(sGroupId, iAutoExpandGroupsToLevel, iStartIndex, iLength) {
var oNO_MISSING_MEMBER = { groupId_Missing: null, length_Missing: 0 };
var that = this;
/**
* helper function
* Searches for missing members in the sub groups of the given sGroupId
* @returns {Object} Either { groupId_Missing, startIndex_Missing, length_Missing }
* expressing the number (length_Missing) of missing contexts starting in group (groupId_Missing)
* at position (startIndex_Missing) using depth-first traversal of loaded data,
* or { null, length_Missing } if the group with given ID (sGroupId) is completely loaded
* and still (length_Missing) further members (of other groups) are missing.
* Special case: { null, 0 } denotes that everything is loaded.
*/
var calculateRequiredSubGroupExpansion = function(sGroupId, iAutoExpandGroupsToLevel, iStartIndex, iLength) {
var iLevel = that._getGroupIdLevel(sGroupId);
if (iLevel == iAutoExpandGroupsToLevel) {
var aContext = that._getLoadedContextsForGroup(sGroupId, iStartIndex, iLength);
var iLastLoadedIndex = iStartIndex + aContext.length - 1;
if (aContext.length >= iLength) {
return oNO_MISSING_MEMBER;
} else if (that.mFinalLength[sGroupId]) {
if (aContext.length >= that.mLength[sGroupId]) {
return { groupId_Missing: null, length_Missing: iLength - aContext.length }; // group completely loaded, but some members are still missing
} else {
return { groupId_Missing: sGroupId, startIndex_Missing: iLastLoadedIndex + 1, length_Missing: iLength - aContext.length }; // loading must start here
}
} else {
return { groupId_Missing: sGroupId, startIndex_Missing: iLastLoadedIndex + 1, length_Missing: iLength - aContext.length }; // loading must start here
}
}
// deepest expansion level not yet reached, so traverse groups in depth-first order
var aContext2 = that._getLoadedContextsForGroup(sGroupId, iStartIndex, iLength);
var iLength_Missing = iLength, iLastLoadedIndex2 = iStartIndex + aContext2.length - 1;
for (var i = -1, oContext; (oContext = aContext2[++i]) !== undefined; ) {
iLength_Missing--; // count the current context
var oGroupExpansionFirstMember = calculateRequiredSubGroupExpansion(that._getGroupIdFromContext(oContext, iLevel + 1), iAutoExpandGroupsToLevel, 0, iLength_Missing);
if (oGroupExpansionFirstMember.groupId_Missing == null) {
if (oGroupExpansionFirstMember.length_Missing == 0) {
return oGroupExpansionFirstMember; // finished - everything is loaded
} else {
iLength_Missing = oGroupExpansionFirstMember.length_Missing;
}
} else {
return oGroupExpansionFirstMember; // loading must start here
}
if (iLength_Missing == 0) {
break;
}
}
if (that.mFinalLength[sGroupId] || iLength_Missing == 0) {
return { groupId_Missing: null, length_Missing: iLength_Missing }; // group completely loaded; maybe some members are still missing
} else {
return { groupId_Missing: sGroupId, startIndex_Missing: iLastLoadedIndex2 + 1, length_Missing: iLength_Missing }; // loading must start here
}
};
// function implementation starts here
var iLevel = this._getGroupIdLevel(sGroupId);
if (iLevel == iAutoExpandGroupsToLevel + 1) {
sGroupId = this._getParentGroupId(sGroupId);
--iLevel;
}
if (sGroupId == null || iLevel > iAutoExpandGroupsToLevel) {
return oNO_MISSING_MEMBER;
}
var iLength_Missing = iLength, iCurrentStartIndex = iStartIndex;
while (sGroupId != null) {
var oGroupExpansionFirstMember = calculateRequiredSubGroupExpansion(sGroupId, iAutoExpandGroupsToLevel, iCurrentStartIndex, iLength_Missing);
if (oGroupExpansionFirstMember.groupId_Missing != null) {
return oGroupExpansionFirstMember;
} else if (oGroupExpansionFirstMember.length_Missing == 0) {
return oGroupExpansionFirstMember;
} else { // last sub-tree is complete, so continue calculation w/ next sibling
var bFoundSibling = false;
while (!bFoundSibling) {
var sParentGroupId = this._getParentGroupId(sGroupId);
if (sParentGroupId == null) {
sGroupId = sParentGroupId;
--iLevel;
break;
}
// determine position of sGroupId in members of group w/ ID sParentGroupId
var sGroupKey = this.mEntityKey[sGroupId];
if (!sGroupKey) {
//jQuery.sap.log.fatal("assertion failed: entitykey for group w/ ID " + sGroupId + " not available");
return oNO_MISSING_MEMBER;
}
var iGroupIndex = this._findKeyIndex(sParentGroupId,sGroupKey);
if (iGroupIndex == -1) {
//jQuery.sap.log.fatal("assertion failed: group w/ ID " + sGroupId + " not found in members of parent w/ ID " + sParentGroupId);
return oNO_MISSING_MEMBER;
}
if (iGroupIndex == this._getKeyCount(sParentGroupId) - 1) {
if (this.mFinalLength[sParentGroupId]) { // last member in group
sGroupId = sParentGroupId;
--iLevel;
continue; // continue with next sibling one level up
} else { // some members of this level have not been loaded yet --> loading must continue at this point
return { groupId_Missing: sParentGroupId, startIndex_Missing: iGroupIndex + 1, length_Missing: iLength_Missing };
}
} else { // continue with next sibling in same level
sGroupKey = this._getKey(sParentGroupId, iGroupIndex + 1);
sGroupId = this._getGroupIdFromContext(this.oModel.getContext('/' + sGroupKey), iLevel);
bFoundSibling = true;
}
}
iCurrentStartIndex = 0;
iLength_Missing = oGroupExpansionFirstMember.length_Missing;
}
}
return { groupId_Missing: null, length_Missing: iLength_Missing }; // all data loaded; number of requested members cannot be fulfilled
};
/**
* @private
*/
AnalyticalBinding.prototype._getResourcePath = function() {
return this.isRelative() ? this.oModel.resolve(this.sPath, this.getContext()) : this.sPath;
};
/**
* @private
*/
AnalyticalBinding.prototype._getEntitySet = function() {
var sEntitySet = this.sEntitySetName;
if (!sEntitySet) {
// assume absolute path complying with conventions from OData4SAP spec
sEntitySet = this.sPath.split("/")[1];
if (sEntitySet.indexOf("(") != -1) {
sEntitySet = sEntitySet.split("(")[0] + "Results";
}
}
return sEntitySet;
};
/**
* get the effective sort order for a given property considering the column settings, local sort() calls and a global sort order from bindRows
* @private
*/
AnalyticalBinding.prototype._getEffectiveSortOrder = function(sPropertyName) {
for (var i = 0; i < this.aSorter.length; i++) {
if (this.aSorter[i] && this.aSorter[i].sPath == sPropertyName) {
return this.aSorter[i].bDescending ? odata4analytics.SortOrder.Descending : odata4analytics.SortOrder.Ascending;
}
}
return null;
};
/**
* get the filter operator that matches the sort order set for the given property
* @private
*/
AnalyticalBinding.prototype._getFilterOperatorMatchingPropertySortOrder = function(sPropertyName, bWithEqual) {
var sFilterOperator;
switch (this._getEffectiveSortOrder(sPropertyName)) {
case odata4analytics.SortOrder.Ascending:
if (bWithEqual) {
sFilterOperator = sap.ui.model.FilterOperator.GE;
} else {
sFilterOperator = sap.ui.model.FilterOperator.GT;
}
break;
case odata4analytics.SortOrder.Descending:
if (bWithEqual) {
sFilterOperator = sap.ui.model.FilterOperator.LE;
} else {
sFilterOperator = sap.ui.model.FilterOperator.LT;
}
break;
default: // null
// default if no sort order applied - matches the default ascending order set for grouped dimensions in prepare...QueryRequest()
sFilterOperator = sap.ui.model.FilterOperator.GT;
}
return sFilterOperator;
};
/**
* @private
*/
AnalyticalBinding.prototype._convertDeprecatedFilterObjects = function(aFilter) {
if (!aFilter) {
return aFilter;
}
// check if some filter object use the deprecated class sap.ui.model.odata.Filter;
// if so, convert them to sap.ui.model.Filter
for (var i = 0, l = aFilter.length; i < l; i++) {
if (sap.ui.model.odata && typeof sap.ui.model.odata.Filter === "function"
&& aFilter[i] instanceof sap.ui.model.odata.Filter) {
aFilter[i] = aFilter[i].convert();
}
}
return aFilter;
};
/********************************
*** Processing Group IDs
********************************/
/**
* @private
*/
AnalyticalBinding.prototype._getGroupIdFromContext = function(oContext, iLevel) {
if (!oContext) {
return null;
}
var sGroupId = "/";
var sDimensionMember = null;
if (iLevel > this.aAggregationLevel.length) {
jQuery.sap.log.fatal("assertion failed: aggregation level deeper than number of current aggregation levels");
}
for (var i = 0; i < iLevel; i++) {
sDimensionMember = oContext.getProperty(this.aAggregationLevel[i]);
if (sDimensionMember != null) {
sGroupId += encodeURIComponent(sDimensionMember) + "/"; // encode to escape slashes and at signs in the value
} else {
sGroupId += "@/";
}
}
return sGroupId;
};
/**
* @private
*/
AnalyticalBinding.prototype._getGroupIdLevel = function(sGroupId) {
if (sGroupId == null) {
jQuery.sap.log.fatal("assertion failed: no need to determine level of group ID = null");
return -1;
}
return sGroupId.split("/").length - 2;
};
/**
* @private
*/
AnalyticalBinding.prototype._getGroupIdComponents = function(sGroupId) {
if (sGroupId == null) {
return null;
}
var aGroupId = sGroupId.split("/");
var aDecodedComponent = [];
for (var i = 1; i < aGroupId.length - 1; i++) { // skip leading and trailing "" array elements
if (aGroupId[i] == "@") {
aDecodedComponent[i - 1] = null;
} else {
aDecodedComponent[i - 1] = decodeURIComponent(aGroupId[i]);
}
}
return aDecodedComponent;
};
/**
* @param {integer} iNumLevels anchestors starting at the root if greater than 0, or starting at the parent of sGroupId if less than 0.
* @private
*/
AnalyticalBinding.prototype._getGroupIdAncestors = function(sGroupId, iNumLevels) {
if (!iNumLevels) {
return [];
}
if (sGroupId == null) {
jQuery.sap.log.fatal("group ID null does not have ancestors");
return [];
}
if (sGroupId == "/") {
if (Math.abs(iNumLevels) == 1) {
return [ null ];
} else {
jQuery.sap.log.fatal("invalid level count " + iNumLevels + " for ancestors of groupId " + sGroupId);
return [];
}
}
var aGroupId = sGroupId.split("/");
var aAncestorGroupId = [], sAncestorGroupId = "";
var iFromLevel = 0, iToLevel = aGroupId.length - 3;
if (iNumLevels > 0) {
if (iNumLevels - 1 > iToLevel) {
jQuery.sap.log.fatal("invalid level count " + iNumLevels + " for ancestors of groupId " + sGroupId);
} else {
iToLevel = iNumLevels - 1;
}
} else if (-(iNumLevels + 1) > iToLevel) {
jQuery.sap.log.fatal("invalid level count " + iNumLevels + " for ancestors of groupId " + sGroupId);
} else {
iFromLevel = iToLevel + 1 + iNumLevels;
for (var i = 0; i < iFromLevel; i++) {
sAncestorGroupId += aGroupId[i] + "/";
}
}
for (var j = iFromLevel; j <= iToLevel; j++) {
sAncestorGroupId += aGroupId[j] + "/";
aAncestorGroupId.push(sAncestorGroupId);
}
return aAncestorGroupId;
};
/**
* @private
*/
AnalyticalBinding.prototype._getParentGroupId = function(sGroupId) {
return this._getGroupIdAncestors(sGroupId, -1)[0];
};
AnalyticalBinding.prototype._removeDuplicatesFromStringArray = function(aString) {
var oTemp = {};
for (var i = 0; i < aString.length; i++) {
oTemp[aString[i]] = true;
}
var aUniqueString = [];
for (var s in oTemp) {
aUniqueString.push(s);
}
return aUniqueString;
};
/********************************
*** Maintaining handles of pending requests
********************************/
/**
* Get an ID for a new request handle yet to be registered
*
* @private
*/
AnalyticalBinding.prototype._getIdForNewRequestHandle = function() {
if (this.oPendingRequestHandle === undefined) {
this.oPendingRequestHandle = [];
}
// find first unused slot or extend array
for (var i = 0; i < this.oPendingRequestHandle.length; i++) {
if (this.oPendingRequestHandle[i] === undefined) {
return i;
}
}
this.oPendingRequestHandle[this.oPendingRequestHandle.length] = undefined;
return this.oPendingRequestHandle.length - 1;
};
/**
* Register a new request handle with its given request ID
*
* @private
*/
AnalyticalBinding.prototype._registerNewRequestHandle = function(iRequestHandleId, oRequestHandle) {
if (this.oPendingRequestHandle[iRequestHandleId] !== undefined) {
jQuery.sap.log.fatal("request handle ID already in use");
}
this.oPendingRequestHandle[iRequestHandleId] = oRequestHandle;
};
/**
* Deregister handle of completed request
*
* @private
*/
AnalyticalBinding.prototype._deregisterHandleOfCompletedRequest = function(iRequestHandleId) {
if (jQuery.isEmptyObject(this.oPendingRequestHandle)) {
jQuery.sap.log.warning("No request handles to be cleared. Previous abort/resetData?");
return;
}
if (this.oPendingRequestHandle[iRequestHandleId] === undefined) {
jQuery.sap.log.fatal("no handle found for this request ID");
}
this.oPendingRequestHandle[iRequestHandleId] = undefined;
};
/**
* Abort all currently sent requests, which have not yet been completed
*
* @private
*/
AnalyticalBinding.prototype._abortAllPendingRequestsByHandle = function() {
// this._trace_enter("ReqHandle", "_abortAllPendingRequestsByHandle"); // DISABLED FOR PRODUCTION
for (var i = 0; i < this.oPendingRequestHandle.length; i++) {
if (this.oPendingRequestHandle[i]) {
// this._trace_message("ReqHandle", "abort index " + i);
if (this.oPendingRequestHandle[i] !== undefined) {
this.oPendingRequestHandle[i].abort();
}
}
}
this.oPendingRequestHandle = [];
// this._trace_leave("ReqHandle", "_abortAllPendingRequestsByHandle"); // DISABLED FOR PRODUCTION
};
/********************************
*** Maintaining pending requests
********************************/
/**
* Construct a request ID for a query request of the specified type
*
* @private
*/
AnalyticalBinding.prototype._getRequestId = function(iRequestType, mParameters) {
switch (iRequestType) {
case AnalyticalBinding._requestType.groupMembersQuery:
if (mParameters.groupId === undefined) {
jQuery.sap.log.fatal("missing group ID");
}
return AnalyticalBinding._requestType.groupMembersQuery + (mParameters.groupId == null ? "" : mParameters.groupId);
case AnalyticalBinding._requestType.levelMembersQuery:
if (mParameters.level === undefined) {
jQuery.sap.log.fatal("missing level");
}
if (mParameters.groupId === undefined) {
jQuery.sap.log.fatal("missing groupId");
}
// for accelerated auto-expand, group Id does not provide context, i.e. filter condition, for the requested data, but is only a starting point
return "" + AnalyticalBinding._requestType.levelMembersQuery + mParameters.level + (mParameters.tupleIndex ? "-" + mParameters.tupleIndex : "");
case AnalyticalBinding._requestType.totalSizeQuery:
return AnalyticalBinding._requestType.totalSizeQuery;
case AnalyticalBinding._requestType.reloadMeasuresQuery:
if (!mParameters.multiUnitEntryKey) {
jQuery.sap.log.fatal("missing multi unit entry key");
}
return AnalyticalBinding._requestType.reloadMeasuresQuery + mParameters.multiUnitEntryKey;
default:
jQuery.sap.log.fatal("invalid request type " + iRequestType);
return -1;
}
};
/**
* Register another request to maintain its lifecycle (pending, completed)
*
* @private
*/
AnalyticalBinding.prototype._registerNewRequest = function(sRequestId) {
if (sRequestId == undefined || sRequestId == "") {
jQuery.sap.log.fatal("missing request ID");
return;
}
if (!this.oPendingRequests[sRequestId]) {
this.oPendingRequests[sRequestId] = 1;
} else {
++this.oPendingRequests[sRequestId];
}
};
/**
* Declare a group of related (pending) requests
*
* @private
*/
AnalyticalBinding.prototype._considerRequestGrouping = function(aRequestId) {
for (var i = -1, sRequestId; (sRequestId = aRequestId[++i]) !== undefined; ) {
if (this.oGroupedRequests[sRequestId] === undefined) {
this.oGroupedRequests[sRequestId] = {};
}
var oGroup = this.oGroupedRequests[sRequestId];
for (var j = 0; j < aRequestId.length; j++) {
oGroup[aRequestId[j]] = true;
}
}
};
/**
* Is a request pending for a given group ID?
*
* @private
*/
AnalyticalBinding.prototype._isRequestPending = function(sRequestId) {
return this.oPendingRequests[sRequestId] != undefined && this.oPendingRequests[sRequestId] > 0;
};
/**
* Deregister a request, because its data have been received and processed. A call to this method must be followed
* (not immediately, but logically) by this._cleanupGroupingForCompletedRequest to cleanup grouping information.
*
* @private
*/
AnalyticalBinding.prototype._deregisterCompletedRequest = function(sRequestId) {
// in case there are no pending request, log a warning. This might happen during a refresh call
// helps to keep track of timing issues / race conditions with already returned requests
if (jQuery.isEmptyObject(this.oPendingRequests)) {
jQuery.sap.log.warning("There are no pending requests which could be set to 'completed'.");
return;
}
if (!this.oPendingRequests[sRequestId]) {
jQuery.sap.log.fatal("assertion failed: there is no pending request ID " + sRequestId);
}
if (this.oPendingRequests[sRequestId] == 1) {
delete this.oPendingRequests[sRequestId];
} else {
--this.oPendingRequests[sRequestId];
}
};
/**
* Cleanup request grouping, because its data have been received and processed. This method allows a caller to determine if it is possible
* to raise the "all data received" event for a group of related OData requests.
*
* A call to this method must be preceded by this._deregisterCompletedRequest to mark the received response.
*
* @return {boolean} whether or not all requests grouped together with this request have now been completed
* @private
*/
AnalyticalBinding.prototype._cleanupGroupingForCompletedRequest = function(sRequestId) {
if (this._isRequestPending(sRequestId)) {
return false;
}
var bGroupCompleted = true;
if (this.oGroupedRequests[sRequestId] != undefined) {
for ( var sOtherRequestId in this.oGroupedRequests[sRequestId]) {
if (this.oPendingRequests[sOtherRequestId]) {
bGroupCompleted = false;
break;
}
}
}
if (bGroupCompleted) {
var oRelatedGroup = this.oGroupedRequests[sRequestId];
delete this.oGroupedRequests[sRequestId];
for ( var sOtherRequestId2 in oRelatedGroup) {
if (sOtherRequestId2 != sRequestId) {
this._cleanupGroupingForCompletedRequest(sOtherRequestId2);
}
}
}
return bGroupCompleted;
};
//********************************************************************************
//*** Service data consolidation (for multi-unit entities)
//********************************************************************************/
AnalyticalBinding.prototype._getKeyIndexMapping = function(sGroupId, iStartIndex) {
var aKeyIndex = this.mKeyIndex[sGroupId];
var aServiceKey = this.mServiceKey[sGroupId];
var iServiceKeyIndex = iStartIndex;
if (aKeyIndex !== undefined) { // find appropriate service key index for given start index
// search for the last occupied key index
var iLastOccupiedIndex = iStartIndex;
if (iLastOccupiedIndex > 0) {
while (--iLastOccupiedIndex > 0) {
if (aKeyIndex[iLastOccupiedIndex] !== undefined) {
break;
}
}
}
var iLastOccupiedServiceKeyIndex;
if (iLastOccupiedIndex == 0) {
iLastOccupiedServiceKeyIndex = 0;
} else {
if (aKeyIndex[iLastOccupiedIndex] >= 0) {
iLastOccupiedServiceKeyIndex = aKeyIndex[iLastOccupiedIndex];
} else if (aKeyIndex[iLastOccupiedIndex + 1] === undefined) { // iLastOccupiedIndex is the last key index before hole.
iLastOccupiedServiceKeyIndex = aKeyIndex[iLastOccupiedIndex] == "ZERO" ? 0 : -aKeyIndex[iLastOccupiedIndex];
while (aServiceKey[iLastOccupiedServiceKeyIndex + 1] !== undefined) {
++iLastOccupiedServiceKeyIndex;
}
} else { // iLastOccupiedServiceKeyIndex is the service key index before start of service keys related to next key index.
iLastOccupiedServiceKeyIndex = Math.abs(aKeyIndex[iLastOccupiedIndex + 1]) - 1;
}
if (aServiceKey[iLastOccupiedServiceKeyIndex] === undefined) {
jQuery.sap.log.fatal("assertion failed: no service key at iLastOccupiedServiceKeyIndex = " + iLastOccupiedServiceKeyIndex);
}
}
var iDistance = iStartIndex - iLastOccupiedIndex;
iServiceKeyIndex = iLastOccupiedServiceKeyIndex + iDistance;
}
var oKeyIndexMapping = {
sGroupId : sGroupId,
iIndex : iStartIndex,
iServiceKeyIndex : iServiceKeyIndex
};
return oKeyIndexMapping;
};
AnalyticalBinding.prototype._moveKeyIndexMapping = function(oKeyIndexMapping, iIndexOffset) {
return this._getKeyIndexMapping(oKeyIndexMapping.sGroupId, oKeyIndexMapping.iIndex + iIndexOffset);
};
// access entry key for a given group ID and index
AnalyticalBinding.prototype._getKey = function(sGroupId, iIndex) { // replaces this.mKey[sGroupId][i] in Table.js
var iServiceKeyIndex = this.mKeyIndex[sGroupId][iIndex];
if (iServiceKeyIndex === undefined) {
return undefined;
}
if (iServiceKeyIndex >= 0) {
return this.mServiceKey[sGroupId][iServiceKeyIndex];
}
if (this.mMultiUnitKey[sGroupId] === undefined) {
jQuery.sap.log.fatal("assertion failed: missing expected multi currency key for group with ID " + sGroupId);
// this._trace_debug_if(true, "assertion failed: missing expected multi currency key for group with ID " + sGroupId);
return null;
}
var sKey = this.mMultiUnitKey[sGroupId][iIndex];
if (sKey === undefined) {
jQuery.sap.log.fatal("assertion failed: missing expected multi currency key for group with ID " + sGroupId + " at pos " + iIndex);
// this._trace_debug_if(true, "assertion failed: missing expected multi currency key for group with ID " + sGroupId + " at pos " + iIndex);
return null;
}
return sKey;
};
// access entry key array for a given group ID (as function)
AnalyticalBinding.prototype._getKeys = function(sGroupId) { // replaces this.mKey[sGroupId][i] in Table.js
if (this.mKeyIndex[sGroupId] === undefined) {
return undefined;
}
var that = this;
return function (iIndex) {
return that._getKey(sGroupId, iIndex);
};
};
// access array of service entry keys for a given group ID and index
AnalyticalBinding.prototype._getServiceKeys = function(sGroupId, iIndex) {
var aKeyIndex = this.mKeyIndex[sGroupId];
if (aKeyIndex === undefined) {
return undefined;
}
var aServiceKey = this.mServiceKey[sGroupId],
iServiceKeyIndex = aKeyIndex[iIndex];
if (iServiceKeyIndex === undefined) {
return undefined;
}
if (iServiceKeyIndex >= 0) {
return [ aServiceKey[iServiceKeyIndex] ];
}
var aGroupIndexServiceKey = [];
if (aKeyIndex[iIndex + 1] === undefined) {
iServiceKeyIndex = aKeyIndex[iIndex] == "ZERO" ? 0 : -aKeyIndex[iIndex];
while (aServiceKey[iServiceKeyIndex] !== undefined) {
aGroupIndexServiceKey.push(aServiceKey[iServiceKeyIndex++]);
}
} else {
iServiceKeyIndex = aKeyIndex[iIndex] == "ZERO" ? 0 : -aKeyIndex[iIndex];
for (var i = iServiceKeyIndex, iNextEntryIndex = Math.abs(aKeyIndex[iIndex + 1]); i < iNextEntryIndex; i++) {
aGroupIndexServiceKey.push(aServiceKey[i]);
}
}
return aGroupIndexServiceKey;
};
// number of keys in a group
AnalyticalBinding.prototype._getKeyCount = function(sGroupId) { // replaces this.mKey[sGroupId].length in Table.js
if (this.mKeyIndex[sGroupId] === undefined) {
return undefined;
}
return this.mKeyIndex[sGroupId].length;
};
// substitute for indexOf in the key array for some group
AnalyticalBinding.prototype._findKeyIndex = function(sGroupId, sKey) {
// TODO optimize by first looking into mMultiUnitKey; if not found, search in mServiceKey; if not found, return -1
// naive implementation follows
var aKeyIndex = this.mKeyIndex[sGroupId];
var aServiceKey = this.mServiceKey[sGroupId];
var aMultiUnitKey = this.mMultiUnitKey[sGroupId];
for (var i = 0; i < this.mLength[sGroupId]; i++) {
if (aKeyIndex[i] < 0) {
if (aMultiUnitKey[i] == sKey) {
return i;
}
} else if (aServiceKey[aKeyIndex[i]] == sKey) {
return i;
}
}
return -1;
};
// save the key of a loaded entry at the given indexes
AnalyticalBinding.prototype._setServiceKey = function(oKeyIndexMapping, sServiceKey) {
if (!this.mServiceKey[oKeyIndexMapping.sGroupId]) {
this.mServiceKey[oKeyIndexMapping.sGroupId] = [];
}
if (!this.mKeyIndex[oKeyIndexMapping.sGroupId]) {
this.mKeyIndex[oKeyIndexMapping.sGroupId] = [];
}
var bNewKey = this.mServiceKey[oKeyIndexMapping.sGroupId][oKeyIndexMapping.iServiceKeyIndex] === undefined;
this.mServiceKey[oKeyIndexMapping.sGroupId][oKeyIndexMapping.iServiceKeyIndex++] = sServiceKey;
this.mKeyIndex[oKeyIndexMapping.sGroupId][oKeyIndexMapping.iIndex++] = oKeyIndexMapping.iServiceKeyIndex - 1;
return bNewKey;
};
// save the keys of adjacent identical entries only differing in the given units; oKeyIndexMapping points to the position after the first multi-unit entry
// returns number of service keys that were not yet available locally
AnalyticalBinding.prototype._setAdjacentMultiUnitKeys = function(oKeyIndexMapping, oMultiUnitRepresentative, aMultiUnitEntry) {
if (!this.mServiceKey[oKeyIndexMapping.sGroupId]) {
this.mServiceKey[oKeyIndexMapping.sGroupId] = [];
}
if (!this.mKeyIndex[oKeyIndexMapping.sGroupId]) {
this.mKeyIndex[oKeyIndexMapping.sGroupId] = [];
}
if (!this.mMultiUnitKey[oKeyIndexMapping.sGroupId]) {
this.mMultiUnitKey[oKeyIndexMapping.sGroupId] = [];
}
// need to adjust positions to point to the first multi-unit entry
// why? because in processGroupMemberQueryResponse(), advancing the mapping halts after(!) when the multi-unit case is detected, which happens with the second entry
--oKeyIndexMapping.iIndex;
--oKeyIndexMapping.iServiceKeyIndex;
this.mMultiUnitKey[oKeyIndexMapping.sGroupId][oKeyIndexMapping.iIndex] = this.oModel._getKey(oMultiUnitRepresentative.oEntry);
// the following setting in the key index serves two purposes: indicate the multi-unit situation and remember position of first related service key
this.mKeyIndex[oKeyIndexMapping.sGroupId][oKeyIndexMapping.iIndex++] = oKeyIndexMapping.iServiceKeyIndex > 0 ? -oKeyIndexMapping.iServiceKeyIndex : "ZERO";
// store service keys and consider new keys in the discarded count
var iNewServiceKeyIndexCount = 0;
for (var i = 0; i < aMultiUnitEntry.length; i++) {
if (!this.mServiceKey[oKeyIndexMapping.sGroupId][oKeyIndexMapping.iServiceKeyIndex]) {
++iNewServiceKeyIndexCount;
}
this.mServiceKey[oKeyIndexMapping.sGroupId][oKeyIndexMapping.iServiceKeyIndex++] = this.oModel._getKey(aMultiUnitEntry[i]);
}
return iNewServiceKeyIndexCount;
};
// combine loaded key index entries with a block of subsequent key index entries starting at the given key index mapping
AnalyticalBinding.prototype._mergeLoadedKeyIndexWithSubsequentIndexes = function(oKeyIndexMapping, aAggregationLevel, aSelectedUnitPropertyName, bIsFlatListRequest) {
/*
* Note:
* This is a complex algorithm with an external description.
* You will need this description in order to understand this implementation.
* The variable names are derived from the names used in the description, underscores in the names indicate indexed names.
*/
var aKI = this.mKeyIndex[oKeyIndexMapping.sGroupId], // is mKI in description
aSK = this.mServiceKey[oKeyIndexMapping.sGroupId], // is mSK in description
aMUK = this.mMultiUnitKey[oKeyIndexMapping.sGroupId], // is mMUK in description
iDiscardedEntriesCount = 0,
n_i = oKeyIndexMapping.iServiceKeyIndex,
n_e = oKeyIndexMapping.iIndex;
var oMultiUnitRepresentative, oMultiUnitEntryKey;
if (aKI === undefined) {
return iDiscardedEntriesCount;
}
// step 1: determine if the adjacent service keys denote same dimension key and therefore must be merged
var bNeedMultiUnitKeyMerge = false;
var sPreviousServiceKey = aSK[n_i - 1],
sNextServiceKey = aSK[n_i];
if (sNextServiceKey === undefined) {
return iDiscardedEntriesCount;
}
if (sPreviousServiceKey === undefined) {
jQuery.sap.log.fatal("assertion failed: missing expected entry before given key index");
return iDiscardedEntriesCount;
}
var oPreviousEntry = this.oModel.getObject("/" + sPreviousServiceKey);
var oNextEntry = this.oModel.getObject("/" + sNextServiceKey);
var sPreviousEntryDimensionKeyString = "",
sNextEntryDimensionKeyString = "";
for (var i = 0; i < aAggregationLevel.length; i++) {
sPreviousEntryDimensionKeyString += oPreviousEntry[aAggregationLevel[i]] + "|";
sNextEntryDimensionKeyString += oNextEntry[aAggregationLevel[i]] + "|";
}
bNeedMultiUnitKeyMerge = sPreviousEntryDimensionKeyString == sNextEntryDimensionKeyString;
// calculate nPrime_e for next steps
var nPrime_e = n_e;
if (nPrime_e >= this.mLength[oKeyIndexMapping.sGroupId]) {
jQuery.sap.log.fatal("assertion failed: service key exists,but no corresponding key index found");
// this._trace_debug_if(true, "assertion failed: service key exists,but no corresponding key index found");
return iDiscardedEntriesCount;
}
while (aKI[nPrime_e] === undefined || Math.abs(aKI[nPrime_e]) < n_i) {
++nPrime_e;
}
// this._trace_enter("SvcDatCons", "_mergeLoadedKeyIndexWithSubsequentIndexes", "groupId=" + oKeyIndexMapping.sGroupId, { n_e: n_e, nPrime_e: nPrime_e, n_i: n_i }, ["n_e","nPrime_e","n_i"]); // DISABLED FOR PRODUCTION
// step 2: combine loaded key index entries with subsequent key index entries
if (bNeedMultiUnitKeyMerge) { // case 1
if (Math.abs(aKI[nPrime_e]) == n_i && aKI[nPrime_e] < 0) { // case a) nPrime_e is a multi-unit entry and starts at n_i
// this._trace_debug_if(aKI[nPrime_e] >= 0 || aMUK[nPrime_e] === undefined, "unexpected: no multi-unit entry found");
if (nPrime_e > n_e) { // relevance check for merging the loaded key index section with subsequent indexes
if (aKI[n_e - 1] < 0) { // case I: (nPrime_e - 1) is a multi-unit entry
// this._trace_message("SvcDatCons", "case 1.a.I"); // DISABLED FOR PRODUCTION
aMUK[nPrime_e] = undefined; // delete its multi-unit entry
// delete aKI entries n_e ... nPrime_e - 1 and at nPrime_e (this will remove the redundant second multi-unit entry at nPrime_e)
aKI.splice(n_e, nPrime_e - n_e + 1);
aMUK.splice(n_e, nPrime_e - n_e + 1);
} else { // case II: (nPrime_e - 1) is NOT a multi-unit entry
// this._trace_message("SvcDatCons", "case 1.a.II"); // DISABLED FOR PRODUCTION
aKI[n_e - 1] = -aKI[n_e - 1]; // make n_e - 1 a multi-unit entry
aMUK[n_e - 1] = aMUK[nPrime_e]; // reuse aMUK[nPrime_e] for aMUK[n_e - 1]
aMUK[nPrime_e] = undefined; // clear aMUK[nPrime_e]
// delete aKI entries n_e ... nPrime_e - 1 and at nPrime_e (this will remove the redundant second multi-unit entry at nPrime_e)
aKI.splice(n_e, nPrime_e - n_e + 1);
aMUK.splice(n_e, nPrime_e - n_e + 1);
iDiscardedEntriesCount = 1;
}
}
} else if (Math.abs(aKI[nPrime_e]) > n_i) { // case b) nPrimePrime_e = nPrime_e - 1 is a multi-unit entry pointing to service keys before n_i
var nPrimePrime_e = nPrime_e - 1;
// this._trace_debug_if(n_e == 314, "stop");
// this._trace_debug_if(!(Math.abs(aKI[nPrimePrime_e]) < n_i), "unexpected: this key index must point to a key before n_i");
if (aKI[nPrimePrime_e] > 0) { // case I: (nPrimePrime_e) is not a multi-unit entry
// this._trace_message("SvcDatCons", "case 1.b.I"); // DISABLED FOR PRODUCTION
// this._trace_debug_if(aKI[nPrimePrime_e] < n_i - 1, "unexpected: this key index must point to the last read service key or before"); // this case would be 1 b) II ii
// create a multi-unit entry for nPrimePrime_e
oMultiUnitRepresentative = this._createMultiUnitRepresentativeEntry(oKeyIndexMapping.sGroupId, oPreviousEntry, aSelectedUnitPropertyName, undefined, bIsFlatListRequest);
oMultiUnitEntryKey = this.oModel._getKey(oMultiUnitRepresentative.oEntry);
// make nPrimePrime_e a multi-unit entry
aKI[nPrimePrime_e] = -aKI[nPrimePrime_e];
aMUK[nPrimePrime_e] = oMultiUnitEntryKey;
if (nPrimePrime_e > n_e) {
// delete aKI entries n_e ... nPrimePrime_e - 1
aKI.splice(n_e, nPrimePrime_e - n_e);
aMUK.splice(n_e, nPrimePrime_e - n_e);
}
// this._trace_debug_if(Math.abs(aKI[nPrime_e]) - Math.abs(aKI[nPrimePrime_e]) <= 1, "unexpected: marked as multi-unit key, but only a single service key!?");
if (oMultiUnitRepresentative.bIsNewEntry) {
// this._trace_debug_if(Math.abs(aKI[nPrime_e]) - Math.abs(aKI[nPrimePrime_e]) > 2, "unexpected: more than one subsequent service key for this multi-unit entry, but no representative so far!?");
// two service keys contributing to this multi-unit entry, and one new multi-unit representative => 1 more service key to discard
iDiscardedEntriesCount = 1;
} else {
// this._trace_debug_if(oMultiUnitRepresentative.iIndex != nPrimePrime_e, "the existing multi-unit representative does not have index nPrimePrime_e");
// more than two service keys contributing to this multi-unit entry, which were already detected as "multi-unit" and therefore discarded.
// since the existing multi-unit representative has index nPrimePrime_e, the service key pointed to by this index was also already covered
// => 0 more service key to discard
iDiscardedEntriesCount = 0;
}
} else if (aKI[n_e - 1] < 0) {
// case II: (nPrimePrime_e) is a multi-unit entry
// case i: (n_e - 1) is a multi-unit entry
if (nPrime_e > n_e) { // relevance check for merging the loaded key index section with subsequent indexes
// this._trace_message("SvcDatCons", "case 1.b.II.i"); // DISABLED FOR PRODUCTION
aMUK[nPrimePrime_e] = undefined; // delete its multi-unit entry
// delete aKI entries n_e ... nPrimePrime_e - 1 and at nPrimePrime_e (this will remove the redundant second multi-unit entry at nPrimePrime_e)
aKI.splice(n_e, nPrimePrime_e - n_e + 1);
aMUK.splice(n_e, nPrimePrime_e - n_e + 1);
}
} else { // case ii: (n_e - 1) is NOT a multi-unit entry
// this._trace_message("SvcDatCons", "case 1.b.II.ii"); // DISABLED FOR PRODUCTION
// this._trace_debug_if(aKI[n_e - 1] != Math.abs(aKI[nPrimePrime_e]), "unexpected: n_e - 1 does not point to same entry as nPrimePrime_e");
// this._trace_debug_if(Math.abs(aKI[nPrimePrime_e]) != n_i - 1, "unexpected: nPrimePrime_e should point to n_i - 1");
aKI[n_e - 1] = -aKI[n_e - 1]; // make n_e - 1 a multi-unit entry
aMUK[n_e - 1] = aMUK[nPrimePrime_e]; // reuse aMUK[nPrimePrime_e] for aMUK[n_e - 1]
aMUK[nPrimePrime_e] = undefined; // clear aMUK[nPrimePrime_e]
// delete aKI entries n_e ... nPrime_e - 1 and at nPrimePrime_e (this will remove the redundant second multi-unit entry at nPrimePrime_e)
aKI.splice(n_e, nPrimePrime_e - n_e + 1);
aMUK.splice(n_e, nPrimePrime_e - n_e + 1);
}
} else if (aKI[nPrime_e] == n_i) { // case c) nPrime_e is NOT a multi-unit entry
if (nPrime_e > n_e) { // relevance check for merging the loaded key index section with subsequent indexes
if (aKI[n_e - 1] < 0) { // case I: (nPrime_e - 1) is a multi-unit entry
// this._trace_message("SvcDatCons", "case 1.c.I"); // DISABLED FOR PRODUCTION
// delete aKI entries n_e ... nPrime_e - 1 and at nPrime_e (this will remove the redundant second multi-unit entry at nPrimePrime_e)
aKI.splice(n_e, nPrime_e - n_e + 1);
aMUK.splice(n_e, nPrime_e - n_e + 1);
iDiscardedEntriesCount = 1;
} else { // case II: (nPrime_e - 1) is NOT a multi-unit entry
// this._trace_message("SvcDatCons", "case 1.c.II"); // DISABLED FOR PRODUCTION
// create a multi-unit entry for n_e - 1
oMultiUnitRepresentative = this._createMultiUnitRepresentativeEntry(oKeyIndexMapping.sGroupId, oPreviousEntry, aSelectedUnitPropertyName, undefined, bIsFlatListRequest);
oMultiUnitEntryKey = this.oModel._getKey(oMultiUnitRepresentative.oEntry);
if (!oMultiUnitRepresentative.bIsNewEntry) {
jQuery.sap.log.fatal("assertion failed: multi-unit entry already existed before");
// this._trace_debug_if(! oMultiUnitRepresentative.bIsNewEntry, "assertion failed: multi-unit entry already existed before");
}
// make n_e - 1 a multi-unit entry
aKI[n_e - 1] = -aKI[n_e - 1];
aMUK[n_e - 1] = oMultiUnitEntryKey;
// delete aKI entries n_e ... nPrime_e - 1 and at nPrime_e (this will remove the redundant second multi-unit entry at nPrimePrime_e)
aKI.splice(n_e, nPrime_e - n_e + 1);
aMUK.splice(n_e, nPrime_e - n_e + 1);
iDiscardedEntriesCount = 1;
}
}
} else {
jQuery.sap.log.fatal("assertion failed: uncovered case detected");
// this._trace_debug_if(true, "assertion failed: uncovered case detected");
return iDiscardedEntriesCount;
}
} else if (aKI[nPrime_e] > n_i) {
// case 2
// case a)
// this._trace_message("SvcDatCons", "case 2.a"); // DISABLED FOR PRODUCTION
jQuery.sap.log.fatal("unstable query result for group ID " + oKeyIndexMapping.sGroupId + ": entries have been removed or added. Complete reload required");
// this._trace_debug_if(true, "unstable query result for group ID " + oKeyIndexMapping.sGroupId + ": entries have been removed or added. Complete reload required");
} else if (nPrime_e - n_e > 0) {
// case b)
// this._trace_message("SvcDatCons", "case 2.b"); // DISABLED FOR PRODUCTION
// delete aKI entries n_e ... nPrime_e - 1
aKI.splice(n_e, nPrime_e - n_e);
// this._trace_debug_if(aMUK === undefined, "unexpected: aMUK is undefined, so no multi-unit keys so far!?");
aMUK.splice(n_e, nPrime_e - n_e);
}
// this._trace_leave("SvcDatCons", "_mergeLoadedKeyIndexWithSubsequentIndexes", "dicardedCount=" + iDiscardedEntriesCount); // DISABLED FOR PRODUCTION
return iDiscardedEntriesCount;
};
// create a local multi unit entry by copying the given reference entry, and modifying this new entry: clear all unit properties that are not part of the aggregation level, and all measures
// returns { oEntry, bIsNewEntry) the multi-unit representativ entry and a flag whether it already existed before this call
AnalyticalBinding.prototype._createMultiUnitRepresentativeEntry = function(sGroupId, oReferenceEntry, aSelectedUnitPropertyName, aDeviatingUnitPropertyName, bIsFlatListRequest) {
// set up properties for measures and units in this new entry
var oMultiUnitEntry = jQuery.extend(true, {}, oReferenceEntry);
var aReloadMeasurePropertyName = [];
for ( var sMeasureName in this.oMeasureDetailsSet) {
var oMeasureDetails = this.oMeasureDetailsSet[sMeasureName];
if (!bIsFlatListRequest && !this.mAnalyticalInfoByProperty[sMeasureName].total) {
if (oMeasureDetails.rawValuePropertyName != undefined) {
oMultiUnitEntry[oMeasureDetails.rawValuePropertyName] = undefined;
}
if (oMeasureDetails.formattedValuePropertyName != undefined) {
oMultiUnitEntry[oMeasureDetails.formattedValuePropertyName] = undefined;
}
} else {
if (oMeasureDetails.rawValuePropertyName != undefined) {
oMultiUnitEntry[oMeasureDetails.rawValuePropertyName] = null; // cannot be "*" because of type validation!
}
if (oMeasureDetails.formattedValuePropertyName != undefined) {
oMultiUnitEntry[oMeasureDetails.formattedValuePropertyName] = "*";
}
}
// determine if this measure that can be reloaded, because their unit properties do not have deviating values
if (aDeviatingUnitPropertyName) {
if (!oMeasureDetails.unitPropertyName || jQuery.inArray(oMeasureDetails.unitPropertyName, aDeviatingUnitPropertyName) == -1) {
aReloadMeasurePropertyName.push(oMeasureDetails.rawValuePropertyName);
}
}
}
for (var k = 0; k < aSelectedUnitPropertyName.length; k++) {
if (jQuery.inArray(aSelectedUnitPropertyName[k], aDeviatingUnitPropertyName) != -1) {
oMultiUnitEntry[aSelectedUnitPropertyName[k]] = "*";
}
}
/*
* assign a key to this new entry that allows to import it into the OData model that is guaranteed to be stable when used for multiple
* bindings 1) Take all(!) grouping dimensions in alphabetical order of their names 2) Concatenate the values of these dimenensions in this
* order separated by "," 3) append some indicator such as "-multiunit-not-dereferencable" to mark this special entry
*/
var sMultiUnitEntryKey = "";
for (var l = 0; l < this.aAllDimensionSortedByName.length; l++) {
var sDimVal = oMultiUnitEntry[this.aAllDimensionSortedByName[l]];
sMultiUnitEntryKey += (sDimVal === undefined ? "" : sDimVal) + ",";
}
sMultiUnitEntryKey += "-multiple-units-not-dereferencable";
// check if an entry already exists; if so, dont proceed, but return it
var iMultiUnitEntryIndex;
if (this.mMultiUnitKey[sGroupId] && (iMultiUnitEntryIndex = jQuery.inArray(sMultiUnitEntryKey, this.mMultiUnitKey[sGroupId])) != -1) {
return { oEntry: this.oModel.getObject("/" + sMultiUnitEntryKey), bIsNewEntry : false, iIndex: iMultiUnitEntryIndex, aReloadMeasurePropertyName: aReloadMeasurePropertyName }; // already created
}
// this modified copy must be imported to the OData model as a new entry with a modified key and OData metadata
oMultiUnitEntry.__metadata.uri = sMultiUnitEntryKey;
delete oMultiUnitEntry.__metadata["self"];
delete oMultiUnitEntry.__metadata["self_link_extensions"];
oMultiUnitEntry["^~volatile"] = true; // mark entry to distinguish it from others contained in the regular OData result
this.oModel._importData(oMultiUnitEntry, {});
// mark the context for this entry as volatile to facilitate special treatment by consumers
var sMultiUnitEntryModelKey = this.oModel._getKey(oMultiUnitEntry);
this.oModel.getContext('/' + sMultiUnitEntryModelKey)["_volatile"] = true;
return { oEntry: oMultiUnitEntry, bIsNewEntry : true, aReloadMeasurePropertyName: aReloadMeasurePropertyName };
};
//********************************
//*** Miscellaneous
//********************************/
AnalyticalBinding.prototype._clearAllPendingRequests = function() {
this.oPendingRequests = {};
this.oGroupedRequests = {};
};
/**
* Resets the current list data and length
*
* @private
*/
AnalyticalBinding.prototype.resetData = function(oContext) {
var sGroupId = oContext ? oContext.getPath() : undefined;
this._resetData(sGroupId);
};
AnalyticalBinding.prototype._resetData = function(sGroupId) {
if (sGroupId) {
// reset only specific content
delete this.mServiceKey[sGroupId];
delete this.mServiceLength[sGroupId];
delete this.mServiceFinalLength[sGroupId];
delete this.mKeyIndex[sGroupId];
delete this.mLength[sGroupId];
delete this.mMultiUnitKey[sGroupId];
delete this.mEntityKey[sGroupId];
} else {
this.mServiceKey = {};
this.mServiceLength = {};
this.mServiceFinalLength = {};
this.mFinalLength = this.mServiceFinalLength;
this.mKeyIndex = {};
this.mLength = {};
this.mMultiUnitKey = {};
this.mEntityKey = {};
}
};
/**
* Refreshes the binding, check whether the model data has been changed and fire change event if this is the case. For service side models this should refetch
* the data from the service. To update a control, even if no data has been changed, e.g. to reset a control after failed validation, please use the parameter
* bForceUpdate.
*
* @param {boolean}
* [bForceUpdate] Update the bound control even if no data has been changed
* @public
*/
AnalyticalBinding.prototype.refresh = function(bForceUpdate) {
// apply is used here to be compatible to ODataModel v1, where the signature is like the private _refresh()
AnalyticalBinding.prototype._refresh.apply(this, arguments);
};
/**
* @private
*/
AnalyticalBinding.prototype._refresh = function(bForceUpdate, mChangedEntities, mEntityTypes) {
var bChangeDetected = false;
if (!bForceUpdate) {
if (mEntityTypes) {
var sResolvedPath = this.oModel.resolve(this.sPath, this.oContext);
var oEntityType = this.oModel.oMetadata._getEntityTypeByPath(sResolvedPath);
if (oEntityType && (oEntityType.entityType in mEntityTypes)) {
bChangeDetected = true;
}
}
if (mChangedEntities && !bChangeDetected) {
jQuery.each(this.mServiceKey, function(i, aNodeKeys) {
jQuery.each(aNodeKeys, function(i, sKey) {
if (sKey in mChangedEntities) {
bChangeDetected = true;
return false;
}
});
if (bChangeDetected) {
return false;
}
});
}
if (!mChangedEntities && !mEntityTypes) { // default
bChangeDetected = true;
}
}
if (bForceUpdate || bChangeDetected) {
this._abortAllPendingRequests();
this.resetData();
this.bNeedsUpdate = false;
this._fireRefresh({reason: ChangeReason.Refresh});
}
};
/**
* Check whether this Binding would provide new values and in case it changed, inform interested parties about this.
*
* @param {boolean}
* bForceUpdate
* @param {object} mChangedEntities
* @private
*/
AnalyticalBinding.prototype.checkUpdate = function(bForceUpdate, mChangedEntities) {
var bChangeDetected = false;
if (!bForceUpdate) {
if (this.bNeedsUpdate || !mChangedEntities) {
bChangeDetected = true;
} else {
jQuery.each(this.mServiceKey, function(i, aNodeKeys) {
jQuery.each(aNodeKeys, function(i, sKey) {
if (sKey in mChangedEntities) {
bChangeDetected = true;
return false;
}
});
if (bChangeDetected) {
return false;
}
});
}
}
if (bForceUpdate || bChangeDetected) {
this.bNeedsUpdate = false;
this._fireChange({reason: ChangeReason.Change});
}
};
/**
* Get a download URL with the specified format considering the
* sort/filter/custom parameters.
*
* The download URL also takes into account the selected dimensions and measures,
* depending on the given column definitions of the AnalyticalTable.
* This is based on the visible/inResult flags of the columns, as well as integrity dependencies,
* e.g. for mandatory Unit properties.
*
* @param {string} sFormat Value for the $format Parameter
* @return {string} URL which can be used for downloading
* @since 1.24
* @public
*/
AnalyticalBinding.prototype.getDownloadUrl = function(sFormat) {
// create a new request
var oAnalyticalQueryRequest = new odata4analytics.QueryResultRequest(this.oAnalyticalQueryResult);
oAnalyticalQueryRequest.setResourcePath(this._getResourcePath());
// add current list of dimensions
var aSelectedDimension = [];
var aSelectedMeasure = [];
for (var oDimensionName in this.oDimensionDetailsSet)
aSelectedDimension.push(oDimensionName);
oAnalyticalQueryRequest.setAggregationLevel(aSelectedDimension);
for (var oDimensionName2 in this.oDimensionDetailsSet) {
var oDimensionDetails = this.oDimensionDetailsSet[oDimensionName2];
var bIncludeText = (oDimensionDetails.textPropertyName != undefined);
oAnalyticalQueryRequest.includeDimensionKeyTextAttributes(oDimensionDetails.name, // bIncludeKey: No, always needed!
true, bIncludeText, oDimensionDetails.aAttributeName);
}
// add current list of measures
for (var sMeasureName in this.oMeasureDetailsSet)
aSelectedMeasure.push(sMeasureName);
oAnalyticalQueryRequest.setMeasures(aSelectedMeasure);
for ( var sMeasureName2 in this.oMeasureDetailsSet) {
var oMeasureDetails = this.oMeasureDetailsSet[sMeasureName2];
var bIncludeRawValue = (oMeasureDetails.rawValuePropertyName != undefined);
var bIncludeFormattedValue = (oMeasureDetails.formattedValuePropertyName != undefined);
var bIncludeUnitProperty = (oMeasureDetails.unitPropertyName != undefined);
oAnalyticalQueryRequest.includeMeasureRawFormattedValueUnit(oMeasureDetails.name, bIncludeRawValue,
bIncludeFormattedValue, bIncludeUnitProperty);
}
// add the sorters
var oSortExpression = oAnalyticalQueryRequest.getSortExpression();
oSortExpression.clear();
for (var i = 0; i < this.aSorter.length; i++) {
if (this.aSorter[i]) {
oSortExpression.addSorter(this.aSorter[i].sPath, this.aSorter[i].bDescending ? odata4analytics.SortOrder.Descending : odata4analytics.SortOrder.Ascending);
}
}
// add the filters
var oFilterExpression = oAnalyticalQueryRequest.getFilterExpression();
oFilterExpression.clear();
if (this.aApplicationFilter) {
oFilterExpression.addUI5FilterConditions(this.aApplicationFilter);
}
if (this.aControlFilter) {
oFilterExpression.addUI5FilterConditions(this.aControlFilter);
}
// determine the entityset path incl. the required params (sort, filter, ...)
var sPath = oAnalyticalQueryRequest.getURIToQueryResultEntitySet();
var aParam = this._getQueryODataRequestOptions(oAnalyticalQueryRequest);
if (!aParam) {
// parameters could not be determined correctly
return undefined;
}
// add the new $select param which is sorted like the Table
var aExportCols = [];
for (var k = 0, m = this.aAnalyticalInfo.length; k < m; k++) {
var oCol = this.aAnalyticalInfo[k];
if ((oCol.visible || oCol.inResult) && oCol.name !== "") {
aExportCols.push(oCol.name);
// add belonging currency column implicitly if present
if (this.oMeasureDetailsSet[oCol.name] != undefined
&& this.oMeasureDetailsSet[oCol.name].unitPropertyName != undefined) {
aExportCols.push(this.oMeasureDetailsSet[oCol.name].unitPropertyName);
}
}
}
// search and replace the $select
for (var j = 0, l = aParam.length; j < l; j++) {
if (/^\$select/i.test(aParam[j])) {
aParam[j] = "$select=" + aExportCols.join(",");
break;
}
}
// insert the format as first parameter
if (sFormat) {
aParam.splice(0, 0, "$format=" + encodeURIComponent(sFormat));
}
// create the request URL
if (sPath) {
return this.oModel._createRequestUrl(sPath, null, aParam);
}
};
//********************************
//*** Tracing execution
//********************************/
/** DISABLED FOR PRODUCTION
// * to enable, search using regex for "^// (.*\._trace_.*)", replace by "$1"
// * to disable, search using regex for "^(.*\._trace_.*)", replace by "// $1"
*
// AnalyticalBinding.prototype._trace_enter = function(groupid, scope, input_msg, _arguments, arg_components) {
if (!this._traceMsgCtr) {
this._traceMsgCtr = { level: 0, msg: [] };
}
this._traceMsgCtr.msg.push( { group: groupid, level: ++this._traceMsgCtr.level, scope: scope, msg: input_msg, details: _arguments, arg_components: arg_components, enter: true } );
};
// AnalyticalBinding.prototype._trace_leave = function (groupid, scope, output_msg, results, arg_components) {
if (!this._traceMsgCtr) {
throw "leave without enter";
}
this._traceMsgCtr.msg.push( { group: groupid, level: this._traceMsgCtr.level--, scope: scope, msg: output_msg, details: results, arg_components: arg_components, leave: true } );
};
// AnalyticalBinding.prototype._trace_message = function (groupid, input_msg, _arguments, arg_components) {
if (!this._traceMsgCtr) {
throw "message without enter";
}
this._traceMsgCtr.msg.push( { group: groupid, level: this._traceMsgCtr.level, msg: input_msg, details: _arguments, arg_components: arg_components } );
};
// AnalyticalBinding.prototype._trace_if_message = function (condition, groupid, message, details) {
if (condition) {
// this._trace_message(groupid, message, details);
}
};
// AnalyticalBinding.prototype._trace_debug_if = function (condition, message, details) {
// if (this._trace_debug_switch === undefined) {
// this._trace_debug_switch = true;
}
// if (this._trace_debug_switch && condition) {
debugger;
}
};
// AnalyticalBinding.prototype._trace_debug = function () {
debugger;
};
// AnalyticalBinding.prototype._trace_debug_switch = function (onoroff) {
// this._trace_debug_switch = onoroff;
};
// AnalyticalBinding.prototype._trace_dump = function (aGroupId) {
var fRenderMessage = function (line) {
var s = "[" + line.group + " ".slice(0,10 - line.group.length) + "]";
for (var i = 0; i < line.level; i++) {
s += " ";
}
if (line.enter) {
s += "->" + line.scope + (line.msg || line.arg_components ? ":\t" : "");
}
else if (line.leave) {
s += "<-" + line.scope + (line.msg || line.arg_components ? ":\t" : "");
} else {
s += " ";
}
if (line.msg) {
s += line.msg + ",";
}
if (line.details && line.arg_components) {
for (var j = 0; j < line.arg_components.length; j++) {
s += line.arg_components[j] + "=" + eval("line.details." + line.arg_components[j]) + (j < line.arg_components.length - 1 ? "," : "");
}
}
s += "\n";
return s;
};
var fRender = function (aMsg) {
var s = "";
for (var i = 0; i < aMsg.length; i++) {
if (!aGroupId || jQuery.inArray(aMsg[i].group, aGroupId) != -1) {
s += fRenderMessage(aMsg[i]);
}
}
return s;
};
if (!this._traceMsgCtr) {
return "";
}
return "\n" + fRender(this._traceMsgCtr.msg);
};
// AnalyticalBinding.prototype._trace_reset = function () {
delete this._traceMsgCtr;
};
**/
return AnalyticalBinding;
});
|
/**
* Created by cthed on 25/02/2016.
* this module will render a chart doughnut for json response fromm web
*/
/**
*
* @type {*[]} data
*/
var data = [
{
value: 61,
color: "#09355C",
label: "Label 1"
}, {
value: 11,
color: "#CBCBCB",
label: "Label 2"
}, {
value: 28,
color: "#B61B12",
label: "Label 3"
}];
/**
*
* @type {{segmentShowStroke: boolean, animateRotate: boolean, animateScale: boolean, percentageInnerCutout: number, tooltipTemplate: string}} options
*
*/
var options = {
segmentShowStroke: false,
animateRotate: true,
animateScale: false,
percentageInnerCutout: 50,
tooltipTemplate: "<%= value %>%"
}
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx).Doughnut(data, options);
// Note - tooltipTemplate is for the string that shows in the tooltip
// legendTemplate is if you want to generate an HTML legend for the chart and use somewhere else on the page
// e.g:
document.getElementById('js-legend').innerHTML = myChart.generateLegend();
|
import { ZoneId, ZonedDateTime, Duration, LocalTime } from 'js-joda';
import { Map as ImmutableMap } from 'immutable';
import { handle } from 'redux-pack';
import * as Actions from 'app/store/action/application';
import { LOAD as LOAD_CALENDARS } from 'app/store/action/calendars';
const INITIAL_STATE = new ImmutableMap({
touch_capable: false,
time_zone: ZoneId.systemDefault(),
last_activity: ZonedDateTime.now(),
is_idle: false,
time: ZonedDateTime.now(),
agenda_config: new ImmutableMap({
day_length: Duration.ofHours(11),
grid_step: Duration.ofMinutes(30),
start_of_agenda: LocalTime.of(8),
nav_header_height: '10vh'
})
});
const agenda_config_keys = [...INITIAL_STATE.get('agenda_config').keys()];
export default function (state = INITIAL_STATE, action = null) {
switch (action.type) {
case LOAD_CALENDARS: {
return handle(state, action, {
success(prev_state) {
return state.set('time_zone', ZoneId.of(action.payload.time_zone));
}
});
}
case Actions.SET_TOUCH_CAPABILITY: {
return state.set('touch_capable', action.payload);
}
case Actions.LAST_ACTIVITY: {
return state.set('last_activity', state.get('time'));
}
case Actions.SET_IDLE: {
return state.set('is_idle', true);
}
case Actions.UNSET_IDLE: {
return state.set('is_idle', false);
}
case Actions.SET_TIME: {
return state.set('time', action.payload);
}
case Actions.CONFIGURE_AGENDA: {
return agenda_config_keys
.filter(key => action.payload[key] !== undefined)
.reduce((s, key) => s.setIn(['agenda_config', key], action.payload[key]), state);
}
default:
return state;
}
}
|
'use strict';
var express = require('express');
var router = express.Router();
var models = require('../../models');
/* GET list pages */
router.get('/', function(req, res, next) {
models.Page.findAll({
include: [models.NavigationItem]
}).then(function(pages) {
res.render('admin/pages/index', {
title: 'Pages',
pages: pages
});
});
});
/* GET page */
router.get('/:id', function(req, res, next) {
models.Page.find(req.params.id).then(function(page) {
if (!page) {
return next();
}
res.render('admin/pages/view', {title: page.title, page:page});
});
});
/* POST create page */
router.post('/', function(req, res, next) {
var data = {
title: req.body.title,
url: req.body.url,
content: req.body.content || null,
enabled: !!req.body.enabled
};
models.Page.create(data).then(function(page) {
req.flash('success', 'The page has been created!');
res.redirect('/admin/pages/' + page.id + '/edit');
}).catch(function(err) {
req.session.formData = data;
req.flash('danger', err.errors[0].message);
res.redirect('/admin/pages/new');
});
});
/* GET new page */
router.get('/new', function(req, res, next) {
var data = req.session.formData;
delete req.session.formData;
res.render('admin/pages/edit', {
title: 'New Page',
page: models.Page.build(data)
});
});
/* GET edit page */
router.get('/:id/edit', function(req, res, next) {
models.Page.find({
where: { id: req.params.id }
}).then(function(page) {
if (!page) {
return next();
}
res.render('admin/pages/edit', {
title: 'Edit Page',
page: page
});
});
});
/* PUT update page */
router.put('/:id', function(req, res, next) {
models.Page.find(req.params.id).then(function(page) {
if (!page) {
return next();
}
page.updateAttributes({
title: req.body.title,
url: req.body.url,
content: req.body.content || null,
enabled: !!req.body.enabled
}).then(function() {
req.flash('success', 'The page has been saved!');
}).catch(function(err) {
req.flash('danger', err.errors[0].message);
}).finally(function() {
res.redirect('/admin/pages/' + req.params.id + '/edit');
});
});
});
/* GET confirm navigation item delete */
router.get('/:id/delete', function(req, res, next) {
models.Page.find(req.params.id).then(function(page) {
if (!page) {
return next();
}
res.render('admin/pages/delete', {title: 'Delete Page', page:page});
});
});
/* DELETE delete page */
router.delete('/:id', function(req, res, next) {
models.Page.find(req.params.id).then(function(page) {
if (!page) {
return next();
}
page.destroy().then(function(result) {
req.flash('success', 'The page has been deleted!');
res.redirect('/admin/pages');
});
});
});
module.exports = router;
|
import React, { PropTypes } from 'react';
export default class MapLayersPicker extends React.Component {
static propTypes = {
title: PropTypes.string,
layers: PropTypes.array.isRequired,
onLayerChange: PropTypes.func
};
static defaultProps = {
title: 'Map Layers'
};
constructor (props) {
super(props);
}
render () {
return (
<div className='map-layers-picker'>
<div className='map-layers-picker-section'>
<div className='map-layers-picker-header'>{ this.props.title }</div>
{ this.props.layers.map(layer => this.renderCheckbox(layer)) }
</div>
</div>
);
}
handleChange (key, checked) {
console.log({ key, checked });
if (this.props.onLayerChange) {
this.props.onLayerChange(key, checked);
}
}
renderCheckbox (config) {
let {
key,
name,
icon,
iconSize,
iconType,
checked
} = config;
iconType = iconType || '';
return (
<div className='map-layers-picker-checkbox' key={ key }>
{ icon ?
<svg
width={ iconSize[0] }
height={ iconSize[1] }
className={ `${ iconType } ${ key } ${ checked ? '' : 'off' }` }
onClick={ e => this.handleChange(key, !checked) }
>
<use xlinkHref={ '#' + icon } />
</svg>
: null }
<input
className={ icon ? 'hidden' : '' }
type='checkbox'
id={ key }
onChange={ e => this.handleChange(key, e.target.checked) }
checked={ checked }
/>
<label htmlFor={ key } className={ iconType } dangerouslySetInnerHTML={{ __html: decodeURIComponent(name) }}></label>
{ this.props.children }
</div>
);
}
}
|
'use strict';
module.exports = cacheMkdirP
var path = require('path')
function cacheMkdirP(mkdirP) {
var cache = new MkdirPCache(mkdirP)
return cache.mkdirP.bind(cache)
}
function MkdirPCache(mkdirP) {
this._mkdirP = mkdirP
this._dirMarks = {}
}
MkdirPCache.prototype.mkdirP = function (dir, opts, cb) {
if (!cb) {
cb = opts
opts = {}
}
dir = path.resolve(dir)
if (this._dirMarks.hasOwnProperty(dir))
return process.nextTick(cb.bind(null, null))
var self = this
this._mkdirP(dir, opts, function (err) {
if (err) return cb(err)
self._dirMarks[dir] = true
return cb(null)
})
}
|
var Mediador = require("../mediador")
var YourClass = function () {}
YourClass.prototype.on = Mediador.prototype.on
YourClass.prototype.off = Mediador.prototype.off
YourClass.prototype.emit = Mediador.prototype.emit
var yourInstance = new YourClass()
var listener = function (you) {
console.log(you + " already firing events!")
}
yourInstance.on("event", listener)
yourInstance.emit("event", ["Me"])
yourInstance.off("event", listener)
|
'use strict'
const yo = require('yo-yo')
const menu = (currentCat, allCats, setCat, clearCat) => yo `
<ul>
${allCats.map((cat) => {
const onClick = (e) => {
e.preventDefault()
e.stopPropagation()
if (currentCat === cat) clearCat()
else setCat(cat)
}
return yo `
<li class="${currentCat === cat ? 'active' : ''}">
<a href="#" role="button" aria-haspopup="true"
onclick=${onClick}>${cat}</a>
</li>`
})}
<ul>`
const noop = () => {}
let dom = menu(null, [], noop, noop)
document.querySelector('#menu').appendChild(dom)
const render = (currentCat, allCats, setCat, clearCat) => {
const newDom = menu(currentCat, allCats, setCat, clearCat)
yo.update(dom, newDom)
}
module.exports = render
|
// By default we create a single styles file, containing both vendor and app styles.
// If you wanted to, you can easily break them into 2 by adding vendor entry point to webpack config and removing the
// import here.
import './vendor';
// Include main styles from scss
import './main.scss';
|
// ignore most things
var IgnoreFile = require("../")
, path = require('path')
// set the ignores just for this test
var c = require("./common.js")
c.ignores({ ".ignore": ["*", "a", "c", "!a/b/c/.abc", "!/c/b/a/cba"] })
// the only files we expect to see
var expected =
[ "/a/b/c/.abc"
, "/a"
, "/a/b"
, "/a/b/c"
, "/c/b/a/cba"
, "/c"
, "/c/b"
, "/c/b/a"
].map(path.normalize)
require("tap").test("basic ignore rules", function (t) {
t.pass("start")
IgnoreFile({ path: __dirname + "/fixtures"
, ignoreFiles: [".ignore"] })
.on("child", function (e) {
var p = e.path.substr(e.root.path.length)
var i = expected.indexOf(p)
if (i === -1) {
t.fail("unexpected file found", {f: p})
} else {
t.pass(p)
expected.splice(i, 1)
}
})
.on("close", function () {
t.notOk(expected.length, "all expected files should be seen")
t.end()
})
})
|
/*global __DEV__ */
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import App from 'containers//App';
import configureStore from './store/configureStore';
import DevTools from 'containers//DevTools';
require('normalize.css');
require('styles//App.sass');
let initialState;
if(window.hasOwnProperty('__DATA__')) {
initialState = window.__DATA__;
}
const store = configureStore(initialState);
const rootElement = document.getElementById('app');
if(__DEV__) {
render(
<Provider store={store} key="provider">
<div>
<App />
<DevTools />
</div>
</Provider>,
rootElement
);
} else {
render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);
}
|
import request from 'request';
import xml2js from 'xml2js';
import util from 'util';
import Promise from 'promise';
export default function boardGames(app) {
app.get('/api/board-games?', function(req, res) {
try {
let minDate = new Date(2015, 0, 1);
let maxDate = new Date(2018, 0, 1);
if(!req.query.username) {
res.status(400).send('Username query parameter required.')
}
// if(req.query.mindate) {
// minDate = req.query.mindate;
// } else {
// minDate.setMonth(0);
// minDate.setDate(1);
// }
fetchBoardGameStats(req.query.username, minDate, maxDate)
.then(function(result) {
res.status(200).send(result);
});
} catch(err) {
res.status(500).send(err);
}
});
}
function fetchBoardGameStats(username, minDate, maxDate) {
return new Promise(function(resolve, reject) {
new Promise.all(
[ fetchPlays(username, minDate, maxDate),
fetchCollection(username, minDate, maxDate) ]
).done(function(results){
let allPlays = calculateAllPlays(results[0]);
let allCollection = results[1];
resolve({
'10x10': get10x10(allPlays),
'100x1': get100x1(allPlays),
'wallOfShame': getWallOfShame(allPlays, allCollection)
});
});
});
}
function getWallOfShame(plays, collection) {
let shame = [];
if(!plays || !collection) { return []; }
for(var game in collection) {
let hasPlayed = false;
for(var i = 0; i < plays.length; i++) {
if(plays[i].name === game) {
hasPlayed = true;
break;
}
}
if(!hasPlayed) {
shame.push({game: game, image: collection[game]});
}
}
return {
number: shame.length,
games: shame
};
}
function get10x10(sortedPlays) {
let length = 10;
if(!sortedPlays || !(sortedPlays instanceof Array)) { return []; };
if(sortedPlays.length < length) {
length = sortedPlays.length;
}
return {
number: length,
plays: sortedPlays.slice(0, 10)
};
}
function get100x1(sortedPlays) {
let length = 100;
if(!sortedPlays) { return []; };
if(sortedPlays.length < length) {
length = sortedPlays.length;
}
return {
number: length,
plays: sortedPlays.slice(0, 100)
};
}
function playSort(play1, play2) {
if(play1.plays < play2.plays) { return 1; }
if(play1.plays > play2.plays) { return -1; }
return 0;
}
function calculateAllPlays(plays) {
let allPlays = {};
if(!plays) {
return {};
}
for(var i = 0; i < plays.length; i++) {
let gameName = plays[i].item[0].$.name;
if(allPlays[gameName] === undefined || allPlays[gameName] === NaN) {
allPlays[gameName] = 1;
} else {
allPlays[gameName] += 1;
}
}
let playsArray = [];
for(var name in allPlays) {
playsArray.push({name: name, plays: allPlays[name]})
}
return playsArray.sort(playSort);
}
function fetchPlays(username, minDate, maxDate) {
return new Promise(function(resolve, reject) {
let allPlays = [];
fetchPlaysByPage(username, minDate, maxDate, 1)
.then(function (result) {
allPlays = result.plays.play;
let totalPlays = result.plays.$.total;
if(totalPlays > 100) {
let numPages = Math.ceil(totalPlays / 100);
let promiseCalls = [];
for(var i = 2; i <= numPages; i++) {
promiseCalls.push(fetchPlaysByPage(username, minDate, maxDate, i));
}
new Promise.all(promiseCalls).done(function(results) {
for(var j = 0; j < results.length; j++) {
for(var k = 0; k < results[j].plays.play.length; k++) {
allPlays.push(results[j].plays.play[k]);
}
}
resolve(allPlays);
});
} else {
resolve(allPlays);
}
});
});
}
function fetchPlaysByPage(username, minDate, maxDate, page) {
return new Promise(function(resolve, reject) {
let minDateString = minDate.toISOString().substring(0, 10);
let maxDateString = '';
if(maxDate) {
maxDateString = maxDate.toISOString().substring(0, 10);
}
request.get({
url: `https://boardgamegeek.com/xmlapi2/plays?username=${username}&page=${page}&subtype=boardgame`
}, function(err, http, res) {
xml2js.Parser().parseString(res, function(error, result) {
resolve(result);
});
});
});
}
function fetchCollection(username) {
return new Promise(function(resolve, reject) {
request.get({
url: `https://boardgamegeek.com/xmlapi2/collection?username=${username}&subtype=boardgame`
}, function(err, http, res) {
if(http.statusCode === 202) {
resolve(fetchCollection(username));
} else {
xml2js.Parser().parseString(res, function(error, result) {
resolve(formatCollection(result.items.item));
});
}
});
});
}
function formatCollection(collection) {
let fullCollection = {};
if(collection) {
for(var i = 0; i < collection.length; i++) {
if(collection[i].status[0].$.own === '1') {
let name = collection[i].name[0]._;
let image = collection[i].image[0];
fullCollection[name] = image;
}
}
}
return fullCollection;
}
|
/*
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides base class sap.ui.core.Component for all components
sap.ui.define(['jquery.sap.global', '../base/ManagedObject', './Component', './library', './UIComponentMetadata', './mvc/Controller', './mvc/View'],
function(jQuery, ManagedObject, Component, library, UIComponentMetadata, Controller, View) {
"use strict";
// shortcut for enum(s)
var ViewType = library.mvc.ViewType;
/**
* Base Class for UIComponent.
*
* If you are extending an UIComponent make sure you read the {@link #.extend} documentation since the metadata is special.
*
* @class
* Creates and initializes a new UIComponent with the given <code>sId</code> and
* settings.
*
* The set of allowed entries in the <code>mSettings</code> object depends on
* the concrete subclass and is described there. See {@link sap.ui.core.Component}
* for a general description of this argument.
*
* @param {string}
* [sId] Optional ID for the new control; generated automatically if
* no non-empty ID is given Note: this can be omitted, no matter
* whether <code>mSettings</code> will be given or not!
* @param {object}
* [mSettings] optional map/JSON-object with initial settings for the
* new component instance
* @public
*
* @extends sap.ui.core.Component
* @abstract
* @author SAP SE
* @version 1.38.4
* @alias sap.ui.core.UIComponent
* @since 1.9.2
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var UIComponent = Component.extend("sap.ui.core.UIComponent", /** @lends sap.ui.core.UIComponent.prototype */
{
constructor : function(sId, mSettings) {
try {
Component.apply(this, arguments);
} catch (e) {
this._destroyCreatedInstances();
throw e;
}
},
metadata : {
"abstract": true,
rootView : null, // the rootView to open (view name as string or view configuration object)
publicMethods: [ "render" ],
aggregations: {
/**
* The root control of the UIComponent.
*
* The root control should be created inside the function {@link sap.ui.core.UIComponent#createContent}.
*/
"rootControl": { type: "sap.ui.core.Control", multiple: false, visibility: "hidden" }
},
routing: {
}
//autoDestroy: false // TODO: destroy component when view should be destroyed (not implemented yet!)
}
}, /* Metadata constructor */ UIComponentMetadata);
/**
* Creates a new subclass of class <code>sap.ui.core.UIComponent</code> with name
* <code>sClassName</code> and enriches it with the information contained in <code>oClassInfo</code>.
* <code>oClassInfo</code> might contain the same kind of information as described in
* {@link sap.ui.core.Element.html#.extend}.
*
* @alias {sap.ui.core.UIComponent.extend}
* @public
* @param {string} sClassName Name of the class to be created
*
* @param {object} [oClassInfo] Object literal with information about the class
*
* @param {object} [oClassInfo.metadata] See {@link sap.ui.core.Element.html#.extend} for the values allowed in every extend.
*
* @param {object} [oClassInfo.metadata.routing]
* @since 1.16
* An object containing he routing-relevant configurations, routes, targets, config
* <b>Example for a config:</b><br/>
* <pre>
* <code>
* metadata : {
* "routing": {
* "routes": {
* "welcome": {
* // If the url has no hash e.g.: index.html or index.html# , this route will be matched.
* "pattern": "",
* // Displays the target called "welcome" specified in metadata.routing.targets.welcome.
* "target": "welcome"
* }
* "product": {
* "pattern": "Product/{id}",
* "target": "product"
* }
* }
* // Default values for targets
* "config": {
* // For a detailed documentation of these parameters have a look at the sap.ui.core.routing.Targets documentation
* "viewType": "XML",
* "controlId": "App",
* "controlAggregation": "pages",
* "viewNamespace": "myApplication.namespace",
* // If you are using the mobile library, you have to use a sap.m.Router, to get support for
* // the controls sap.m.App, sap.m.SplitApp, sap.m.NavContainer and sap.m.SplitContainer.
* "routerClass": "sap.m.routing.Router"
* // What happens if no route matches the hash?
* "bypassed": {
* // the not found target gets displayed
* "target": "notFound"
* }
* }
* "targets": {
* "welcome": {
* // Referenced by the route "welcome"
* "viewName": "Welcome",
* "viewLevel": 0
* },
* "product": {
* // Referenced by the route "Product"
* "viewName": "Product",
* "viewLevel": 1
* }
* "notFound": {
* // Referenced by the bypassed section of the config
* "viewName": "NotFound"
* }
* }
* }
* }
* </code>
* </pre>
*
* Later you can retrieve the Router with {@link #getRouter} to register on callbacks when routes have matched. You can also retrieve Targets with {@link #getTargets} to display views without changing the hash.
*
* @param {object} [oClassInfo.metadata.routing.routes]
* @since 1.16
* An object containing the routes that should be added to the Router. See {@link sap.ui.core.routing.Route} for the allowed properties.
*
* @param {object} [oClassInfo.metadata.routing.targets]
* @since 1.28.1
* An object containing the targets that will be available for the router and the Targets instance.
* Read {@link sap.ui.core.routing.Targets} for the allowed values.
*
* @param {object} [oClassInfo.metadata.routing.config]
* @since 1.16
* An object containing default values used for routes and targets.
* See {@link sap.ui.core.routing.Router#constructor} and {@link sap.ui.core.routing.Targets} for more documentation.
*
* @param {string|function} [oClassInfo.metadata.routing.config.routerClass] Default: "sap.ui.core.routing.Router".
* @since 1.20
* The namespace of the router that is used in the component.
* If you are using an own router extension, it has to be required before the constructor of the component is invoked.
* If you use <code>sap.m.routing.Router</code> the component will automatically create a {@link sap.m.routing.Targets} instance.
* If you pass a function, it has to be a constructor function extending a router.
*
* @param {string|function} [oClassInfo.metadata.routing.config.targetsClass]
* @since 1.28.1
* default: "sap.ui.core.routing.Targets".
* The namespace of the targets that are used in the component.
* If you are using an own Targets extension, it has to be required before the constructor of the component is invoked.
* If you define routes in your routing section, this parameter will be ignored and the Targets instance of the router will be taken see {@lint #sap.ui.core.routing.Router#getTargets}.
*
*
* @param {string} [oClassInfo.metadata.routing.config.rootView]
* By default the rootView will be set to the ID of the view returned by the {@link #getRootView} function.
* You should not set this parameter if you create a view with the UIComponent.
*
* @param {function} [FNMetaImpl} Constructor function for the metadata object. If not given, it defaults to {@link sap.ui.core.ElementMetadata}.
*/
/**
* Callback handler which will be executed once a new Component instance is
* initialized.
* <p>
* Example usage:
* <pre>
* sap.ui.core.UIComponent._fnOnInstanceCreated = function(oComponent) {
* // do some logic with the Component
* }
* </pre>
* <p>
* <b>ATTENTION:</b> This hook must only be used by Fiori 2.0 adapter.
*
* @sap-restricted sap.ushell
* @private
* @since 1.37.0
*/
UIComponent._fnOnInstanceInitialized = null;
/**
* Initializes the Component instance after creation.
*
* Applications must not call this hook method directly, it is called by the
* framework while the constructor of a Component is executed.
*
* Subclasses of Component should override this hook to implement any necessary
* initialization. <b>When overriding this function make sure to invoke the
* init function of the UIComponent as well!</b>
*
* @protected
*/
UIComponent.prototype.init = function() {
var that = this;
var oPreprocessors = {};
// when auto prefixing is enabled we add the prefix
if (this.getAutoPrefixId()) {
oPreprocessors.id = function(sId) {
return that.createId(sId);
};
}
// create the routing
// extend the metadata config, so that the metadata object cannot be modified afterwards
var oRoutingManifestEntry = this._getManifestEntry("/sap.ui5/routing", true) || {},
oRoutingConfig = oRoutingManifestEntry.config || {},
vRoutes = oRoutingManifestEntry.routes;
// create the router for the component instance
if (vRoutes) {
var Router = sap.ui.requireSync("sap/ui/core/routing/Router");
var fnRouterConstructor = getConstructorFunctionFor(oRoutingConfig.routerClass || Router);
this._oRouter = new fnRouterConstructor(vRoutes, oRoutingConfig, this, oRoutingManifestEntry.targets);
this._oTargets = this._oRouter.getTargets();
this._oViews = this._oRouter.getViews();
} else if (oRoutingManifestEntry.targets) {
var Targets = sap.ui.requireSync("sap/ui/core/routing/Targets");
var Views = sap.ui.requireSync("sap/ui/core/routing/Views");
this._oViews = new Views({
component: this
});
var fnTargetsConstructor = getConstructorFunctionFor(oRoutingConfig.targetsClass || Targets);
this._oTargets = new fnTargetsConstructor({
targets: oRoutingManifestEntry.targets,
config: oRoutingConfig,
views: this._oViews
});
}
// create the content
this.runAsOwner(function() {
ManagedObject.runWithPreprocessors(function() {
that.setAggregation("rootControl", that.createContent());
}, oPreprocessors);
});
// only for root "views" we automatically define the target parent
var oRootControl = this.getAggregation("rootControl");
if (oRootControl instanceof View) {
if (oRoutingConfig.targetParent === undefined) {
oRoutingConfig.targetParent = oRootControl.getId();
}
if (this._oTargets) {
this._oTargets._setRootViewId(oRootControl.getId());
}
}
// notify Component initialization callback handler
if (typeof UIComponent._fnOnInstanceInitialized === "function") {
UIComponent._fnOnInstanceInitialized(this);
}
};
function getConstructorFunctionFor (vRoutingObjectConstructor) {
var fnConstructor;
if (typeof vRoutingObjectConstructor === "string") {
fnConstructor = jQuery.sap.getObject(vRoutingObjectConstructor);
if (!fnConstructor) {
jQuery.sap.log.error("The specified class for router or targets '" + vRoutingObjectConstructor + "' is undefined.", this);
}
} else {
fnConstructor = vRoutingObjectConstructor;
}
return fnConstructor;
}
/*
* Destruction of the UIComponent
*/
UIComponent.prototype.destroy = function() {
// destroy the router
this._destroyCreatedInstances();
// make sure that the component is destroyed properly
Component.prototype.destroy.apply(this, arguments);
};
UIComponent.prototype._destroyCreatedInstances = function () {
// destroy the router
if (this._oRouter) {
this._oRouter.destroy();
delete this._oRouter;
}
if (this._oTargets) {
this._oTargets.destroy();
this._oTargets = null;
}
if (this._oViews) {
this._oViews.destroy();
this._oViews = null;
}
};
/**
* Returns the reference to the router instance. The passed controller or view
* has to be created in the context of a UIComponent to return the router
* instance. Otherwise this function will return undefined.
* You may define the routerClass property in the config section of the routing to make the Component create your router extension.
* Example:
* routing: {
* config: {
* routerClass : myAppNamespace.MyRouterClass
* ...
* }
* ...
* @param {sap.ui.core.mvc.View|sap.ui.core.mvc.Controller} oControllerOrView either a view or controller
* @return {sap.ui.core.routing.Router} the router instance
* @since 1.16.1
* @public
*/
UIComponent.getRouterFor = function(oControllerOrView) {
var oView = oControllerOrView;
if (oView instanceof Controller) {
oView = oView.getView();
}
if (oView instanceof View) {
var oComponent = Component.getOwnerComponentFor(oView);
if (oComponent) {
return oComponent.getRouter();
} else {
return undefined;
}
}
};
/**
* Returns the reference to the router instance which has been created by
* the UIComponent once the routes in the routing metadata has been defined.
* @since 1.16.1
* @return {sap.ui.core.routing.Router} the router instance
* @public
*/
UIComponent.prototype.getRouter = function() {
return this._oRouter;
};
/**
* Returns the reference to the Targets instance which has been created by
* the UIComponent once the targets in the routing metadata has been defined.
* If routes have been defined, it will be the Targets instance created and used by the router.
* @since 1.28
* @return {sap.ui.core.routing.Targets} the targets instance
* @public
*/
UIComponent.prototype.getTargets = function() {
return this._oTargets;
};
/**
* A method to be implemented by UIComponents, returning the flag whether to prefix
* the IDs of controls automatically or not if the controls are created inside
* the {@link sap.ui.core.UIComponent#createContent} function. By default this
* feature is not activated.
*
* You can overwrite this function and return <code>true</code> to activate the automatic
* prefixing. In addition the default behavior can be configured in the manifest
* by specifying the entry <code>sap.ui5/autoPrefixId</code>.
*
* @since 1.15.1
* @return {boolean} true, if the Controls IDs should be prefixed automatically
* @protected
*/
UIComponent.prototype.getAutoPrefixId = function() {
return !!this.getManifestObject().getEntry("/sap.ui5/autoPrefixId");
};
/**
* Returns an element by its ID in the context of the Component
*
* @param {string} sId
* @return {sap.ui.core.Element} Element by its id
* @public
*/
UIComponent.prototype.byId = function(sId) {
return sap.ui.getCore().byId(this.createId(sId));
};
/**
* Creates an ID for an element prefixed with the Component ID
*
* @param {string} sId
* @return {string} prefixed id
* @public
*/
UIComponent.prototype.createId = function(sId) {
if (!this.isPrefixedId(sId)) {
// components have 3 dashes as separator, views 2 and controls/elements 1
sId = this.getId() + "---" + sId;
}
return sId;
};
/**
* Checks whether the given ID is already prefixed with this view's ID
*
* @param {string} potentially prefixed id
* @return whether the ID is already prefixed
*/
UIComponent.prototype.isPrefixedId = function(sId) {
return (sId && sId.indexOf(this.getId() + "---") === 0);
};
/**
* The method to create the content (UI Control Tree) of the Component.
* This method has to be overwritten in the implementation of the component
* if the root view is not declared in the component metadata.
*
* @public
*/
UIComponent.prototype.createContent = function() {
var oRootView = this._getManifestEntry("/sap.ui5/rootView", true);
if (oRootView && typeof oRootView === "string") {
// This is a duplication of the logic in UIComponentMetadata#_convertLegacyMetadata
// to convert the string into a configuration object for the view factory in
// case of the manifest first approach.
// !This should be kept in sync with the UIComponentMetadata functionality!
return sap.ui.view({
viewName: oRootView,
type: ViewType.XML
});
} else if (oRootView && typeof oRootView === "object") {
// make sure to prefix the ID of the rootView
if (oRootView.id) {
oRootView.id = this.createId(oRootView.id);
}
return sap.ui.view(oRootView);
} else if (oRootView) {
throw new Error("Configuration option 'rootView' of component '" + this.getMetadata().getName() + "' is invalid! 'rootView' must be type of string or object!");
}
return null;
};
/**
* Renders the the root control of the UIComponent.
*
* @param {sap.ui.core.RenderManager} oRenderManager a RenderManager instance
* @public
*/
UIComponent.prototype.render = function(oRenderManager) {
var oControl = this.getAggregation("rootControl");
if (oControl && oRenderManager) {
oRenderManager.renderControl(oControl);
}
};
/**
* Returns the reference to the UIArea of the container.
*
* @return {sap.ui.core.UIArea} reference to the UIArea of the container
* @public
*/
UIComponent.prototype.getUIArea = function() {
return (this.oContainer ? this.oContainer.getUIArea() : null);
};
/**
* @see sap.ui.base.EventProvider#getEventingParent
* @protected
*/
UIComponent.prototype.getEventingParent = function() {
return this.getUIArea();
};
/**
* Sets the reference to the ComponentContainer - later required for the
* determination of the UIArea for the UIComponent.
*
* @param {sap.ui.core.ComponentContainer} oContainer reference to a ComponentContainer
* @return {sap.ui.core.UIComponent} reference to this instance to allow method chaining
* @public
*/
UIComponent.prototype.setContainer = function(oContainer) {
this.oContainer = oContainer;
return this;
};
/**
* Function is called when the rendering of the ComponentContainer is started.
*
* Applications must not call this hook method directly, it is called from ComponentContainer.
*
* Subclasses of UIComponent override this hook to implement any necessary actions before the rendering.
*
* @protected
*/
UIComponent.prototype.onBeforeRendering = function() {};
/**
* Function is called when the rendering of the ComponentContainer is completed.
*
* Applications must not call this hook method directly, it is called from ComponentContainer.
*
* Subclasses of UIComponent override this hook to implement any necessary actions after the rendering.
*
* @protected
*/
UIComponent.prototype.onAfterRendering = function() {};
return UIComponent;
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:60fe92ac860ec76faf13530db2255b366e1981dc01a248f77723c030070fdfd4
size 28903
|
MainTablet.widgets = {
varNavItems: ["wm.Variable", {"isList":true,"json":"[{\"dataValue\":\"CreateShipmentDD\"},{\"dataValue\":\"GetLabelDD\"},{\"dataValue\":\"DeleteShipmentDD\"}]","type":"StringData"}, {}],
navCallInformation: ["wm.NavigationCall", {"operation":"gotoPageContainerPage"}, {}, {
input: ["wm.ServiceInput", {"type":"gotoPageContainerPageInputs"}, {}, {
binding: ["wm.Binding", {}, {}, {
wire: ["wm.Wire", {"expression":"\"Information\"","targetProperty":"pageName"}, {}],
wire1: ["wm.Wire", {"expression":undefined,"source":"pagContainer","targetProperty":"pageContainer"}, {}]
}]
}]
}],
varResultByNavItems: ["wm.Variable", {"dataSet":"","type":"StringData"}, {}, {
binding: ["wm.Binding", {}, {}, {
wire: ["wm.Wire", {"expression":undefined,"source":"lstNavigation.selectedItem.dataValue","targetProperty":"dataSet.dataValue"}, {}]
}]
}],
navCallCreateShipmentDD: ["wm.NavigationCall", {"operation":"gotoPageContainerPage"}, {}, {
input: ["wm.ServiceInput", {"type":"gotoPageContainerPageInputs"}, {}, {
binding: ["wm.Binding", {}, {}, {
wire: ["wm.Wire", {"expression":"\"CreateShipmentDD\"","targetProperty":"pageName"}, {}],
wire1: ["wm.Wire", {"expression":undefined,"source":"pagContainer","targetProperty":"pageContainer"}, {}]
}]
}]
}],
navCallGetShipmentDD: ["wm.NavigationCall", {"operation":"gotoPageContainerPage"}, {}, {
input: ["wm.ServiceInput", {"type":"gotoPageContainerPageInputs"}, {}, {
binding: ["wm.Binding", {}, {}, {
wire: ["wm.Wire", {"expression":"\"GetLabelDD\"","targetProperty":"pageName"}, {}],
wire1: ["wm.Wire", {"expression":undefined,"source":"pagContainer","targetProperty":"pageContainer"}, {}]
}]
}]
}],
navCallDeleteShipmentDD: ["wm.NavigationCall", {"operation":"gotoPageContainerPage"}, {}, {
input: ["wm.ServiceInput", {"type":"gotoPageContainerPageInputs"}, {}, {
binding: ["wm.Binding", {}, {}, {
wire1: ["wm.Wire", {"expression":undefined,"source":"pagContainer","targetProperty":"pageContainer"}, {}],
wire: ["wm.Wire", {"expression":"\"DeleteShipmentDD\"","targetProperty":"pageName"}, {}]
}]
}]
}],
lbxMain: ["wm.Layout", {"deviceSizes":null,"enableTouchHeight":true,"horizontalAlign":"left","styles":{},"verticalAlign":"top"}, {}, {
pnlDesktop: ["wm.Panel", {"deviceType":["tablet"],"height":"100%","horizontalAlign":"left","layoutKind":"left-to-right","verticalAlign":"top","width":"100%"}, {}, {
pnlLeft: ["wm.Panel", {"deviceSizes":null,"deviceType":["tablet"],"height":"100%","horizontalAlign":"left","verticalAlign":"top","width":"270px"}, {}, {
lstNavigation: ["wm.List", {"_classes":{"domNode":["GridListStyle","MobileListStyle"]},"border":"1","columns":[
{"show":true,"field":"dataValue","title":"Geschäftskundenversand API","width":"100%","align":"left","formatFunc":"","mobileColumn":false},
{"show":false,"field":"PHONE COLUMN","title":"-","width":"100%","align":"left","expression":"\"<div class='MobileRowTitle'>\" +\n\"Geschäftskundenversand API: \" + ${dataValue} +\n\"</div>\"\n\n","mobileColumn":true},
{"show":true,"controller":"rightarrow","width":"20px","title":"-","field":"_rightArrow","mobileColumn":true}
],"deviceSizes":null,"deviceType":["tablet"],"height":"100%","isNavigationMenu":false,"minDesktopHeight":60,"primaryKeyFields":["dataValue"],"rightNavArrow":true,"scrollToSelection":true,"styleAsGrid":false,"styles":{}}, {"onSelect":"lstNavigationSelect"}, {
binding: ["wm.Binding", {}, {}, {
wire: ["wm.Wire", {"expression":undefined,"source":"varNavItems","targetProperty":"dataSet"}, {}]
}]
}]
}],
pnlDetail: ["wm.Panel", {"deviceType":["tablet"],"height":"100%","horizontalAlign":"left","verticalAlign":"top","width":"100%"}, {}, {
pnlDetailTop: ["wm.Panel", {"deviceType":["tablet"],"height":"35px","horizontalAlign":"left","layoutKind":"left-to-right","verticalAlign":"top","width":"100%"}, {}, {
edtShipmentNr: ["wm.Text", {"caption":"ShipmentNr","dataValue":"","deviceType":["tablet"],"displayValue":"","emptyValue":"emptyString","height":"100%","helpText":undefined,"placeHolder":"Number for DD-Services","width":"343px"}, {}]
}],
pagContainer: ["wm.PageContainer", {"deferLoad":true,"deviceType":["tablet"],"styles":{}}, {}],
pnlDetailButtom: ["wm.Panel", {"deviceType":["tablet"],"height":"40px","horizontalAlign":"center","layoutKind":"left-to-right","verticalAlign":"top","width":"100%"}, {}, {
btnInfo: ["wm.Button", {"caption":"About","deviceType":["tablet"],"height":"100%","margin":"4"}, {"onclick":"navCallInformation","onclick1":"btnInfoClick1"}]
}]
}]
}]
}]
}
|
function couchapp_load(scripts) {
for (var i=0; i < scripts.length; i++) {
document.write('<script src="'+scripts[i]+'"><\/script>')
};
};
couchapp_load([
'/_utils/script/sha1.js',
'/_utils/script/json2.js',
'/_utils/script/jquery.js',
'/_utils/script/jquery.couch.js',
'/_utils/script/jquery.form.js',
'/_utils/script/jquery.dialog.js',
'vendor/couchapp/jquery.couch.app.js',
'vendor/couchapp/jquery.couch.app.util.js',
'vendor/couchapp/jquery.mustache.js',
'vendor/couchapp/jquery.evently.js',
'vendor/couchapp/jquery.couchLogin.js',
'vendor/couchapp/jquery.couchProfile.js',
'vendor/couchapp/jquery.class.js',
'vendor/couchapp/md5.js',
]);
|
'use strict';
/**
* Colstudent Schema
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ColstudentSchema = new Schema({
LastName: {type: String, required: true} ,
FirstName: {type: String, required: true} ,
MAT251CalcI: { type: String},
MAT252CalcII: { type: String},
MAT320DiscreteMath: { type: String},
CPS210CompSciI: { type: String},
CPS310CompSciII: { type: String},
CPS315CompSciIII: { type: String},
CPS352OOP: { type: String},
CPS330AssemblyArch: { type: String},
CPS353SoftEng: { type: String},
CPS415DiscContAlgorithms: { type: String},
CPS340OpSys: { type: String},
CPS425LangProcessing: { type: String},
CPS493Elect1: { type: String},
CPS493Projects: { type: String},
EGC230DigLogic: { type: String},
EGC208DigLogicLab: { type: String},
SCIENCEI: { type: String},
SCIENCEII: { type: String},
SCIENCEICOMMENT: { type: String},
SCIENCEIICOMMENT: { type: String},
EGC208DigLogicLabCOMMENT: { type: String},
EGC2230DigLogicCOMMENT: { type: String},
CPS493ProjectsCOMMENT: { type: String},
CPS493Elect1COMMENT: { type: String},
CPS425LangProcessingCOMMENT: { type: String},
CPS340OpSysCOMMENT:{ type: String},
CPS415DiscContAlgorithmsCOMMENT: { type: String},
CPS353SoftEngCOMMENT: { type: String},
CPS330AssemblyArchCOMMENT: { type: String},
CPS352OOPCOMMENT: { type: String},
CPS315CompSciIIICOMMENT: { type: String},
CPS310CompSciIICOMMENT: { type: String},
CPS210CompSciICOMMENT: { type: String},
MAT320DiscreteMathCOMMENT:{ type: String},
MAT252CalcIICOMMENT:{ type: String},
MAT251CalcICOMMENT:{ type: String}
});
/* Returns the student's full name with last name first
* followed by first name
* For instance, "Smith, John */
/**schema.virtual('wholeName').get(function() {
return this.LastName +','+''+ this.FirstName;
});
*/
mongoose.model('Colstudent', ColstudentSchema);
|
module.exports = {
environments: [
{
extension: 'js',
testNameSuffix: '.test',
testDir: 'src',
sourceDir: 'src',
testRunnerCommand: { command: 'echo "I test thee"' },
},
],
};
|
$(document).ready(function(){
//表单数据示例
var formData = [
{
recieve_id : '20180001',
recieve_list : [
{
recieve_name : '西门子冰箱',
recieve_model : 'XMZ-21'
},
{
recieve_name : '海尔冰箱',
recieve_model : 'HR-SD1'
}
]
},
{
recieve_id : '20180002',
recieve_list : [
{
recieve_name : '飞利浦投影仪',
recieve_model : 'potu0239-21'
},
{
recieve_name : '夏普投影仪',
recieve_model : 'SP3asF'
}
]
}
];
var initData = [
{
recieve_location : 'D2 202',
recieve_id : '20180001',
recieve_name : '西门子冰箱',
recieve_model : 'XMZ-21',
recieve_num : '23',
recieve_ps : '这是备注内容',
reciever : '小D'
}
];
function getOptionsFromData(data,key) {
var selectData = [];
for(i in data) {
selectData.push({
value : data[i][key],
text : data[i][key]
});
}
return selectData;
}
function fillFormData(data, id){
var recieve_id_data = window.commonTools.getSubArrayByObjValue(data, 'recieve_id', $('#recieve_id_' + id).val())[0];
$('#recieve_name_' + id).empty();
window.window.commonTools.addSelectOptions($('#recieve_name_' + id), getOptionsFromData(recieve_id_data.recieve_list,'recieve_name'));
fillNameData(data, id);
$('#recieve_name_' + id).change(function(){
fillNameData(data, id);
});
}
function fillNameData(data, id) {
var recieve_id_data = window.commonTools.getSubArrayByObjValue(data, 'recieve_id', $('#recieve_id_' + id).val())[0];
var recieve_name_data = window.commonTools.getSubArrayByObjValue(recieve_id_data.recieve_list, 'recieve_name', $('#recieve_name_' + id).val())[0];
$('#recieve_model_' + id).val(recieve_name_data.recieve_model);
}
window.commonTools.duplicateFormCtrl({
container : $('#recieve_content'),
html : '<div class="col-xs-12 col-sm-3">' +
'<div class="form-group form-group-sm cool-form-group cool-form-input-group">' +
'<div class="input-group">' +
'<div class="input-group-addon addon-label">存放地点:</div>' +
'<input type="text" class="form-control" id="recieve_location">' +
'</div>' +
'</div>' +
'</div>' +
'<div class="col-xs-12 col-sm-3">' +
'<div class="form-group form-group-sm cool-form-group cool-form-input-group">' +
'<div class="input-group">' +
'<div class="input-group-addon addon-label">采购单号:</div>' +
'<select type="text" class="form-control" id="recieve_id">' +
'</select>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="col-xs-12 col-sm-3">' +
'<div class="form-group form-group-sm cool-form-group cool-form-input-group">' +
'<div class="input-group">' +
'<div class="input-group-addon addon-label">资产名称:</div>' +
'<select type="text" class="form-control" id="recieve_name">' +
'</select>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="col-xs-12 col-sm-3">' +
'<div class="form-group form-group-sm cool-form-group cool-form-input-group">' +
'<div class="input-group">' +
'<div class="input-group-addon addon-label">规格:</div>' +
'<input type="text" class="form-control" id="recieve_model" disabled>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="col-xs-12 col-sm-2 col-md-3">' +
'<div class="form-group form-group-sm cool-form-group cool-form-input-group">' +
'<div class="input-group">' +
'<div class="input-group-addon addon-label">数量:</div>' +
'<input type="text" class="form-control" id="recieve_num">' +
'</div>' +
'</div>' +
'</div>' +
'<div class="col-xs-12 col-sm-5">' +
'<div class="form-group form-group-sm cool-form-group cool-form-input-group">' +
'<div class="input-group">' +
'<div class="input-group-addon addon-label">备注:</div>' +
'<input type="text" class="form-control" id="recieve_ps">' +
'</div>' +
'</div>' +
'</div>' +
'<div class="col-xs-12 col-sm-3">' +
'<div class="form-group form-group-sm cool-form-group cool-form-input-group">' +
'<div class="input-group">' +
'<div class="input-group-addon addon-label">领用人:</div>' +
'<select class="form-control selectpicker" id="reciever" title="请选择领用人">' +
'<optgroup label="行政">' +
'<option> 小A' +
'<option> 小B' +
'<option> 小C' +
'</optgroup>' +
'<optgroup label="后勤">' +
'<option> 小D' +
'<option> 小E' +
'<option> 小F' +
'</optgroup>' +
'</select>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="col-xs-12 col-sm-2 col-md-1">' +
'<div class="btn btn-line btn-line-red btn-small btn-block" id="recieve_btn_delete">' +
'<i class="fa fa-remove"></i> 删除' +
'</div>' +
'</div>' +
'<div class="col-xs-12">' +
'<div class="cool-form-hline"></div>' +
'</div>',
ids : [
'recieve_location',
'recieve_id',
'recieve_name',
'recieve_model',
'recieve_num',
'recieve_ps',
'reciever',
'recieve_btn_delete'
],
btn_delete_id : 'recieve_btn_delete',
btn_add_id : 'recieve_btn_add',
btn_add_container_id : 'recieve_btn_add_container',
btn_add_html : '<div id="recieve_btn_add_container">' +
'<div class="col-xs-12 col-sm-10 col-md-11">' +
'<div class="form-group form-group-sm cool-form-group cool-form-input-group">' +
'<div class="cool-form-content font-gray-66">点击右侧按钮,添加新的领用申请</div>' +
'</div>' +
'</div>' +
'<div class="col-xs-12 col-sm-2 col-md-1">' +
'<div class="btn btn-line btn-small btn-block" id="recieve_btn_add">' +
'<i class="fa fa-plus"></i> 添加' +
'</div>' +
'</div>' +
'</div>',
init_number : 1,
max_number : 5,
removeOnMax : false,
afterAdd : function($container, id) {
$('#reciever_' + id).selectpicker({
liveSearch : true,
liveSearchPlaceholder : '搜索人员...'
});
window.window.commonTools.addSelectOptions($('#recieve_id_' + id), getOptionsFromData(formData,'recieve_id'));
fillFormData(formData, id);
$('#recieve_id_' + id).change(function(){
fillFormData(formData, id);
})
},
initialData : initData,
fillInitialData : function($container, data, id) {
$('#recieve_id_' + id).val(data.recieve_id);
fillFormData(formData, id);
$('#recieve_name_' + id).val(data.recieve_name);
fillNameData(formData, id);
//$('#recieve_model_' + id).val(data.recieve_model);
$('#recieve_location_' + id).val(data.recieve_location);
$('#recieve_num_' + id).val(data.recieve_num);
$('#recieve_ps_' + id).val(data.recieve_ps);
$('#reciever_' + id).selectpicker('val',data.reciever);
}
});
$('#btn_submit').click(function(){
window.location.href='oa-purchase-assets-get.html';
});
$('#btn_save').click(function(){
toastr.success('您编辑的信息已保存');
});
});
|
/*
json2.js
2012-10-08
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', { '': value });
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({ '': j }, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
} ());
|
module.exports = {
"src_folders": [
"tests" // tests are stored here
],
"output_folder": "./reports", // reports (test outcome) output by nightwatch
"selenium": { // downloaded by selenium-download module (see readme)
"start_process": true, // tells nightwatch to start/stop the selenium process
"server_path": "node_modules/selenium-server/lib/runner/selenium-server-standalone-3.1.0.jar",
"host": "127.0.0.1",
"port": 4444, // standard selenium port
"cli_args": { // chromedriver is downloaded by selenium-download (see readme)
"webdriver.chrome.driver" : "node_modules/.bin/chromedriver"
}
},
"test_settings": {
"default": {
"screenshots": {
"enabled": true, // if you want to keep screenshots
"path": './screenshots' // save screenshots here
},
"globals": {
"waitForConditionTimeout": 5000 // sometimes internet is slow so wait.
},
"desiredCapabilities": { // use Chrome as the default browser for tests
"browserName": "chrome"
}
},
"chrome": {
"desiredCapabilities": {
"browserName": "chrome",
"javascriptEnabled": true // set to false to test progressive enhancement
}
}
}
}
|
var lazyAss = require('lazy-ass');
var check = require('check-types');
var fs = require('fs.extra');
var Comment = require('./Comment');
var preprocess = require('./preprocess');
var postprocess = require('./postprocess').comments;
var dox = require('./dox');
function getComments(source) {
lazyAss(check.unemptyString(source), 'missing source', source);
var cleaned = preprocess(source);
var parsingOptions = {
raw: false
};
// console.log(cleaned);
var comments = dox.parseComments(cleaned, parsingOptions);
if (!check.array(comments)) {
console.error('could not extract comments from source');
comments = [];
}
// console.dir(comments);
comments = postprocess(comments);
return comments;
}
function getTaggedComments(inputFiles) {
if (check.string(inputFiles)) {
inputFiles = [inputFiles];
}
lazyAss(check.array(inputFiles), 'missing input filenames', inputFiles);
var api = [];
inputFiles.forEach(function (filename) {
var fileApi = getFileApi(filename);
lazyAss(check.array(api), 'could not get api array from', filename);
api = api.concat(fileApi);
});
return api;
}
function keepFilename(comments, filename) {
return comments.map(function (aComment) {
aComment.filename = filename;
return aComment;
});
}
function makeComments(comments) {
return comments.map(function (rawComment) {
return new Comment(rawComment);
});
}
function getFileApi(filename) {
lazyAss(check.unemptyString(filename), 'missing filename', filename);
var contents = fs.readFileSync(filename, 'utf-8');
lazyAss(check.string(contents), 'could not load contents of', filename);
var raw = getComments(contents);
lazyAss(check.array(raw), 'could not get tags array from', filename);
raw = keepFilename(raw, filename);
var comments = makeComments(raw);
return comments;
}
function getSamples(inputFiles) {
if (check.string(inputFiles)) {
inputFiles = [inputFiles];
}
lazyAss(check.array(inputFiles), 'missing input filenames');
var docs = getTaggedComments(inputFiles);
// console.dir(docs);
var samples = docs.filter(function (comment) {
return comment.isSample();
});
return samples;
}
module.exports = {
getCommentsFromFiles: getTaggedComments,
getComments: getComments,
getSampleTests: getSamples
};
|
/**
* @author Javier Valencia Romero <javiervalenciaromero@gmail.com>
* @copyright Javier Valencia Romero
* @license {@link https://github.com/jvalen/prototypePacman/blob/master/license.txt|MIT License}
*/
/**
* Keyboard class constructor
*
* @class Controls.Keyboard
* @constructor
*/
var Controls = Controls || {};
Controls.Keyboard = function() {
this.KEYS = {
LEFT: 37,
RIGHT: 39,
UP: 38,
DOWN: 40
};
this.keyState = {};
var _this = this;
//Private methods called by the event listener
this._onKeyDown = function (event) {
event.preventDefault();
return _this.processKeyDown(event);
};
this._onKeyUp = function (event) {
return _this.processKeyUp(event);
};
//Creates the event listeners
window.addEventListener('keydown', this._onKeyDown, false);
window.addEventListener('keyup', this._onKeyUp, true);
};
Controls.Keyboard.prototype = {
/**
* Keep track when the key is down
* @method Controls.Keyboard#processKeyDown
* @param {object} event
*/
processKeyDown: function(event) {
this.keyState[event.keyCode] = true;
},
/**
* Keep track when the key is up
* @method Controls.Keyboard#processKeyUp
* @param {object} event
*/
processKeyUp: function(event) {
this.keyState[event.keyCode] = false;
},
/**
* Returns true if the key is down
* @method Controls.Keyboard#isDown
* @param {number} keycode
* @return {boolean}
*/
isDown: function (keyCode) {
return this.keyState[keyCode] === true;
}
};
Controls.Keyboard.prototype.constructor = Controls.Keyboard;
|
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { connect } from 'react-redux';
import styles from '../styles';
export const Attempts = (props) => {
const { attempts } = props;
const renderLetter = (letterWithScore, idx) => {
let style = styles.attemptLetter;
if (letterWithScore.score === 2) {
style = styles.attemptLetterOnRightLocation;
} else if (letterWithScore.score === 1) {
style = styles.attemptLetterOnOtherLocation;
}
return (<Text style={ style } key={ idx }>{ letterWithScore.letter }</Text>)
};
const renderAttempt = (attempt, attemptId) => {
const letters = attempt.word.split('');
const lettersWithScore = letters.map((elem, index) => {
return {
letter: elem,
score: attempt.score[index]
}
});
return (
<View style={ styles.attempt } key={ attemptId }>
{ lettersWithScore.map((elem, index) => renderLetter(elem, `${attemptId}.${index}`)) }
</View>
);
};
return (
<View style={ styles.attempts }>
{ attempts.map(renderAttempt) }
</View>
);
};
const mapStateToProps = (state) => {
return {
attempts: state.game.attempts
};
};
const mapDispatchToProps = (dispatch) => {
return { };
};
/**
* Props:
* attempts: [{
* word: string
* }]
*/
export default connect(mapStateToProps, mapDispatchToProps)(Attempts);
|
import React from 'react';
import './sidebar.css';
const Sidebar = props => {
return(
<div className="sidebar">
</div>
);
}
export default Sidebar;
|
//
// Drawphone
//
import Game from "./game.js";
class Drawphone {
constructor(devModeEnabled) {
this.games = [];
this.locked = false;
this.minutesUntilRestart;
//add the dev game
if (devModeEnabled) {
this.newGame("ffff");
}
}
newGame(forceCode) {
if (this.locked) return false;
let newCode;
if (forceCode) {
newCode = forceCode;
} else {
newCode = this.generateCode();
}
const newGame = new Game(newCode, () => {
//will be ran when this game has 0 players left
this.removeGame(newCode);
});
this.games.push(newGame);
return newGame;
}
findGame(code) {
if (!code || code.length !== 4) return false;
for (let i = 0; i < this.games.length; i++) {
if (this.games[i].code === code.toLowerCase()) {
return this.games[i];
}
}
return false;
}
generateCode() {
let code;
do {
//generate 4 letter code
code = "";
const possible = "abcdefghijklmnopqrstuvwxyz";
for (let i = 0; i < 4; i++) {
code += possible.charAt(
Math.floor(Math.random() * possible.length)
);
}
//make sure the code is not already in use
} while (this.findGame(code));
return code;
}
removeGame(code) {
const game = this.findGame(code);
const index = this.games.indexOf(game);
if (index > -1) {
this.games.splice(index, 1);
}
}
lock() {
this.locked = true;
this.minutesUntilRestart = 16;
const interval = setInterval(() => {
this.minutesUntilRestart--;
if (this.minutesUntilRestart <= 0) {
clearInterval(interval);
}
}, 1000 * 60); // every minute
}
}
export default Drawphone;
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
function _debounce() {
const data = _interopRequireDefault(require("lodash/debounce"));
_debounce = function () {
return data;
};
return data;
}
function _makeDir() {
const data = require("make-dir");
_makeDir = function () {
return data;
};
return data;
}
function _slash() {
const data = _interopRequireDefault(require("slash"));
_slash = function () {
return data;
};
return data;
}
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _fs() {
const data = _interopRequireDefault(require("fs"));
_fs = function () {
return data;
};
return data;
}
var util = _interopRequireWildcard(require("./util"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
const FILE_TYPE = Object.freeze({
NON_COMPILABLE: "NON_COMPILABLE",
COMPILED: "COMPILED",
IGNORED: "IGNORED",
ERR_COMPILATION: "ERR_COMPILATION"
});
function outputFileSync(filePath, data) {
(0, _makeDir().sync)(_path().default.dirname(filePath));
_fs().default.writeFileSync(filePath, data);
}
function _default(_x) {
return _ref.apply(this, arguments);
}
function _ref() {
_ref = _asyncToGenerator(function* ({
cliOptions,
babelOptions
}) {
const filenames = cliOptions.filenames;
function write(_x2, _x3) {
return _write.apply(this, arguments);
}
function _write() {
_write = _asyncToGenerator(function* (src, base) {
let relative = _path().default.relative(base, src);
if (!util.isCompilableExtension(relative, cliOptions.extensions)) {
return FILE_TYPE.NON_COMPILABLE;
}
relative = util.withExtension(relative, cliOptions.keepFileExtension ? _path().default.extname(relative) : cliOptions.outFileExtension);
const dest = getDest(relative, base);
try {
const res = yield util.compile(src, Object.assign({}, babelOptions, {
sourceFileName: (0, _slash().default)(_path().default.relative(dest + "/..", src))
}));
if (!res) return FILE_TYPE.IGNORED;
if (res.map && babelOptions.sourceMaps && babelOptions.sourceMaps !== "inline") {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
res.map.file = _path().default.basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
outputFileSync(dest, res.code);
util.chmod(src, dest);
if (cliOptions.verbose) {
console.log(src + " -> " + dest);
}
return FILE_TYPE.COMPILED;
} catch (err) {
if (cliOptions.watch) {
console.error(err);
return FILE_TYPE.ERR_COMPILATION;
}
throw err;
}
});
return _write.apply(this, arguments);
}
function getDest(filename, base) {
if (cliOptions.relative) {
return _path().default.join(base, cliOptions.outDir, filename);
}
return _path().default.join(cliOptions.outDir, filename);
}
function handleFile(_x4, _x5) {
return _handleFile.apply(this, arguments);
}
function _handleFile() {
_handleFile = _asyncToGenerator(function* (src, base) {
const written = yield write(src, base);
if (cliOptions.copyFiles && written === FILE_TYPE.NON_COMPILABLE || cliOptions.copyIgnored && written === FILE_TYPE.IGNORED) {
const filename = _path().default.relative(base, src);
const dest = getDest(filename, base);
outputFileSync(dest, _fs().default.readFileSync(src));
util.chmod(src, dest);
}
return written === FILE_TYPE.COMPILED;
});
return _handleFile.apply(this, arguments);
}
function handle(_x6) {
return _handle.apply(this, arguments);
}
function _handle() {
_handle = _asyncToGenerator(function* (filenameOrDir) {
if (!_fs().default.existsSync(filenameOrDir)) return 0;
const stat = _fs().default.statSync(filenameOrDir);
if (stat.isDirectory()) {
const dirname = filenameOrDir;
let count = 0;
const files = util.readdir(dirname, cliOptions.includeDotfiles);
for (const filename of files) {
const src = _path().default.join(dirname, filename);
const written = yield handleFile(src, dirname);
if (written) count += 1;
}
return count;
} else {
const filename = filenameOrDir;
const written = yield handleFile(filename, _path().default.dirname(filename));
return written ? 1 : 0;
}
});
return _handle.apply(this, arguments);
}
let compiledFiles = 0;
let startTime = null;
const logSuccess = (0, _debounce().default)(function () {
if (startTime === null) {
return;
}
const diff = process.hrtime(startTime);
console.log(`Successfully compiled ${compiledFiles} ${compiledFiles !== 1 ? "files" : "file"} with Babel (${diff[0] * 1e3 + Math.round(diff[1] / 1e6)}ms).`);
compiledFiles = 0;
startTime = null;
}, 100, {
trailing: true
});
if (!cliOptions.skipInitialBuild) {
if (cliOptions.deleteDirOnStart) {
util.deleteDir(cliOptions.outDir);
}
(0, _makeDir().sync)(cliOptions.outDir);
startTime = process.hrtime();
for (const filename of cliOptions.filenames) {
compiledFiles += yield handle(filename);
}
if (!cliOptions.quiet) {
logSuccess();
logSuccess.flush();
}
}
if (cliOptions.watch) {
const chokidar = util.requireChokidar();
filenames.forEach(function (filenameOrDir) {
const watcher = chokidar.watch(filenameOrDir, {
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 50,
pollInterval: 10
}
});
let processing = 0;
["add", "change"].forEach(function (type) {
watcher.on(type, function () {
var _ref2 = _asyncToGenerator(function* (filename) {
processing++;
if (startTime === null) startTime = process.hrtime();
try {
yield handleFile(filename, filename === filenameOrDir ? _path().default.dirname(filenameOrDir) : filenameOrDir);
compiledFiles++;
} catch (err) {
console.error(err);
}
processing--;
if (processing === 0 && !cliOptions.quiet) logSuccess();
});
return function (_x7) {
return _ref2.apply(this, arguments);
};
}());
});
});
}
});
return _ref.apply(this, arguments);
}
|
var path = require('path')
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
vendor: ['react','redux','react-redux','react-router'],
bundle: './src/index'
},
output: {
path: path.join(__dirname, 'build'),
filename: '[hash:8].[name].js',
},
plugins: [
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
}),
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
//filename:"vendor.js",
minChunks: Infinity //Infinity
}),
new ExtractTextPlugin('[hash:8].style.css', { allChunks: true }),
new HtmlWebpackPlugin({
favicon:'./src/favicon.ico',
title: "Julian's blog",
template: path.join(__dirname,'src/template.html'), //模板文件
inject:'body',
hash:false, //为静态资源生成hash值
minify:{ //压缩HTML文件
removeComments:false, //移除HTML中的注释
collapseWhitespace:true //删除空白符与换行符
}
}),
],
module: {
loaders: [{
test: /\.js$/,
loaders: [ 'babel' ],
exclude: /node_modules/,
include: path.join(__dirname,'src')
},
{ test: /\.(css|scss)$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap!sass-loader?sourceMap&includePaths[]=' + path.resolve(__dirname, "./node_modules/compass-mixins/lib") ) },
{
test: /\.(jpe?g|png|gif)$/i,
loaders: [
'url?limit=10000&name=images/[hash:8].[name].[ext]',
'image-webpack?{progressive:true, optimizationLevel: 7, interlaced: false, pngquant:{quality: "65-90", speed: 4}}'
]
},{
test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url?limit=10000&name=fonts/[hash:8].[name].[ext]'
}
]
},
resolve: {
root: path.resolve(__dirname, 'node_modules'),
extensions: ['','.js','.scss']
}
}
|
'use babel';
import utils from '../utils';
class SQLMetaProvider {
constructor() {
this.selector = '.source.sql, .source.pgsql';
this.disableForSelector = '.source.sql .string, .source.sql .comment'
this.filterSuggestions = true;
atom.config.observe( // called immediately and on update
'autocomplete-plus.minimumWordLength',
(newValue) => this.minimumWordLength = newValue
)
}
getSchemaNames(editor, search) {
let items = editor.dataAtomSchemata || [];
if (items.length == 0)
return [];
return items.map((item) => {
return {
text: item.name,
rightLabelHTML: `<span class="data-atom autocomplete"></span>${item.type}`
};
});
}
getTableNames(editor, tableSearch, schema) {
let tables = editor.dataAtomTables || [];
if (tables.length == 0)
return [];
let results = tables.filter((table) => {
if (schema)
return table.schemaName === schema;
else
return true;
});
return results.map((table) => {
return {
text: table.name,
displayText: (schema || table.schemaName === editor.defaultSchema) ? table.name : table.schemaName + '.' + table.name,
rightLabelHTML: `<span class="data-atom autocomplete autocomplete-tbl"></span>${table.type}`
};
});
}
getColumnNames(editor, columnSearch, objectName) {
let columns = editor.dataAtomColumns || [];
if (columns.length == 0)
return [];
let valid = columns.filter((col) => {
if (objectName)
return col.tableName === objectName;
else
return true;
});
return valid.map((col) => {
return {
text: col.name,
rightLabelHTML: '<span class="data-atom autocomplete autocomplete-col"></span>Column',
leftLabel: col.type || col.udt
};
});
}
getAliasedObject(editor, lastIdentifier) {
let query = editor.getBuffer().getTextInRange(utils.getRangeForQueryAtCursor(editor));
let matches = query.match(new RegExp('([\\w0-9]*)\\s*(?:AS)?\\s*' + lastIdentifier + '[\\s;]', 'i'));
if (matches) {
return matches[matches.length - 1];
} else {
return null;
}
}
getPrefix(editor, bufferPosition) {
let line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]);
let matches = line.match(/[\w\.]+$/);
if (matches) {
return matches[0] || '';
} else {
return '';
}
}
getSuggestions({editor, bufferPosition, scopeDescriptor}) {
return new Promise(resolve => {
let prefix = this.getPrefix(editor, bufferPosition);
let identifiers = prefix.split('.');
let identsLength = identifiers.length;
let results = [];
let lastIdentifier = (identsLength > 1) && identifiers[identsLength - 2];
let search = identifiers[identsLength - 1];
if (search.length < this.minimumWordLength) return [];
results = this.getColumnNames(editor, search, lastIdentifier).concat(this.getTableNames(editor, search, lastIdentifier));
if (!lastIdentifier)
results = results.concat(this.getSchemaNames(editor, search));
// If there are no results, check for alias
if (!results.length) {
let tableName = this.getAliasedObject(editor, lastIdentifier);
if (tableName) {
// Get by matched alias table
results = this.getColumnNames(editor, search, tableName);
}
}
resolve(results);
});
}
}
export default new SQLMetaProvider();
|
$(function(){
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
slidesPerView : 3,
slidesPerGroup : 3
});
})
|
var utils = require('../src/utils');
var key = require('../src/rudiments').key;
var scale = require('../src/rudiments').scale;
var ensemble = require("../src/instruments/ensemble");
var instruments = require("../src/instruments/instruments");
var stringQuartet = ensemble.stringQuartet;
var performer = ensemble.stringQuartet.performers.sacconi.individual;
var players = utils.playersFromEnsemble(stringQuartet, performer, true);
utils.addPlayer(players, instruments.piano, 'piano1');
utils.addPlayer(players, instruments.piano, 'piano2',5);
var rules = {
v1a: ' >e F ',
v1b: ' cD ',
v1c: ' BC^///DE^',
v1d: ' Fd/+FGAg',
v1e: ' 48,v1a 24,v1b 48,v1a 0:24, v1c v1f',
v1f: ' 24,v1b v1d 1: 24,v1b v1d v1e',
violin1: '{pizzicato} 0:24, v1e v1f ^',
violin2:'v1b 0: 48,v1a v1d 0: 3@ v1a 24,v1c v1e 0@ v1f',
c1a: '-1:24, cE^/G',
c1b: '-1:48, g^//',
c1c: '-1:48, /24,aB^',
c1d: '-1:48, ////',
c1e: 'c1a c1b v1c c1a c1c c1f',
c1f: 'c1b c1d c1b v1a v1b v1a c1d c1e',
cello: '{pizzicato} c1e c1f ^',
p1e: '12, v1a 24,v1b 12,v1a 0: v1c v1f',
p1f: '12, v1b {pedaldown} v1d 48, 1: v1b 24, v1d {pedalup} v1e',
piano1: '0: 12, p1e p1f',
piano2: '3@ 12, p1f p1e '
};
var conductor = {
1: scale.cblues + ' 144=T',
17: scale.fblues,
25: scale.cblues,
33: scale.gblues,
37: scale.fblues,
41: scale.gblues,
45: scale.fblues,
49: scale.gblues,
53: scale.fblues,
58: scale.cblues
};
utils.addRudiments(rules);
module.exports = {
players: players,
rules: rules,
conductor: conductor
};
|
'use strict';
// =============================================================================
// var declaration
// =============================================================================
var mongoose = require('mongoose'),
Performance = mongoose.model('Performance'),
SystemConfig = mongoose.model('SystemConfig');
// =============================================================================
// helper function declaration
// =============================================================================
var savePerformance = function(persistensiPerformance, jumlahEvent, jumlahEventHadir) {
persistensiPerformance.kriteriaPersistensi.jumlahEvent = jumlahEvent;
persistensiPerformance.kriteriaPersistensi.jumlahEventHadir = jumlahEventHadir;
// persistensiPerformance.kriteriaPersistensi.kriteriaValue = (parseInt(jumlahEventHadir) / 4);
persistensiPerformance.save();
};
//
var updatePerformance = function(resourceId, jumlahEvent, jumlahEventHadir,year,pengali) {
Performance.findOne({resource: resourceId, year:year, isEvent:true}).exec(function(err, persistensiPerformance) {
if(!err) {
if(persistensiPerformance ===undefined || persistensiPerformance === null){
persistensiPerformance = new Performance({
resource:resourceId,
year:year,
isEvent:true,
rumusAkhir:pengali
});
}
savePerformance(persistensiPerformance, jumlahEvent, jumlahEventHadir);
}
});
};
var findSystemConfigPengaliPerformance = function(resourceId, jumlahEvent, jumlahEventHadir,year) {
SystemConfig.findOne({key: SystemConfig.PENGALI_PERFORMANCE}, function(err, systemConfig) {
if(!err) {
var pengali = systemConfig.value;
updatePerformance(resourceId, jumlahEvent, jumlahEventHadir,year,pengali);
}
});
};
// =============================================================================
// exported function declaration
// =============================================================================
exports.do = function(req, res) {
var resourceId = req.body.resource;
var jumlahEvent = req.body.kriteriaPersistensi.jumlahEvent;
var jumlahEventHadir = req.body.kriteriaPersistensi.jumlahEventHadir;
var year = req.body.year;
//var kriteriaValue = (parseInt(jumlahEventHadir) / parseInt(jumlahEvent));
//console.log(resourceId);
//console.log(jumlahEvent);
//console.log(jumlahEventHadir);
//console.log('test');
//updatePerformance(resourceId, jumlahEvent, jumlahEventHadir,year);
findSystemConfigPengaliPerformance(resourceId, jumlahEvent, jumlahEventHadir,year);
res.send(200);
};
|
import * as userQueries from './queries';
import * as userMutations from './mutations';
export default {
userQueries,
userMutations,
};
|
/**
* Mi9Controller
*
* @description :: Server-side logic for managing mi9s
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
/**
* `Mi9Controller.index()`
*/
index: function(req, res) {
//sails.log.debug(req.body)
if (req.body == undefined || req.body.payload == undefined) {
res.status(400)
res.send({
"error": "Could not decode request: JSON parsing failed"
})
} else {
var json = []
for(var i in req.body.payload){
//sails.log.debug(i)
var src = req.body.payload[i]
if (src.episodeCount && src.episodeCount>0){
var obj = {}
if(src.image && src.image.showImage){
obj.image = src.image.showImage
}
obj.slug = src.slug
obj.title = src.title
json.push(obj)
}
}
return res.json({
response: json
});
}
}
}
|
define({
"taskUrl": "Tehtävän URL-osoite",
"setTask": "Määritä",
"setTaskPopupTitle": "Määritä tehtävä",
"validate": "Määritä",
"inValidGPService": "Anna kelvollinen geoprosessointipalvelu.",
"GPFeatureRecordSetLayerERR": "Anna geoprosessointipalvelu, jossa on vain GPFeatureRecordSetLayer-tyypin lähtöaineistoa.",
"invalidInputParameters": "Syöteparametreja on alle 1 tai yli 3. Anna kelvollinen geoprosessointipalvelu.",
"projectSetting": {
"title": "Projektiasetukset",
"note": "Huomautus: projektiasetukset ovat valinnaiset, koska määritetty käyttäjä voi tallentaa projektin haluamiinsa web-kartan karttatasoihin verkon käyttökatkoalueiden ja lähtöaineiston parametrien kanssa. Käyttäjä voi tallentaa muut tulosparametrit Syöte/Tulos-välilehden Tulos-ryhmästä.",
"projectPolygonLayer": "Projektin aluekarttataso",
"outputParameterName": "Tulosparametrin nimi",
"projectPointLayer": "Projektin pistekarttataso",
"selectLabel": "Valitse",
"polygonLayerHelp": "<p>Seuraavia ehtoja vastaavat aluekarttatasot näytetään:<br/><ul><li>Karttatasossa on oltava muokkaustoiminnot eli Luo, Poista ja Päivitä</li><li>Karttatasossa on oltava kaksi kenttää, joissa on tarkat nimi- ja tietotyypit:</li><ul><li>nimi (String-tyypin kenttä)</li><li>globalid (GlobalID-tyypin kenttä)</li></ul></ul><p/>",
"outputParameterHelp": "<p>Tehtävän URL-osoitteen tulosaineiston aluekarttatasot näytetään<p/>",
"pointLayerHelp": "<p>Seuraavia ehtoja vastaavat pistekarttatasot näytetään:<br/><ul><li>Karttatasossa on oltava muokkaustoiminnot eli Luo, Poista ja Päivitä</li><li>Karttatasossa on oltava kaksi kenttää, joissa on tarkat nimi- ja tietotyypit:</li><ul><li>inputtype (String-tyypin kenttä)</li><li>projectid (GUID-tyypin kenttä)</li></ul></ul><p/>"
},
"inputOutputTab": {
"flag": "Lippu",
"barrier": "Este",
"skip": "Ohita",
"title": "Syöte/Tulos",
"inputSettingsLabel": "Syöteasetukset",
"outputSettingsLabel": "Tulosasetukset",
"inputLabel": "Tunnusteksti",
"inputTooltip": "Työkalun ohje",
"symbol": "Symboli",
"typeText": "Tyyppi",
"outputParametersText": "Tulosparametrit",
"saveToLayerText": "Tallenna karttatasoon (valinnainen)",
"skipText": "Ohitettavissa",
"visibilityText": "Näkyvä",
"exportToCsvText": "Vie CSV-tiedostoon",
"exportToCsvDisplayText": "CSV",
"settitngstext": "Asetukset",
"addFieldTitle": "Lisää kenttä",
"enterDisplayText": "Kirjoita näyttöteksti",
"setScale": "Määritä mittakaava",
"outputDisplay": "Näyttöteksti",
"saveToLayerHelp": "<p>Seuraavia ehtoja vastaava karttataso näytetään:<br/><ul><li>Karttatasossa on oltava muokkaustoiminnot eli Luo, Poista ja Päivitä</li><li>Karttatasossa on oltava kaksi kenttää, joissa on nimi- ja tietotyypit:</li><ul><li>parametername (String-tyypin kenttä)</li><li>projectid (GUID-tyypin kenttä)</li></ul></ul><p/>"
},
"summaryTab": {
"title": "Yleiset asetukset",
"summaryFieldsetText": "Yhteenvetoasetukset",
"inputOutput": "Syöte/Tulos",
"field": "Kenttä",
"operator": "Laskutoimitus",
"inputOperatorCountOption": "Lukumäärä",
"outputOperatorCountOption": "Lukumäärä",
"outputOperatorSkipCountOption": "OhitettavaMäärä",
"fieldOperatorSumOption": "Summa",
"fieldOperatorMinOption": "Vähimmäisarvo",
"fieldOperatorMaxOption": "Enimmäisarvo",
"fieldOperatorMeanOption": "Keskiarvo",
"expressionAddButtonText": "Lisää",
"expressionVerifyButtonText": "Tarkasta",
"summaryEditorText": "Yhteenvetoteksti",
"autoZoomAfterTrace": "Lisävalinnat",
"zoomText": "Automaattinen tarkennus jäljityksen jälkeen",
"summarSettingTooltipText": "Lisää lähtöaineiston/tulosaineiston määrä"
},
"validationErrorMessage": {
"webMapError": "Web-kartassa ei ole karttatasoja. Valitse kelvollinen web-kartta.",
"inputTypeFlagGreaterThanError": "Lipputyypin syötteitä ei voi olla yhtä enempää.",
"inputTypeFlagLessThanError": "Vähintään yksi lipputyypin syöte on pakollinen.",
"inputTypeBarrierErr": "Estetyypin syötteitä ei voi olla yhtä enempää.",
"inputTypeSkipErr": "Ohitustyypin syötteitä ei voi olla yhtä enempää.",
"displayTextForButtonError": "Suorita-painikkeen näyttöteksti ei voi olla tyhjä.",
"UnableToLoadGeoprocessError": "Geoprosessointipalvelua ei voi ladata.",
"invalidSummaryExpression": "Virheellinen lauseke.",
"validSummaryExpression": "Onnistui!",
"invalidProjectSettings": "Virheelliset projektiasetukset.<br/> Valitse kelvollinen arvo asetuksessa ${projectSetting}."
},
"hintText": {
"labelTextHint": "Vihje: määritä tulosparametrin tulosruudussa näytettävä tunnusteksti.",
"displayTextHint": "Vihje: tämä näytetään tämän tulosparametrin Tiedot-ruudussa.",
"inputTextHint": "Vihje: muodosta lausekkeesi yllä valitsemalla syöte, tulos ja kenttien nimet.",
"expressionHint": "Vihje: muodosta lauseke valitsemalla kohteet ja napsauttamalla Lisää."
}
});
|
'use strict';
exports = module.exports = function(app, passport) {
var LocalStrategy = require('passport-local').Strategy,
TwitterStrategy = require('passport-twitter').Strategy,
GitHubStrategy = require('passport-github').Strategy,
FacebookStrategy = require('passport-facebook').Strategy,
GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
TumblrStrategy = require('passport-tumblr').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
var conditions = { isActive: 'yes' };
if (username.indexOf('@') === -1) {
conditions.username = username;
}
else {
conditions.email = username.toLowerCase();
}
app.db.models.User.findOne(conditions, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Unknown user' });
}
app.db.models.User.validatePassword(password, user.password, function(err, isValid) {
if (err) {
return done(err);
}
if (!isValid) {
return done(null, false, { message: 'Invalid password' });
}
return done(null, user);
});
});
}
));
if (app.config.oauth.twitter.key) {
passport.use(new TwitterStrategy({
consumerKey: app.config.oauth.twitter.key,
consumerSecret: app.config.oauth.twitter.secret
},
function(token, tokenSecret, profile, done) {
done(null, false, {
token: token,
tokenSecret: tokenSecret,
profile: profile
});
}
));
}
if (app.config.oauth.github.key) {
passport.use(new GitHubStrategy({
clientID: app.config.oauth.github.key,
clientSecret: app.config.oauth.github.secret,
customHeaders: { "User-Agent": app.config.projectName }
},
function(accessToken, refreshToken, profile, done) {
done(null, false, {
accessToken: accessToken,
refreshToken: refreshToken,
profile: profile
});
}
));
}
if (app.config.oauth.facebook.key) {
passport.use(new FacebookStrategy({
clientID: app.config.oauth.facebook.key,
clientSecret: app.config.oauth.facebook.secret
},
function(accessToken, refreshToken, profile, done) {
done(null, false, {
accessToken: accessToken,
refreshToken: refreshToken,
profile: profile
});
}
));
}
if (app.config.oauth.google.key) {
passport.use(new GoogleStrategy({
clientID: app.config.oauth.google.key,
clientSecret: app.config.oauth.google.secret
},
function(accessToken, refreshToken, profile, done) {
done(null, false, {
accessToken: accessToken,
refreshToken: refreshToken,
profile: profile
});
}
));
}
if (app.config.oauth.tumblr.key) {
passport.use(new TumblrStrategy({
consumerKey: app.config.oauth.tumblr.key,
consumerSecret: app.config.oauth.tumblr.secret
},
function(token, tokenSecret, profile, done) {
done(null, false, {
token: token,
tokenSecret: tokenSecret,
profile: profile
});
}
));
}
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
app.db.models.User.findOne({ _id: id }).populate('roles.admin').populate('roles.account').populate('roles.dataEntryOperator').exec(function(err, user) {
if (user && user.roles && user.roles.admin) {
user.roles.admin.populate("groups", function(err, admin) {
done(err, user);
});
}
else {
done(err, user);
}
});
});
};
|
/*jslint node: true */
'use strict';
// Gulp Dependencies
var gulp = require('gulp'),
rename = require('gulp-rename');
// Build Dependencies
var transform = require('vinyl-transform'),
browserify = require('browserify'),
uglify = require('gulp-uglify');
// Style Dependencies
var stylus = require('gulp-stylus'),
notify = require('gulp-notify'),
minifyCSS = require('gulp-minify-css');
// Development Dependencies
var jshint = require('gulp-jshint'),
browserSync = require('browser-sync'),
reload = browserSync.reload;
// Lint
gulp.task('lint-client', function() {
return gulp.src('./client/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// Browserify
gulp.task('browserify-client', ['lint-client'], function() {
var browserified = transform(function(filename) {
var b = browserify({
entries: filename,
debug: true
});
return b.bundle();
});
return gulp.src('client/js/main.js')
.pipe(browserified)
.pipe(rename('main.js'))
.pipe(gulp.dest('public/js'));
});
// Styles
gulp.task('styles', function() {
return gulp.src('./client/stylus/main.styl')
.pipe(stylus().on('error', notify.onError(function(error) {
return "Error:" + error.message;
})))
.pipe(gulp.dest('public/css'))
.pipe(browserSync.reload({
stream: true
}));
});
// Build
gulp.task('minify', ['styles'], function() {
return gulp.src('public/css/main.css')
.pipe(minifyCSS())
.pipe(rename('main.min.css'))
.pipe(gulp.dest('public/css'));
});
// Uglify
gulp.task('uglify', ['browserify-client'], function() {
return gulp.src('public/js/main.js')
.pipe(uglify())
.pipe(rename('main.min.js'))
.pipe(gulp.dest('public/js'))
.pipe(browserSync.reload({
stream: true
}));
});
// Watch
gulp.task('watch', ['browserSync'], function() {
gulp.watch('client/**/*.js', ['uglify']).on('change', reload);
gulp.watch('client/**/*.styl', ['styles', 'minify']).on('change', reload);
gulp.watch('views/*.hbs').on('change', reload);
});
// Tasks
gulp.task('default', ['uglify', 'minify']);
|
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json')
});
grunt.loadNpmTasks('grunt-react');
grunt.initConfig({
react: {
single_file_output: {
files: {
'react/EEM/app.js': 'react/ownership/app.jsx'
}
},
dynamic_mappings: {
files: [
{
expand: true,
cwd: 'react/ownership',
src: ['**/*.jsx'],
dest: 'react/ownership',
ext: '.js'
}
]
}
},
})
// task setup
grunt.registerTask('default', ['react']);
};
|
$(function () {
update()
$('input#send').click(send)
$('input#update').click(update)
})
function update(){
$.get('/get', function (result, status){
$('textarea').val(result.txt)
if(result.txt==undefined){
alert('Sth went wrong!')
}
})
}
function send(){
$.post('/', {txt:$('textarea').val()},function(result){
if(result.code!=0){
alert("Something went wrong!")
}
})
}
|
import {
assignNumber,
computeStyleFromItem,
CurrentLevel,
depthOf,
div, EventBus,
findLevel,
flattenAll, generateColour, getPalletXPosition,
mapDepths,
matchesRange,
RANGE_DISPLAY_LARGE,
RANGE_DISPLAY_NONE,
RANGE_DISPLAY_PREV_NEXT,
renderTemporal,
setStyle,
sortByKey
} from '../utils';
export default class DeepRange {
static CSS_ITEM = 'galway-timeline__item';
static CSS_ITEM_ACTIVE = 'galway-timeline__item--active';
static CSS_ITEM_REPRESENTATION = 'galway-timeline__representation';
static CSS_TEMPORAL = 'galway-timeline__temporal';
static CSS_ITEM_CHILDREN = 'galway-timeline__item--children';
constructor($el, model) {
this.$el = $el;
this.model = model;
this.bus = new EventBus('DeepRange');
// Initial DOM elements
this.renderInitial($el);
}
onClickRange(func) {
this.$elements.forEach(
$el => {
const key = this.$elements.indexOf($el);
const item = this.model.flatItems[key];
$el.addEventListener('click', e => {
return func(item, key, $el, e);
});
}
);
}
renderInitial($el) {
const $tooltip = document.querySelector('.galway-timeline__tooltip-float');
$el.addEventListener('mouseenter', (e) => {
$tooltip.classList.add('galway-timeline__tooltip-float--active');
});
$el.addEventListener('mouseleave', () => {
$tooltip.classList.remove('galway-timeline__tooltip-float--active');
});
$el.addEventListener('mousemove', (e) => {
const calc = getPalletXPosition($tooltip.getBoundingClientRect().width, e.clientX, window.innerWidth);
$tooltip.style.left = `${calc}px`;
});
this.$elements = this.model.flatItems.map(
(item) => {
// Only show top level, hide the rest.
const visibility = this.model.topKeys.indexOf(item.key) === -1 ? RANGE_DISPLAY_NONE : RANGE_DISPLAY_LARGE;
return (
div({
className: DeepRange.CSS_ITEM,
style: computeStyleFromItem(visibility, item),
onMouseEnter: () => {
$tooltip.innerText = item.label;
this.hoveredItem = item;
this.bus.dispatch('item:hover', item);
},
onMouseLeave: () => {
this.bus.dispatch('item:blur', item);
if (this.hoveredItem === item) {
this.hoveredItem = null;
}
},
}, [
div({
className: DeepRange.CSS_ITEM_REPRESENTATION, style: {
background: generateColour(item.level)
}
}),
div({className: DeepRange.CSS_TEMPORAL}, [
renderTemporal(item)
]),
])
);
}
);
$el.innerHTML = '';
this.$elements.forEach($element => {
$el.appendChild($element);
});
}
renderTopLevel(canvasIndex, model) {
this.$elements.forEach(($element, key) => {
const currentLevel = model.topKeys.indexOf(key);
const item = model.structure[currentLevel];
this.renderActive($element, item, canvasIndex);
if (currentLevel !== -1) {
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_LARGE, item));
return;
}
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_NONE, item));
});
}
renderActive($element, item, canvasIndex) {
if (matchesRange(item, canvasIndex)) {
$element.classList.add(DeepRange.CSS_ITEM_ACTIVE);
this.bus.dispatch('item:active', item);
if (item.children) {
$element.classList.add(DeepRange.CSS_ITEM_CHILDREN);
}
} else if ($element.classList.contains(DeepRange.CSS_ITEM_ACTIVE)) {
this.bus.dispatch('item:inactive', item);
$element.classList.remove(DeepRange.CSS_ITEM_ACTIVE);
$element.classList.remove(DeepRange.CSS_ITEM_CHILDREN);
}
}
render(canvasIndex, model) {
// If we are at the top level depth, we just render as normal.
if (model.depth === 0) {
return this.renderTopLevel(canvasIndex, model);
}
// Here we look for the current "view" which is the sub-sections expanded out.
if (model.currentViews.length === 0) {
// Default back to top level if we can't find a view.
return this.renderTopLevel(canvasIndex, model);
}
this.$elements.forEach(($element, key) => {
const item = model.current.findCurrent(key);
// Render the current item with class.
this.renderActive($element, item, canvasIndex);
if (model.current.isNext(key) || model.current.isPrevious(key)) {
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_PREV_NEXT, item));
return;
}
if (item) {
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_LARGE, item));
return;
}
setStyle($element, computeStyleFromItem(RANGE_DISPLAY_NONE, item));
});
}
}
|
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable values for each character.
*
* EXAMPLES:
* // No arguments - returns RFC4122, version 4 ID
* >>> Math.uuid()
* "92329D39-6F5C-4520-ABFC-AAB64544E172"
*
* // One argument - returns ID of the specified length
* >>> Math.uuid(15) // 15 character ID (default base=62)
* "VcydxgltxrVZSTV"
*
* // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
* >>> Math.uuid(8, 2) // 8 character ID (base=2)
* "01001010"
* >>> Math.uuid(8, 10) // 8 character ID (base=10)
* "47473046"
* >>> Math.uuid(8, 16) // 8 character ID (base=16)
* "098F4D35"
*/
// Private array of chars to use
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var math = {
uuid: function (len, radix) {
var chars = CHARS, uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
},
uuidFast: function () {
var chars = CHARS, uuid = new Array(36), rnd = 0, r;
for (var i = 0; i < 36; i++) {
if (i == 8 || i == 13 || i == 18 || i == 23) {
uuid[i] = '-';
} else if (i == 14) {
uuid[i] = '4';
} else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
r = rnd & 0xf;
rnd = rnd >> 4;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
return uuid.join('');
}, uuidCompact: function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
};
function replaceSign(rs)
{
return rs.replace(/\-/g, '');
}
exports.get = math.uuid;
exports.getNoSign = function () {
return replaceSign(math.uuid.apply(this, arguments));
};
exports.getFast = math.uuidFast;
exports.getFastNoSign = function () {
return replaceSign(math.uuidFast.apply(this, arguments));
};
exports.getCompact = math.uuidCompact;
exports.getCompactNoSign = function () {
return replaceSign(math.uuidCompact.apply(this, arguments));
};
|
var ctrl = function ($scope, $q, $state, $stateParam, $anchorScroll, categoryService,
eventService, placeService, transactionService) {
$scope.isEditMode = $stateParam.publicId;
$scope.options = {
showWeeks: false
};
const applyToPromise = transactionService.getApplyToList();
$q.when(applyToPromise, function (data) {
$scope.applyToList = data;
});
const categoryPromise = categoryService.getList();
$q.when(categoryPromise, function (data) {
$scope.categoryList = data;
});
const eventPromise = eventService.defaultList()
$q.when(eventPromise, function (data) {
$scope.eventList = data;
});
const placePromise = placeService.defaultList()
$q.when(placePromise, function (data) {
$scope.placeList = data;
});
$scope.currentTx = {};
$q.all([
applyToPromise,
categoryPromise,
eventPromise,
placePromise
]).then(function () {
if ($scope.isEditMode) {
var request = { publicId: $stateParam.publicId };
transactionService.retrieve(request).then(function (data) {
data.calendar = new Date(data.calendar);
$scope.currentTx = data;
$scope.toExpense = data.category.toExpense;
});
} else {
$scope.currentTx.calendar = new Date();
}
});
$scope.filterByApplyTo = function (item) {
return item.toExpense === $scope.toExpense;
};
$scope.submit = function (data) {
$scope.submitted = true;
$anchorScroll();
transactionService.create(data).then(
function () {
if ($scope.isEditMode) {
$scope.cancel();
} else {
$scope.submitted = false;
$scope.toExpense = undefined;
$scope.currentTx.amount = null;
$scope.currentTx.category = null;
$scope.currentTx.description = null;
$scope.hasSaved = true;
$scope.hasError = false;
}
}, function (error) {
$scope.submitted = false;
$scope.hasSaved = false;
$scope.hasError = true;
console.error(error);
});
};
$scope.cancel = function () {
$state.go('accountTransactions');
};
};
ctrl.$inject = ['$scope', '$q', '$state', '$stateParams', '$anchorScroll', 'categoryService',
'eventService', 'placeService', 'transactionService'];
export default {
name: 'AddOrEditTransactionCtrl',
fn: ctrl
};
|
var assert = require('assert')
, svgfont2svgicons = require(__dirname + '/../src/index.js')
, Fs = require('fs')
, StringDecoder = require('string_decoder').StringDecoder
, Path = require("path")
;
// Tests
describe('Parsing fonts', function() {
it("should work for simple SVG fonts", function(done) {
var fontStream = Fs.createReadStream(__dirname + '/fixtures/cleanicons.svg');
var iconProvider = svgfont2svgicons();
var icons = [];
var bufferedIcons = 0;
var ended = false;
fontStream.pipe(iconProvider);
iconProvider.on('readable', function() {
var icon;
do {
icon = iconProvider.read();
if(icon) {
icon.content = '';
icons.push(icons);
icon.stream.on('readable', (function(icon) {
return function() {
var chunk;
do {
chunk = icon.stream.read();
if(chunk) {
icon.content += chunk.toString('utf-8');
}
} while(null !== chunk);
};
})(icon));
icon.stream.once('end', (function(icon) {
return function() {
assert.equal(
Fs.readFileSync(__dirname + '/expected/cleanicons/' + icon.name + '.svg'),
icon.content
);
bufferedIcons++;
if(ended && icons.length == bufferedIcons) {
done();
}
};
})(icon));
}
} while(null !== icon);
}).once('end',function() {
ended = true;
if(icons.length == bufferedIcons) {
done();
}
});
});
});
|
angular.module('demo').controller('ComponentsDemoCtrl',function($scope,$rootScope,$state){
});
|
import _ from 'lodash';
function registerMethod(vorpal, browser, property) {
vorpal
.command(`${property} [params...]`, 'Refer http://webdriver.io/api')
.parse(cmd => cmd
.split(' ')
.map(encodeURIComponent)
.join(' '))
.action(async ({ params = [] }) => {
const cleanedParams = params.map(decodeURIComponent);
const res = await browser[property](...cleanedParams);
if (res.value) {
vorpal.log(res.value);
} else {
vorpal.log(res);
}
});
}
module.exports = ({ vorpal, driver: { current: browser } }) => {
const methods = _.keysIn(browser);
methods.forEach((property) => {
registerMethod(vorpal, browser, property);
});
};
|
var dir_aa9befc4bdfa617079e96718d920d9d2 =
[
[ "Projects", "dir_9749fe1d1039c274ca5f4a0137bd5805.html", "dir_9749fe1d1039c274ca5f4a0137bd5805" ]
];
|
var items = require('../repositories/item');
var S = require('string');
var ObjectId = require('mongodb').ObjectID;
var extend = require('extend');
exports.fetchForTab = function(req, res) {
items.findByTabId(req.db,
req.params.tabId,
function(err, items) {
if (err) {
res.jsonError();
} else {
res.jsonSuccess(items);
}
}
);
};
exports.create = function(req, res) {
res.render('item/create', {
title: '',
content: '',
backUrl: '/tabs/' + req.params.tabId
});
};
exports.store = function(req, res) {
var err = validateItem(req);
if (err) {
req.flash('error', err);
res.render('item/create');
} else {
items.insert(req.db, {
tab_id: new ObjectId(req.params.tabId),
title: req.body.title,
content: req.body.content
}, function(err, result) {
if (err) {
throw err;
} else {
req.flash('success', 'New item has been successfully created.');
res.redirect('/tabs/' + req.params.tabId);
}
});
}
};
exports.edit = function(req, res) {
items.findById(req.db, req.params.id, function(err, item) {
if (err) {
throw err;
} else {
res.render('item/edit', extend(item, {
backUrl: '/tabs/' + req.params.tabId
})
);
}
});
};
exports.update = function(req, res) {
var err = validateItem(req);
if (err) {
req.flash('error', err);
res.render('item/edit', {
title: req.body.item,
content: req.body.content
});
return;
}
items.update(req.db,
{
id: req.params.id,
title: req.body.title,
content: req.body.content
},
function(err, result) {
if (err) {
throw err;
} else {
res.redirect('/tabs/' + req.params.tabId);
}
}
);
};
function validateItem(req) {
title = S(req.body.title).trim().s;
if (!title) {
return 'Title name cannot be empty.';
}
content = S(req.body.content).trim().s;
if (!content) {
return 'Content cannot be empty.';
}
return '';
}
exports.delete = function(req, res) {
items.delete(req.db, req.params.id, function(err, result) {
if (err) {
throw err;
} else {
res.redirect('/tabs/' + req.params.tabId);
}
});
};
|
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
/*!
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */
(function ($) {
var $jQval = $.validator,
adapters,
data_validation = "unobtrusiveValidation";
function setValidationValues(options, ruleName, value) {
options.rules[ruleName] = value;
if (options.message) {
options.messages[ruleName] = options.message;
}
}
function splitAndTrim(value) {
return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
}
function escapeAttributeValue(value) {
// As mentioned on http://api.jquery.com/category/selectors/
return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
}
function getModelPrefix(fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
}
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
}
function onErrors(event, validator) { // 'this' is the form element
var container = $(this).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length && validator.errorList.length) {
list.empty();
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
$.each(validator.errorList, function () {
$("<li />").html(this.message).appendTo(list);
});
}
}
function onSuccess(error) { // 'this' is the form element
var container = error.data("unobtrusiveContainer"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;
if (container) {
container.addClass("field-validation-valid").removeClass("field-validation-error");
error.removeData("unobtrusiveContainer");
if (replace) {
container.empty();
}
}
}
function onReset(event) { // 'this' is the form element
var $form = $(this),
key = '__jquery_unobtrusive_validation_form_reset';
if ($form.data(key)) {
return;
}
// Set a flag that indicates we're currently resetting the form.
$form.data(key, true);
try {
$form.data("validator").resetForm();
} finally {
$form.removeData(key);
}
$form.find(".validation-summary-errors")
.addClass("validation-summary-valid")
.removeClass("validation-summary-errors");
$form.find(".field-validation-error")
.addClass("field-validation-valid")
.removeClass("field-validation-error")
.removeData("unobtrusiveContainer")
.find(">*") // If we were using valmsg-replace, get the underlying error
.removeData("unobtrusiveContainer");
}
function validationInfo(form) {
var $form = $(form),
result = $form.data(data_validation),
onResetProxy = $.proxy(onReset, form),
defaultOptions = $jQval.unobtrusive.options || {},
execInContext = function (name, args) {
var func = defaultOptions[name];
func && $.isFunction(func) && func.apply(form, args);
}
if (!result) {
result = {
options: { // options structure passed to jQuery Validate's validate() method
errorClass: defaultOptions.errorClass || "input-validation-error",
errorElement: defaultOptions.errorElement || "span",
errorPlacement: function () {
onError.apply(form, arguments);
execInContext("errorPlacement", arguments);
},
invalidHandler: function () {
onErrors.apply(form, arguments);
execInContext("invalidHandler", arguments);
},
messages: {},
rules: {},
success: function () {
onSuccess.apply(form, arguments);
execInContext("success", arguments);
}
},
attachValidation: function () {
$form
.off("reset." + data_validation, onResetProxy)
.on("reset." + data_validation, onResetProxy)
.validate(this.options);
},
validate: function () { // a validation function that is called by unobtrusive Ajax
$form.validate();
return $form.valid();
}
};
$form.data(data_validation, result);
}
return result;
}
$jQval.unobtrusive = {
adapters: [],
parseElement: function (element, skipAttach) {
/// <summary>
/// Parses a single HTML element for unobtrusive validation attributes.
/// </summary>
/// <param name="element" domElement="true">The HTML element to be parsed.</param>
/// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
/// validation to the form. If parsing just this single element, you should specify true.
/// If parsing several elements, you should specify false, and manually attach the validation
/// to the form when you are finished. The default is false.</param>
var $element = $(element),
form = $element.parents("form")[0],
valInfo, rules, messages;
if (!form) { // Cannot do client-side validation without a form
return;
}
valInfo = validationInfo(form);
valInfo.options.rules[element.name] = rules = {};
valInfo.options.messages[element.name] = messages = {};
$.each(this.adapters, function () {
var prefix = "data-val-" + this.name,
message = $element.attr(prefix),
paramValues = {};
if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
prefix += "-";
$.each(this.params, function () {
paramValues[this] = $element.attr(prefix + this);
});
this.adapt({
element: element,
form: form,
message: message,
params: paramValues,
rules: rules,
messages: messages
});
}
});
$.extend(rules, { "__dummy__": true });
if (!skipAttach) {
valInfo.attachValidation();
}
},
parse: function (selector) {
/// <summary>
/// Parses all the HTML elements in the specified selector. It looks for input elements decorated
/// with the [data-val=true] attribute value and enables validation according to the data-val-*
/// attribute values.
/// </summary>
/// <param name="selector" type="String">Any valid jQuery selector.</param>
// $forms includes all forms in selector's DOM hierarchy (parent, children and self) that have at least one
// element with data-val=true
var $selector = $(selector),
$forms = $selector.parents()
.addBack()
.filter("form")
.add($selector.find("form"))
.has("[data-val=true]");
$selector.find("[data-val=true]").each(function () {
$jQval.unobtrusive.parseElement(this, true);
});
$forms.each(function () {
var info = validationInfo(this);
if (info) {
info.attachValidation();
}
});
}
};
adapters = $jQval.unobtrusive.adapters;
adapters.add = function (adapterName, params, fn) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
/// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
/// mmmm is the parameter name).</param>
/// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
/// attributes into jQuery Validate rules and/or messages.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
if (!fn) { // Called with no params, just a function
fn = params;
params = [];
}
this.push({ name: adapterName, params: params, adapt: fn });
return this;
};
adapters.addBool = function (adapterName, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has no parameter values.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, function (options) {
setValidationValues(options, ruleName || adapterName, true);
});
};
adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
/// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a minimum value.</param>
/// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a maximum value.</param>
/// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
/// have both a minimum and maximum value.</param>
/// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the minimum value. The default is "min".</param>
/// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the maximum value. The default is "max".</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
var min = options.params.min,
max = options.params.max;
if (min && max) {
setValidationValues(options, minMaxRuleName, [min, max]);
}
else if (min) {
setValidationValues(options, minRuleName, min);
}
else if (max) {
setValidationValues(options, maxRuleName, max);
}
});
};
adapters.addSingleVal = function (adapterName, attribute, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has a single value.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
/// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
/// The default is "val".</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [attribute || "val"], function (options) {
setValidationValues(options, ruleName || adapterName, options.params[attribute]);
});
};
$jQval.addMethod("__dummy__", function (value, element, params) {
return true;
});
$jQval.addMethod("regex", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
match = new RegExp(params).exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
$jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
var match;
if (nonalphamin) {
match = value.match(/\W/g);
match = match && match.length >= nonalphamin;
}
return match;
});
if ($jQval.methods.extension) {
adapters.addSingleVal("accept", "mimtype");
adapters.addSingleVal("extension", "extension");
} else {
// for backward compatibility, when the 'extension' validation method does not exist, such as with versions
// of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
// validating the extension, and ignore mime-type validations as they are not supported.
adapters.addSingleVal("extension", "extension", "accept");
}
adapters.addSingleVal("regex", "pattern");
adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
adapters.add("equalto", ["other"], function (options) {
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
setValidationValues(options, "equalTo", element);
});
adapters.add("required", function (options) {
// jQuery Validate equates "required" with "mandatory" for checkbox elements
if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
setValidationValues(options, "required", true);
}
});
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {}
},
prefix = getModelPrefix(options.element.name);
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
var paramName = appendModelPrefix(fieldName, prefix);
value.data[paramName] = function () {
var field = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']");
// For checkboxes and radio buttons, only pick up values from checked fields.
if (field.is(":checkbox")) {
return field.filter(":checked").val() || field.filter(":hidden").val() || '';
}
else if (field.is(":radio")) {
return field.filter(":checked").val() || '';
}
return field.val();
};
});
setValidationValues(options, "remote", value);
});
adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
if (options.params.min) {
setValidationValues(options, "minlength", options.params.min);
}
if (options.params.nonalphamin) {
setValidationValues(options, "nonalphamin", options.params.nonalphamin);
}
if (options.params.regex) {
setValidationValues(options, "regex", options.params.regex);
}
});
$(function () {
$jQval.unobtrusive.parse(document);
});
}(jQuery));
// SIG // Begin signature block
// SIG // MIIdkQYJKoZIhvcNAQcCoIIdgjCCHX4CAQExCzAJBgUr
// SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB
// SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB
// SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFERK7HKPGs4A
// SIG // c8SDSgXz8oOWoM19oIIYUzCCBMIwggOqoAMCAQICEzMA
// SIG // AAC/kWz7fBok4CIAAAAAAL8wDQYJKoZIhvcNAQEFBQAw
// SIG // dzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0
// SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p
// SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWlj
// SIG // cm9zb2Z0IFRpbWUtU3RhbXAgUENBMB4XDTE2MDkwNzE3
// SIG // NTg0OVoXDTE4MDkwNzE3NTg0OVowgbIxCzAJBgNVBAYT
// SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH
// SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y
// SIG // cG9yYXRpb24xDDAKBgNVBAsTA0FPQzEnMCUGA1UECxMe
// SIG // bkNpcGhlciBEU0UgRVNOOjU3QzgtMkQxNS0xQzhCMSUw
// SIG // IwYDVQQDExxNaWNyb3NvZnQgVGltZS1TdGFtcCBTZXJ2
// SIG // aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
// SIG // AQEAre1/hsD2onVXFU0U9sqIVfy9XaUzAr3+Ax5QmNBl
// SIG // JoRMw+GJ9tqv6p6mUxw3fCJSPzh7yoVgvZLChBfgYAR7
// SIG // VED0oO7OvmV8uval+uK+pu1/zWIs3it9Q7EnC7Ax56rG
// SIG // 58CWjWdgtruYYXCrB73PAWkrL/5ypa+vnoNol9svWotb
// SIG // gdckjXrpxLXX3IQK9VOkG+wCR61zE3SpfKbS6L+u2hVN
// SIG // K0UTMECTlh0fqP4EGvb+M/3+N0WNj5zEaBew87Z+nYra
// SIG // EPQoE4jHUjLbKhVjAEDTLeW2fKGNYZoJEgzehcE41clB
// SIG // BOrdyibYF9oTB4zlarR10JbndBkd2S7QDjG0uwIDAQAB
// SIG // o4IBCTCCAQUwHQYDVR0OBBYEFORsGjkax5NYtEY2ZQfE
// SIG // ALd5F5wRMB8GA1UdIwQYMBaAFCM0+NlSRnAK7UD7dvuz
// SIG // K7DDNbMPMFQGA1UdHwRNMEswSaBHoEWGQ2h0dHA6Ly9j
// SIG // cmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3Rz
// SIG // L01pY3Jvc29mdFRpbWVTdGFtcFBDQS5jcmwwWAYIKwYB
// SIG // BQUHAQEETDBKMEgGCCsGAQUFBzAChjxodHRwOi8vd3d3
// SIG // Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY3Jvc29m
// SIG // dFRpbWVTdGFtcFBDQS5jcnQwEwYDVR0lBAwwCgYIKwYB
// SIG // BQUHAwgwDQYJKoZIhvcNAQEFBQADggEBAI7eto3GftmA
// SIG // apu0SorfNuw0VPTioqIuhxBEU9F9Gy/iY1E7t+5OKYj3
// SIG // Ctyf9HH5LVrj462ErskmvzW5JpbwIUFeFaaFsYqcd3Ga
// SIG // ZRfRyvSB+LfAA2A8VCObtcW9q9uGhMRiM1mPtbh/dm80
// SIG // ymwI7sDc0zENc9dCnGuF1zyOBxWWpV8YC324wpFdyCjb
// SIG // KVNUyC1dA85NLXSgMMfzKHmTdRxXAfVo826RZwlR/jsv
// SIG // zcniTsojROLk/+osh89flwqn9pyK1fw117CWCsIn1ZTr
// SIG // 0ieGa1eNDGLnKt5VkLihEX14ryxV5XSsl0K0uHnk6ET0
// SIG // nr0YrHNBgWLmXM6ZHXjeX2gwggYAMIID6KADAgECAhMz
// SIG // AAAAww6bp9iy3PcsAAAAAADDMA0GCSqGSIb3DQEBCwUA
// SIG // MH4xCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5n
// SIG // dG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVN
// SIG // aWNyb3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01p
// SIG // Y3Jvc29mdCBDb2RlIFNpZ25pbmcgUENBIDIwMTEwHhcN
// SIG // MTcwODExMjAyMDI0WhcNMTgwODExMjAyMDI0WjB0MQsw
// SIG // CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQ
// SIG // MA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9z
// SIG // b2Z0IENvcnBvcmF0aW9uMR4wHAYDVQQDExVNaWNyb3Nv
// SIG // ZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUA
// SIG // A4IBDwAwggEKAoIBAQC7V9c40bEGf0ktqW2zY596urY6
// SIG // IVu0mK6N1KSBoMV1xSzvgkAqt4FTd/NjAQq8zjeEA0BD
// SIG // V4JLzu0ftv2AbcnCkV0Fx9xWWQDhDOtX3v3xuJAnv3VK
// SIG // /HWycli2xUibM2IF0ZWUpb85Iq2NEk1GYtoyGc6qIlxW
// SIG // SLFvRclndmJdMIijLyjFH1Aq2YbbGhElgcL09Wcu53kd
// SIG // 9eIcdfROzMf8578LgEcp/8/NabEMC2DrZ+aEG5tN/W1H
// SIG // OsfZwWFh8pUSoQ0HrmMh2PSZHP94VYHupXnoIIJfCtq1
// SIG // UxlUAVcNh5GNwnzxVIaA4WLbgnM+Jl7wQBLSOdUmAw2F
// SIG // iDFfCguLAgMBAAGjggF/MIIBezAfBgNVHSUEGDAWBgor
// SIG // BgEEAYI3TAgBBggrBgEFBQcDAzAdBgNVHQ4EFgQUpxNd
// SIG // HyGJVegD7p4XNuryVIg1Ga8wUQYDVR0RBEowSKRGMEQx
// SIG // DDAKBgNVBAsTA0FPQzE0MDIGA1UEBRMrMjMwMDEyK2M4
// SIG // MDRiNWVhLTQ5YjQtNDIzOC04MzYyLWQ4NTFmYTIyNTRm
// SIG // YzAfBgNVHSMEGDAWgBRIbmTlUAXTgqoXNzcitW2oynUC
// SIG // lTBUBgNVHR8ETTBLMEmgR6BFhkNodHRwOi8vd3d3Lm1p
// SIG // Y3Jvc29mdC5jb20vcGtpb3BzL2NybC9NaWNDb2RTaWdQ
// SIG // Q0EyMDExXzIwMTEtMDctMDguY3JsMGEGCCsGAQUFBwEB
// SIG // BFUwUzBRBggrBgEFBQcwAoZFaHR0cDovL3d3dy5taWNy
// SIG // b3NvZnQuY29tL3BraW9wcy9jZXJ0cy9NaWNDb2RTaWdQ
// SIG // Q0EyMDExXzIwMTEtMDctMDguY3J0MAwGA1UdEwEB/wQC
// SIG // MAAwDQYJKoZIhvcNAQELBQADggIBAE2XTzR+8XCTnOPV
// SIG // GkucEX5rJsSlJPTfRNQkurNqCImZmssx53Cb/xQdsAc5
// SIG // f+QwOxMi3g7IlWe7bn74fJWkkII3k6aD00kCwaytWe+R
// SIG // t6dmAA6iTCXU3OddBwLKKDRlOzmDrZUqjsqg6Ag6HP4+
// SIG // e0BJlE2OVCUK5bHHCu5xN8abXjb1p0JE+7yHsA3ANdkm
// SIG // h1//Z+8odPeKMAQRimfMSzVgaiHnw40Hg16bq51xHykm
// SIG // CRHU9YLT0jYHKa7okm2QfwDJqFvu0ARl+6EOV1PM8piJ
// SIG // 858Vk8gGxGNSYQJPV0gc9ft1Esq1+fTCaV+7oZ0NaYMn
// SIG // 64M+HWsxw+4O8cSEQ4fuMZwGADJ8tyCKuQgj6lawGNSy
// SIG // vRXsN+1k02sVAiPGijOHOtGbtsCWWSygAVOEAV/ye8F6
// SIG // sOzU2FL2X3WBRFkWOCdTu1DzXnHf99dR3DHVGmM1Kpd+
// SIG // n2Y3X89VM++yyrwsI6pEHu77Z0i06ELDD4pRWKJGAmEm
// SIG // Whm/XJTpqEBw51swTHyA1FBnoqXuDus9tfHleR7h9VgZ
// SIG // b7uJbXjiIFgl/+RIs+av8bJABBdGUNQMbJEUfe7K4vYm
// SIG // 3hs7BGdRLg+kF/dC/z+RiTH4p7yz5TpS3Cozf0pkkWXY
// SIG // ZRG222q3tGxS/L+LcRbELM5zmqDpXQjBRUWlKYbsATFt
// SIG // XnTGVjELMIIGBzCCA++gAwIBAgIKYRZoNAAAAAAAHDAN
// SIG // BgkqhkiG9w0BAQUFADBfMRMwEQYKCZImiZPyLGQBGRYD
// SIG // Y29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MS0w
// SIG // KwYDVQQDEyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0
// SIG // ZSBBdXRob3JpdHkwHhcNMDcwNDAzMTI1MzA5WhcNMjEw
// SIG // NDAzMTMwMzA5WjB3MQswCQYDVQQGEwJVUzETMBEGA1UE
// SIG // CBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe
// SIG // MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw
// SIG // HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0Ew
// SIG // ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCf
// SIG // oWyx39tIkip8ay4Z4b3i48WZUSNQrc7dGE4kD+7Rp9FM
// SIG // rXQwIBHrB9VUlRVJlBtCkq6YXDAm2gBr6Hu97IkHD/cO
// SIG // BJjwicwfyzMkh53y9GccLPx754gd6udOo6HBI1PKjfpF
// SIG // zwnQXq/QsEIEovmmbJNn1yjcRlOwhtDlKEYuJ6yGT1VS
// SIG // DOQDLPtqkJAwbofzWTCd+n7Wl7PoIZd++NIT8wi3U21S
// SIG // tEWQn0gASkdmEScpZqiX5NMGgUqi+YSnEUcUCYKfhO1V
// SIG // eP4Bmh1QCIUAEDBG7bfeI0a7xC1Un68eeEExd8yb3zuD
// SIG // k6FhArUdDbH895uyAc4iS1T/+QXDwiALAgMBAAGjggGr
// SIG // MIIBpzAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBQj
// SIG // NPjZUkZwCu1A+3b7syuwwzWzDzALBgNVHQ8EBAMCAYYw
// SIG // EAYJKwYBBAGCNxUBBAMCAQAwgZgGA1UdIwSBkDCBjYAU
// SIG // DqyCYEBWJ5flJRP8KuEKU5VZ5KShY6RhMF8xEzARBgoJ
// SIG // kiaJk/IsZAEZFgNjb20xGTAXBgoJkiaJk/IsZAEZFglt
// SIG // aWNyb3NvZnQxLTArBgNVBAMTJE1pY3Jvc29mdCBSb290
// SIG // IENlcnRpZmljYXRlIEF1dGhvcml0eYIQea0WoUqgpa1M
// SIG // c1j0BxMuZTBQBgNVHR8ESTBHMEWgQ6BBhj9odHRwOi8v
// SIG // Y3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0
// SIG // cy9taWNyb3NvZnRyb290Y2VydC5jcmwwVAYIKwYBBQUH
// SIG // AQEESDBGMEQGCCsGAQUFBzAChjhodHRwOi8vd3d3Lm1p
// SIG // Y3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY3Jvc29mdFJv
// SIG // b3RDZXJ0LmNydDATBgNVHSUEDDAKBggrBgEFBQcDCDAN
// SIG // BgkqhkiG9w0BAQUFAAOCAgEAEJeKw1wDRDbd6bStd9vO
// SIG // eVFNAbEudHFbbQwTq86+e4+4LtQSooxtYrhXAstOIBNQ
// SIG // md16QOJXu69YmhzhHQGGrLt48ovQ7DsB7uK+jwoFyI1I
// SIG // 4vBTFd1Pq5Lk541q1YDB5pTyBi+FA+mRKiQicPv2/OR4
// SIG // mS4N9wficLwYTp2OawpylbihOZxnLcVRDupiXD8WmIsg
// SIG // P+IHGjL5zDFKdjE9K3ILyOpwPf+FChPfwgphjvDXuBfr
// SIG // Tot/xTUrXqO/67x9C0J71FNyIe4wyrt4ZVxbARcKFA7S
// SIG // 2hSY9Ty5ZlizLS/n+YWGzFFW6J1wlGysOUzU9nm/qhh6
// SIG // YinvopspNAZ3GmLJPR5tH4LwC8csu89Ds+X57H2146So
// SIG // dDW4TsVxIxImdgs8UoxxWkZDFLyzs7BNZ8ifQv+AeSGA
// SIG // nhUwZuhCEl4ayJ4iIdBD6Svpu/RIzCzU2DKATCYqSCRf
// SIG // WupW76bemZ3KOm+9gSd0BhHudiG/m4LBJ1S2sWo9iaF2
// SIG // YbRuoROmv6pH8BJv/YoybLL+31HIjCPJZr2dHYcSZAI9
// SIG // La9Zj7jkIeW1sMpjtHhUBdRBLlCslLCleKuzoJZ1GtmS
// SIG // hxN1Ii8yqAhuoFuMJb+g74TKIdbrHk/Jmu5J4PcBZW+J
// SIG // C33Iacjmbuqnl84xKf8OxVtc2E0bodj6L54/LlUWa8kT
// SIG // o/0wggd6MIIFYqADAgECAgphDpDSAAAAAAADMA0GCSqG
// SIG // SIb3DQEBCwUAMIGIMQswCQYDVQQGEwJVUzETMBEGA1UE
// SIG // CBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe
// SIG // MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTIw
// SIG // MAYDVQQDEylNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0
// SIG // ZSBBdXRob3JpdHkgMjAxMTAeFw0xMTA3MDgyMDU5MDla
// SIG // Fw0yNjA3MDgyMTA5MDlaMH4xCzAJBgNVBAYTAlVTMRMw
// SIG // EQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRt
// SIG // b25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRp
// SIG // b24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
// SIG // bmcgUENBIDIwMTEwggIiMA0GCSqGSIb3DQEBAQUAA4IC
// SIG // DwAwggIKAoICAQCr8PpyEBwurdhuqoIQTTS68rZYIZ9C
// SIG // Gypr6VpQqrgGOBoESbp/wwwe3TdrxhLYC/A4wpkGsMg5
// SIG // 1QEUMULTiQ15ZId+lGAkbK+eSZzpaF7S35tTsgosw6/Z
// SIG // qSuuegmv15ZZymAaBelmdugyUiYSL+erCFDPs0S3XdjE
// SIG // LgN1q2jzy23zOlyhFvRGuuA4ZKxuZDV4pqBjDy3TQJP4
// SIG // 494HDdVceaVJKecNvqATd76UPe/74ytaEB9NViiienLg
// SIG // Ejq3SV7Y7e1DkYPZe7J7hhvZPrGMXeiJT4Qa8qEvWeSQ
// SIG // Oy2uM1jFtz7+MtOzAz2xsq+SOH7SnYAs9U5WkSE1JcM5
// SIG // bmR/U7qcD60ZI4TL9LoDho33X/DQUr+MlIe8wCF0JV8Y
// SIG // KLbMJyg4JZg5SjbPfLGSrhwjp6lm7GEfauEoSZ1fiOIl
// SIG // XdMhSz5SxLVXPyQD8NF6Wy/VI+NwXQ9RRnez+ADhvKwC
// SIG // gl/bwBWzvRvUVUvnOaEP6SNJvBi4RHxF5MHDcnrgcuck
// SIG // 379GmcXvwhxX24ON7E1JMKerjt/sW5+v/N2wZuLBl4F7
// SIG // 7dbtS+dJKacTKKanfWeA5opieF+yL4TXV5xcv3coKPHt
// SIG // bcMojyyPQDdPweGFRInECUzF1KVDL3SV9274eCBYLBNd
// SIG // YJWaPk8zhNqwiBfenk70lrC8RqBsmNLg1oiMCwIDAQAB
// SIG // o4IB7TCCAekwEAYJKwYBBAGCNxUBBAMCAQAwHQYDVR0O
// SIG // BBYEFEhuZOVQBdOCqhc3NyK1bajKdQKVMBkGCSsGAQQB
// SIG // gjcUAgQMHgoAUwB1AGIAQwBBMAsGA1UdDwQEAwIBhjAP
// SIG // BgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFHItOgIx
// SIG // kEO5FAVO4eqnxzHRI4k0MFoGA1UdHwRTMFEwT6BNoEuG
// SIG // SWh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js
// SIG // L3Byb2R1Y3RzL01pY1Jvb0NlckF1dDIwMTFfMjAxMV8w
// SIG // M18yMi5jcmwwXgYIKwYBBQUHAQEEUjBQME4GCCsGAQUF
// SIG // BzAChkJodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtp
// SIG // L2NlcnRzL01pY1Jvb0NlckF1dDIwMTFfMjAxMV8wM18y
// SIG // Mi5jcnQwgZ8GA1UdIASBlzCBlDCBkQYJKwYBBAGCNy4D
// SIG // MIGDMD8GCCsGAQUFBwIBFjNodHRwOi8vd3d3Lm1pY3Jv
// SIG // c29mdC5jb20vcGtpb3BzL2RvY3MvcHJpbWFyeWNwcy5o
// SIG // dG0wQAYIKwYBBQUHAgIwNB4yIB0ATABlAGcAYQBsAF8A
// SIG // cABvAGwAaQBjAHkAXwBzAHQAYQB0AGUAbQBlAG4AdAAu
// SIG // IB0wDQYJKoZIhvcNAQELBQADggIBAGfyhqWY4FR5Gi7T
// SIG // 2HRnIpsLlhHhY5KZQpZ90nkMkMFlXy4sPvjDctFtg/6+
// SIG // P+gKyju/R6mj82nbY78iNaWXXWWEkH2LRlBV2AySfNIa
// SIG // SxzzPEKLUtCw/WvjPgcuKZvmPRul1LUdd5Q54ulkyUQ9
// SIG // eHoj8xN9ppB0g430yyYCRirCihC7pKkFDJvtaPpoLpWg
// SIG // Kj8qa1hJYx8JaW5amJbkg/TAj/NGK978O9C9Ne9uJa7l
// SIG // ryft0N3zDq+ZKJeYTQ49C/IIidYfwzIY4vDFLc5bnrRJ
// SIG // OQrGCsLGra7lstnbFYhRRVg4MnEnGn+x9Cf43iw6IGmY
// SIG // slmJaG5vp7d0w0AFBqYBKig+gj8TTWYLwLNN9eGPfxxv
// SIG // FX1Fp3blQCplo8NdUmKGwx1jNpeG39rz+PIWoZon4c2l
// SIG // l9DuXWNB41sHnIc+BncG0QaxdR8UvmFhtfDcxhsEvt9B
// SIG // xw4o7t5lL+yX9qFcltgA1qFGvVnzl6UJS0gQmYAf0AAp
// SIG // xbGbpT9Fdx41xtKiop96eiL6SJUfq/tHI4D1nvi/a7dL
// SIG // l+LrdXga7Oo3mXkYS//WsyNodeav+vyL6wuA6mk7r/ww
// SIG // 7QRMjt/fdW1jkT3RnVZOT7+AVyKheBEyIXrvQQqxP/uo
// SIG // zKRdwaGIm1dxVk5IRcBCyZt2WwqASGv9eZ/BvW1taslS
// SIG // cxMNelDNMYIEqjCCBKYCAQEwgZUwfjELMAkGA1UEBhMC
// SIG // VVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcT
// SIG // B1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw
// SIG // b3JhdGlvbjEoMCYGA1UEAxMfTWljcm9zb2Z0IENvZGUg
// SIG // U2lnbmluZyBQQ0EgMjAxMQITMwAAAMMOm6fYstz3LAAA
// SIG // AAAAwzAJBgUrDgMCGgUAoIG+MBkGCSqGSIb3DQEJAzEM
// SIG // BgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgor
// SIG // BgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBRUN/lpWZj1
// SIG // RaCsaThy/nCcHyyKHjBeBgorBgEEAYI3AgEMMVAwTqAm
// SIG // gCQATQBpAGMAcgBvAHMAbwBmAHQAIABMAGUAYQByAG4A
// SIG // aQBuAGehJIAiaHR0cDovL3d3dy5taWNyb3NvZnQuY29t
// SIG // L2xlYXJuaW5nIDANBgkqhkiG9w0BAQEFAASCAQCkq4tO
// SIG // VjP6szFewnN6HfBMtifdiCwlB0MWCdzTT4mQTc/q+g9n
// SIG // p0xSerD1R+Zsfj1McAyQJJoMZWOYUyAZ3drZBKXbIhDW
// SIG // 0yqnYSEKIBd5LgLekWNIdNZMh2sGrdyNV2A7EzBSIGFv
// SIG // rZ7/XU5fPanS6/Ev/zIN1awatMV6XcU1e2wLEcNSqS/Y
// SIG // sBBkKffgy6EJym1GAvU87baXAOpQvT2U8CdqEJuBYWuw
// SIG // Jugwwi6t9qByoLe0RUmRP3dwY59+akgwcJC/1xQk2wSF
// SIG // z8EK+gQ3hOF29CYU159i7OV9U2qFw0yIxyQHI0Oaopty
// SIG // edbrdFlsk+P2cHHIfQ1QWP92HXTBoYICKDCCAiQGCSqG
// SIG // SIb3DQEJBjGCAhUwggIRAgEBMIGOMHcxCzAJBgNVBAYT
// SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH
// SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y
// SIG // cG9yYXRpb24xITAfBgNVBAMTGE1pY3Jvc29mdCBUaW1l
// SIG // LVN0YW1wIFBDQQITMwAAAL+RbPt8GiTgIgAAAAAAvzAJ
// SIG // BgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3
// SIG // DQEHATAcBgkqhkiG9w0BCQUxDxcNMTcxMjI5MDYxMTQ0
// SIG // WjAjBgkqhkiG9w0BCQQxFgQUBLBTVvXEYFjtO79voUQ1
// SIG // XbMDEkcwDQYJKoZIhvcNAQEFBQAEggEAIex0rD1R3EYw
// SIG // K+E4a0Mt+zlZmL4NHKaxBXO48IIi1xgCD12KSxFtsVNG
// SIG // ifI2LiTqdUbEaQAMWzO9IkCEH36Uu9fTq1/8jN7J8yd5
// SIG // WH2yrKVwj6drA1GoIjVu++s6OqKDV0WwXJT0hfdyxAv6
// SIG // NtBSZv30JfMMJCTGW6rxzz4wvl+rcoesKyOzILVgok6P
// SIG // GSsZFQWdv5g5qTsSxJ8sHUpiBg0uUr9Vt5aKKfACw2OU
// SIG // O9n5cUl8l2FE+SAA2BJ4G3hT8u9BB5fvpsgDeEqE7CX3
// SIG // k5WxgDyEJoiaQtANTgkK3i+2ckHNx9YSuzjET3RjSR1F
// SIG // d/iK9UnSI/Cc+yJd/HZGIQ==
// SIG // End signature block
|
var mongoose = require('mongoose');
var extend = require('mongoose-schema-extend');
var Schema = mongoose.Schema;
var ad_objects = require('./additionalModels.js');
var Element = require('mongoose').model('Element').schema;
var ElementVersion = require('mongoose').model('ElementVersion').schema;
var RecordVersion = require('mongoose').model('RecordVersion').schema;
var Territory = Element.extend({
territoryAtomized: {
extentOfOccurrence : String,
areaOfOccupancy : String
},
territoryUnstructured : String
},{ collection: 'territory', versionKey: false });
var TerritoryVersion = ElementVersion.extend({
territory : Territory
},{ collection: 'TerritoryVersion', versionKey: false });
module.exports = mongoose.model('TerritoryVersion', TerritoryVersion );
|
// All code points with the `Deprecated` property as per Unicode v9.0.0:
[
0x149,
0x673,
0xF77,
0xF79,
0x17A3,
0x17A4,
0x206A,
0x206B,
0x206C,
0x206D,
0x206E,
0x206F,
0x2329,
0x232A,
0xE0001
];
|
vows = require('vows');
assert = require('assert');
_ = require('lodash');
r = require('../');
vows.describe('Rhythmically merge').addBatch({
"merge sequences": function() {
s = r.merge(r.sequence('a b'), r.sequence('d e'));
assert.equal(s.length, 4);
assert.deepEqual(_.pluck(s, 'value'), ['a', 'd', 'b', 'e']);
assert.deepEqual(_.pluck(s, 'duration'), [1/4, 1/4, 1/4, 1/4]);
assert.deepEqual(_.pluck(s, 'position'), [0, 0, 0.25, 0.25]);
}
}).export(module);
|
'use strict';
module.exports = function(models) {
const OurServices = models.OurServices;
return {
createOurServicesData(ourServicesData) {
let ourServices = new OurServices(ourServicesData);
return new Promise((resolve, reject) => {
ourServices.save((error) => {
if (error) {
return reject(error);
}
return resolve(ourServices);
});
});
},
getAllOurServices() {
return new Promise((resolve, reject) => {
OurServices.find((err, details) => {
if (err) {
return reject(err);
}
return resolve(details);
});
});
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.