code stringlengths 2 1.05M |
|---|
/**
* @license AngularJS v1.2.0rc1
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document, undefined) {'use strict';
/**
* @description
*
* This object provides a utility for producing rich Error messages within
* Angular. It can be called as follows:
*
* var exampleMinErr = minErr('example');
* throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
*
* The above creates an instance of minErr in the example namespace. The
* resulting error will have a namespaced error code of example.one. The
* resulting error will replace {0} with the value of foo, and {1} with the
* value of bar. The object is not restricted in the number of arguments it can
* take.
*
* If fewer arguments are specified than necessary for interpolation, the extra
* interpolation markers will be preserved in the final string.
*
* Since data will be parsed statically during a build step, some restrictions
* are applied with respect to how minErr instances are created and called.
* Instances should have names of the form namespaceMinErr for a minErr created
* using minErr('namespace') . Error codes, namespaces and template strings
* should all be static strings, not variables or general expressions.
*
* @param {string} module The namespace to use for the new minErr instance.
* @returns {function(string, string, ...): Error} instance
*/
function minErr(module) {
return function () {
var prefix = '[' + (module ? module + ':' : '') + arguments[0] + '] ',
template = arguments[1],
templateArgs = arguments,
message;
message = prefix + template.replace(/\{\d+\}/g, function (match) {
var index = +match.slice(1, -1), arg;
if (index + 2 < templateArgs.length) {
arg = templateArgs[index + 2];
if (isFunction(arg)) {
return arg.toString().replace(/ ?\{[\s\S]*$/, '');
} else if (isUndefined(arg)) {
return 'undefined';
} else if (!isString(arg)) {
return toJson(arg);
}
return arg;
}
return match;
});
return new Error(message);
};
}
////////////////////////////////////
/**
* hasOwnProperty may be overwritten by a property of the same name, or entirely
* absent from an object that does not inherit Object.prototype; this copy is
* used instead
*/
var hasOwnPropertyFn = Object.prototype.hasOwnProperty;
var hasOwnPropertyLocal = function(obj, key) {
return hasOwnPropertyFn.call(obj, key);
};
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
var /** holds major version number for IE or NaN for real browsers */
msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
ngMinErr = minErr('ng'),
_angular = window.angular,
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
nodeName_,
uid = ['0', '0', '0'];
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...)
*/
function isArrayLike(obj) {
if (obj == null || isWindow(obj)) {
return false;
}
var length = obj.length;
if (obj.nodeType === 1 && length) {
return true;
}
return isArray(obj) || !isFunction(obj) && (
length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj
);
}
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)){
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isArrayLike(obj)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value) };
}
/**
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
* the number string gets longer over time, and it can also overflow, where as the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index = uid.length;
var digit;
while(index) {
index--;
digit = uid[index].charCodeAt(0);
if (digit == 57 /*'9'*/) {
uid[index] = 'A';
return uid.join('');
}
if (digit == 90 /*'Z'*/) {
uid[index] = '0';
} else {
uid[index] = String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* Set or clear the hashkey for an object.
* @param obj object
* @param h the hashkey (!truthy to delete the hashkey)
*/
function setHashKey(obj, h) {
if (h) {
obj.$$hashKey = h;
}
else {
delete obj.$$hashKey;
}
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function extend(dst) {
var h = dst.$$hashKey;
forEach(arguments, function(obj){
if (obj !== dst) {
forEach(obj, function(value, key){
dst[key] = value;
});
}
});
setHashKey(dst,h);
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(new (extend(function() {}, {prototype:parent}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
<pre>
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || angular.identity)(value);
};
</pre>
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value){return typeof value == 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value){return typeof value != 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value){return value != null && typeof value == 'object';}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value){return typeof value == 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value){return typeof value == 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){
return toString.apply(value) == '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
return toString.apply(value) == '[object Array]';
}
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value){return typeof value == 'function';}
/**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return toString.apply(value) == '[object RegExp]';
}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.apply(obj) === '[object File]';
}
function isBoolean(value) {
return typeof value == 'boolean';
}
var trim = (function() {
// native trim is way faster: http://jsperf.com/angular-trim-test
// but IE doesn't have it... :-(
// TODO: we should move this into IE/ES5 polyfill
if (!String.prototype.trim) {
return function(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
};
}
return function(value) {
return isString(value) ? value.trim() : value;
};
})();
/**
* @ngdoc function
* @name angular.isElement
* @function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.on && node.find)); // we have an on and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str){
var obj = {}, items = str.split(","), i;
for ( i = 0; i < items.length; i++ )
obj[ items[i] ] = true;
return obj;
}
if (msie < 9) {
nodeName_ = function(element) {
element = element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName != 'HTML')
? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
};
} else {
nodeName_ = function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function map(obj, iterator, context) {
var results = [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @description
* Determines the number of elements in an array, the number of properties an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*/
function size(obj, ownPropsOnly) {
var size = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
function includes(array, obj) {
return indexOf(array, obj) != -1;
}
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
function arrayRemove(array, value) {
var index = indexOf(array, value);
if (index >=0)
array.splice(index, 1);
return value;
}
function isLeafNode (node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*/
function copy(source, destination){
if (isWindow(source) || isScope(source)) {
throw ngMinErr('cpws', "Can't copy! Making copies of Window or Scope instances is not supported.");
}
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isRegExp(source)) {
destination = new RegExp(source.source);
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (source === destination) throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
if (isArray(source)) {
destination.length = 0;
for ( var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
var h = destination.$$hashKey;
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] = copy(source[key]);
}
setHashKey(destination,h);
}
}
return destination;
}
/**
* Create a shallow copy of an object
*/
function shallowCopy(src, dst) {
dst = dst || {};
for(var key in src) {
if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and
* objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties pass `===` comparison.
* * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
* * Both values represent the same regular expression (In JavasScript,
* /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
* representation matches).
*
* During a property comparison, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) == o2.length) {
for(key=0; key<length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
return isDate(o2) && o1.getTime() == o2.getTime();
} else if (isRegExp(o1) && isRegExp(o2)) {
return o1.toString() == o2.toString();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
keySet = {};
for(key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for(key in o2) {
if (!keySet.hasOwnProperty(key) &&
key.charAt(0) !== '$' &&
o2[key] !== undefined &&
!isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are prebound to the function. This feature is also
* known as [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (/^\$+/.test(key)) {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string. Properties with leading $ characters will be
* stripped since angular uses this notation internally.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string|undefined} JSON-ified string representing `obj`.
*/
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.html('');
} catch(e) {}
// As Per DOM Standards
var TEXT_NODE = 3;
var elemHtml = jqLite('<div>').append(element).html();
try {
return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
elemHtml.
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
} catch(e) {
return lowercase(elemHtml);
}
}
/////////////////////////////////////////////////
/**
* Tries to decode the URI component without throwing an exception.
*
* @private
* @param str value potential URI component to check.
* @returns {boolean} True if `value` can be decoded
* with the decodeURIComponent function.
*/
function tryDecodeURIComponent(value) {
try {
return decodeURIComponent(value);
} catch(e) {
// Ignore any invalid uri component
}
}
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if ( keyValue ) {
key_value = keyValue.split('=');
key = tryDecodeURIComponent(key_value[0]);
if ( isDefined(key) ) {
var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
if (!obj[key]) {
obj[key] = val;
} else if(isArray(obj[key])) {
obj[key].push(val);
} else {
obj[key] = [obj[key],val];
}
}
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
if (isArray(value)) {
forEach(value, function(arrayValue) {
parts.push(encodeUriQuery(key, true) + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
});
} else {
parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
}
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
/**
* @ngdoc directive
* @name ng.directive:ngApp
*
* @element ANY
* @param {angular.Module} ngApp an optional application
* {@link angular.module module} name to load.
*
* @description
*
* Use this directive to auto-bootstrap an application. Only
* one ngApp directive can be used per HTML document. The directive
* designates the root of the application and is typically placed
* at the root of the page.
*
* The first ngApp found in the document will be auto-bootstrapped. To use multiple applications in an
* HTML document you must manually bootstrap them using {@link angular.bootstrap}.
* Applications cannot be nested.
*
* In the example below if the `ngApp` directive would not be placed
* on the `html` element then the document would not be compiled
* and the `{{ 1+2 }}` would not be resolved to `3`.
*
* `ngApp` is the easiest way to bootstrap an application.
*
<doc:example>
<doc:source>
I can add: 1 + 2 = {{ 1+2 }}
</doc:source>
</doc:example>
*
*/
function angularInit(element, bootstrap) {
var elements = [element],
appElement,
module,
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(element) {
element && elements.push(element);
}
forEach(names, function(name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (element.querySelectorAll) {
forEach(element.querySelectorAll('.' + name), append);
forEach(element.querySelectorAll('.' + name + '\\:'), append);
forEach(element.querySelectorAll('[' + name + ']'), append);
}
});
forEach(elements, function(element) {
if (!appElement) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
appElement = element;
module = (match[2] || '').replace(/\s+/g, ',');
} else {
forEach(element.attributes, function(attr) {
if (!appElement && names[attr.name]) {
appElement = element;
module = attr.value;
}
});
}
}
});
if (appElement) {
bootstrap(appElement, module ? [module] : []);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
* They must use {@link api/ng.directive:ngApp ngApp}.
*
* @param {Element} element DOM element which is the root of angular application.
* @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
var doBootstrap = function() {
element = jqLite(element);
if (element.injector()) {
var tag = (element[0] === document) ? 'document' : startingTag(element);
throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
}
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector = createInjector(modules);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
function(scope, element, compile, injector, animate) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
animate.enabled(true);
}]
);
return injector;
};
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return doBootstrap();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
doBootstrap();
};
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator){
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
function bindJQuery() {
// bind to jQuery if present;
jQuery = window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
// Method signature: JQLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
JQLitePatchJQueryRemove('remove', true, true, false);
JQLitePatchJQueryRemove('empty', false, false, false);
JQLitePatchJQueryRemove('html', false, false, true);
} else {
jqLite = JQLite;
}
angular.element = jqLite;
}
/**
* throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* Return the value accessible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accessible by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collection of services, directives, filters, and configuration information.
* `angular.module` is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Optional configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw minErr('$injector')('nomod', "Module '{0}' is not available! You either misspelled the module name " +
"or forgot to load it. If registering a module ensure that you specify the dependencies as the second " +
"argument.", name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#animation
* @methodOf angular.Module
* @param {string} name animation name
* @param {Function} animationFactory Factory function for creating new instance of an animation.
* @description
*
* **NOTE**: animations are take effect only if the **ngAnimate** module is loaded.
*
*
* Defines an animation hook that can be later used with {@link ngAnimate.$animate $animate} service and
* directives that use this service.
*
* <pre>
* module.animation('.animation-name', function($inject1, $inject2) {
* return {
* eventName : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction(element) {
* //code to cancel the animation
* }
* }
* }
* })
* </pre>
*
* See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
* {@link ngAnimate ngAnimate module} for more information.
*/
animation: invokeLater('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
}
}
});
};
});
}
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.2.0rc1', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
minor: 2,
dot: 0,
codeName: 'spooky-giraffe'
};
function publishExternalAPI(angular){
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop':noop,
'bind':bind,
'toJson': toJson,
'fromJson': fromJson,
'identity':identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'$$minErr': minErr,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0}
});
angularModule = setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtml: ngBindHtmlDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngIf: ngIfDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$animate: $AnimateProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sce: $SceProvider,
$sceDelegate: $SceDelegateProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider,
$$urlUtils: $$UrlUtilsProvider
});
}
]);
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
* within a very small footprint, so only a subset of the jQuery API - methods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
* raw DOM references.
*
* ## Angular's jqLite
* Angular's lite version of jQuery provides only the following jQuery methods:
*
* - [addClass()](http://api.jquery.com/addClass/)
* - [after()](http://api.jquery.com/after/)
* - [append()](http://api.jquery.com/append/)
* - [attr()](http://api.jquery.com/attr/)
* - [bind()](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [children()](http://api.jquery.com/children/) - Does not support selectors
* - [clone()](http://api.jquery.com/clone/)
* - [contents()](http://api.jquery.com/contents/)
* - [css()](http://api.jquery.com/css/)
* - [data()](http://api.jquery.com/data/)
* - [eq()](http://api.jquery.com/eq/)
* - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [hasClass()](http://api.jquery.com/hasClass/)
* - [html()](http://api.jquery.com/html/)
* - [next()](http://api.jquery.com/next/) - Does not support selectors
* - [on()](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [off()](http://api.jquery.com/off/) - Does not support namespaces or selectors
* - [parent()](http://api.jquery.com/parent/) - Does not support selectors
* - [prepend()](http://api.jquery.com/prepend/)
* - [prop()](http://api.jquery.com/prop/)
* - [ready()](http://api.jquery.com/ready/)
* - [remove()](http://api.jquery.com/remove/)
* - [removeAttr()](http://api.jquery.com/removeAttr/)
* - [removeClass()](http://api.jquery.com/removeClass/)
* - [removeData()](http://api.jquery.com/removeData/)
* - [replaceWith()](http://api.jquery.com/replaceWith/)
* - [text()](http://api.jquery.com/text/)
* - [toggleClass()](http://api.jquery.com/toggleClass/)
* - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
* - [unbind()](http://api.jquery.com/off/) - Does not support namespaces
* - [val()](http://api.jquery.com/val/)
* - [wrap()](http://api.jquery.com/wrap/)
*
* ## jQuery/jqLite Extras
* Angular also provides the following additional methods and events to both jQuery and jqLite:
*
* ### Events
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
* on all DOM nodes being removed. This can be used to clean up and 3rd party bindings to the DOM
* element before it is removed.
* ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
* element or its parent.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache = JQLite.cache = {},
jqName = JQLite.expando = 'ng-' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, false);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}),
removeEventListenerFn = (window.document.removeEventListener
? function(element, type, fn) {element.removeEventListener(type, fn, false); }
: function(element, type, fn) {element.detachEvent('on' + type, fn); });
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
var jqLiteMinErr = minErr('jqLite');
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
/////////////////////////////////////////////
// jQuery mutation patch
//
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
function JQLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
function removePatch(param) {
var list = filterElems && param ? [this.filter(param)] : [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children;
if (!getterIfNoArguments || param != null) {
while(list.length) {
set = list.shift();
for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
element = jqLite(set[setIndex]);
if (fireEvent) {
element.triggerHandler('$destroy');
} else {
fireEvent = !fireEvent;
}
for(childIndex = 0, childLength = (children = element.children()).length;
childIndex < childLength;
childIndex++) {
list.push(jQuery(children[childIndex]));
}
}
}
}
return originalJqFn.apply(this, arguments);
}
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) != '<') {
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
JQLiteAddNodes(this, div.childNodes);
var fragment = jqLite(document.createDocumentFragment());
fragment.append(this); // detach the elements from the temporary DOM div.
} else {
JQLiteAddNodes(this, element);
}
}
function JQLiteClone(element) {
return element.cloneNode(true);
}
function JQLiteDealoc(element){
JQLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
JQLiteDealoc(children[i]);
}
}
function JQLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
if (isUndefined(type)) {
forEach(events, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete events[type];
});
} else {
forEach(type.split(' '), function(type) {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type] || [], fn);
}
});
}
}
function JQLiteRemoveData(element, name) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (name) {
delete jqCache[expandoId].data[name];
return;
}
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
JQLiteOff(element);
}
delete jqCache[expandoId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
function JQLiteExpandoStore(element, key, value) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
element[jqName] = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {};
}
expandoStore[key] = value;
} else {
return expandoStore && expandoStore[key];
}
}
function JQLiteData(element, key, value) {
var data = JQLiteExpandoStore(element, 'data'),
isSetter = isDefined(value),
keyDefined = !isSetter && isDefined(key),
isSimpleGetter = keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
JQLiteExpandoStore(element, 'data', data = {});
}
if (isSetter) {
data[key] = value;
} else {
if (keyDefined) {
if (isSimpleGetter) {
// don't create data in this case.
return data && data[key];
} else {
extend(data, key);
}
} else {
return data;
}
}
}
function JQLiteHasClass(element, selector) {
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
function JQLiteRemoveClass(element, cssClasses) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
}
function JQLiteAddClass(element, cssClasses) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(cssClass));
}
});
}
}
function JQLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
? elements
: [ elements ];
for(var i=0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
function JQLiteController(element, name) {
return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
}
function JQLiteInheritedData(element, name, value) {
element = jqLite(element);
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if(element[0].nodeType == 9) {
element = element.find('html');
}
while (element.length) {
if ((value = element.data(name)) !== undefined) return value;
element = element.parent();
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
// check if document already is loaded
if (document.readyState === 'complete'){
setTimeout(trigger);
} else {
this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
JQLite(window).on('load', trigger); // fallback to window.onload for others
}
},
toString: function() {
var value = [];
forEach(this, function(e){ value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
BOOLEAN_ELEMENTS[uppercase(value)] = true;
});
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
}
forEach({
data: JQLiteData,
inheritedData: JQLiteInheritedData,
scope: function(element) {
return JQLiteInheritedData(element, '$scope');
},
controller: JQLiteController ,
injector: function(element) {
return JQLiteInheritedData(element, '$injector');
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
hasClass: JQLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
var val;
if (msie <= 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why
val = element.currentStyle && element.currentStyle[name];
if (val === '') val = 'auto';
}
val = val || element.style[name];
if (msie <= 8) {
// jquery weirdness :-/
val = (val === '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value){
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name)|| noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: (function() {
var NODE_TYPE_TEXT_PROPERTY = [];
if (msie < 9) {
NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
} else {
NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
}
getText.$dv = '';
return getText;
function getText(element, value) {
var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType]
if (isUndefined(value)) {
return textProp ? element[textProp] : '';
}
element[textProp] = value;
}
})(),
val: function(element, value) {
if (isUndefined(value)) {
if (nodeName_(element) === 'SELECT' && element.multiple) {
var result = [];
forEach(element.options, function (option) {
if (option.selected) {
result.push(option.value || option.text);
}
});
return result.length === 0 ? null : result;
}
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
JQLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
}
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
// JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for(i=0; i < this.length; i++) {
if (fn === JQLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
var value = fn.$dv;
// Only if we have $dv do we iterate over all, otherwise it is just the first element.
var jj = value == undefined ? Math.min(this.length, 1) : this.length;
for (var j = 0; j < jj; j++) {
var nodeValue = fn(this[j], arg1, arg2);
value = value ? value + nodeValue : nodeValue;
}
return value;
}
} else {
// we are a write, so apply to all children
for(i=0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
};
});
function createEventHandler(element, events) {
var eventHandler = function (event, type) {
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation = function() {
event.cancelBubble = true; //ie
};
}
if (!event.target) {
event.target = event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent = event.preventDefault;
event.preventDefault = function() {
event.defaultPrevented = true;
prevent.call(event);
};
event.defaultPrevented = false;
}
event.isDefaultPrevented = function() {
return event.defaultPrevented || event.returnValue == false;
};
forEach(events[type || event.type], function(fn) {
fn.call(element, event);
});
// Remove monkey-patched methods (IE),
// as they would cause memory leaks in IE8.
if (msie <= 8) {
// IE7/8 does not allow to delete property on native object
event.preventDefault = null;
event.stopPropagation = null;
event.isDefaultPrevented = null;
} else {
// It shouldn't affect normal browsers (native methods are defined on prototype).
delete event.preventDefault;
delete event.stopPropagation;
delete event.isDefaultPrevented;
}
};
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: JQLiteRemoveData,
dealoc: JQLiteDealoc,
on: function onFn(element, type, fn, unsupported){
if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!events) JQLiteExpandoStore(element, 'events', events = {});
if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
forEach(type.split(' '), function(type){
var eventFns = events[type];
if (!eventFns) {
if (type == 'mouseenter' || type == 'mouseleave') {
var contains = document.body.contains || document.body.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
events[type] = [];
// Refer to jQuery's implementation of mouseenter & mouseleave
// Read about mouseenter and mouseleave:
// http://www.quirksmode.org/js/events_mouse.html#link8
var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
onFn(element, eventmap[type], function(event) {
var target = this, related = event.relatedTarget;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !contains(target, related)) ){
handle(event, type);
}
});
} else {
addEventListenerFn(element, type, handle);
events[type] = [];
}
eventFns = events[type]
}
eventFns.push(fn);
});
},
off: JQLiteOff,
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
JQLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element){
if (element.nodeType === 1)
children.push(element);
});
return children;
},
contents: function(element) {
return element.childNodes || [];
},
append: function(element, node) {
forEach(new JQLite(node), function(child){
if (element.nodeType === 1 || element.nodeType === 11) {
element.appendChild(child);
}
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
element.insertBefore(child, index);
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode)[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: function(element) {
JQLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
forEach(new JQLite(newElement), function(node){
parent.insertBefore(node, index.nextSibling);
index = node;
});
},
addClass: JQLiteAddClass,
removeClass: JQLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition = !JQLiteHasClass(element, selector);
}
(condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
next: function(element) {
if (element.nextElementSibling) {
return element.nextElementSibling;
}
// IE8 doesn't have nextElementSibling
var elm = element.nextSibling;
while (elm != null && elm.nodeType !== 1) {
elm = elm.nextSibling;
}
return elm;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: JQLiteClone,
triggerHandler: function(element, eventName, eventData) {
var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName];
eventData = eventData || {
preventDefault: noop,
stopPropagation: noop
};
forEach(eventFns, function(fn) {
fn.call(element, eventData);
});
}
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2, arg3) {
var value;
for(var i=0; i < this.length; i++) {
if (value == undefined) {
value = fn(this[i], arg1, arg2, arg3);
if (value !== undefined) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
}
}
return value == undefined ? this : value;
};
// bind legacy bind/unbind to on/off
JQLite.prototype.bind = JQLite.prototype.on;
JQLite.prototype.unbind = JQLite.prototype.off;
});
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj) {
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof (key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
key = obj.$$hashKey = nextUid();
}
} else {
key = obj;
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array){
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key)] = value;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key)];
delete this[key];
return value;
}
};
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
*
* @example
* Typical usage
* <pre>
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* </pre>
*/
/**
* @ngdoc overview
* @name AUTO
* @description
*
* Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, underscore, name){
$inject.push(name);
});
});
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc object
* @name AUTO.$injector
* @function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link AUTO.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* <pre>
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* </pre>
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following are all valid ways of annotating function with injection arguments and are equivalent.
*
* <pre>
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* </pre>
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
* parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
* tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name AUTO.$injector#get
* @methodOf AUTO.$injector
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name AUTO.$injector#invoke
* @methodOf AUTO.$injector
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!function} fn The function to invoke. The function arguments come form the function annotation.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name AUTO.$injector#has
* @methodOf AUTO.$injector
*
* @description
* Allows the user to query if the particular service exist.
*
* @param {string} Name of the service to query.
* @returns {boolean} returns true if injector has given service.
*/
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
* Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
* all of the arguments to the constructor function as specified by the constructor annotation.
*
* @param {function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name AUTO.$injector#annotate
* @methodOf AUTO.$injector
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is used by the injector
* to determine which services need to be injected into the function when the function is invoked. There are three
* ways in which the function can be annotated with the needed dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
* the function into a string using `toString()` method and extracting the argument names.
* <pre>
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* This method does not work with code minification / obfuscation. For this reason the following annotation strategies
* are supported.
*
* # The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
* services to be injected into the function.
* <pre>
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController.$inject = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
* inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
* minification is a better choice:
*
* <pre>
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* </pre>
*
* @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
* above.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc object
* @name AUTO.$provide
*
* @description
*
* Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
* The providers share the same name as the instance they create with `Provider` suffixed to them.
*
* A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
* a service. The Provider can have additional methods which would allow for configuration of the provider.
*
* <pre>
* function GreetProvider() {
* var salutation = 'Hello';
*
* this.salutation = function(text) {
* salutation = text;
* };
*
* this.$get = function() {
* return function (name) {
* return salutation + ' ' + name + '!';
* };
* };
* }
*
* describe('Greeter', function(){
*
* beforeEach(module(function($provide) {
* $provide.provider('greet', GreetProvider);
* }));
*
* it('should greet', inject(function(greet) {
* expect(greet('angular')).toEqual('Hello angular!');
* }));
*
* it('should allow configuration of salutation', function() {
* module(function(greetProvider) {
* greetProvider.salutation('Ahoj');
* });
* inject(function(greet) {
* expect(greet('angular')).toEqual('Ahoj angular!');
* });
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if only `$get` method is required.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
* `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* A short hand for registering service of given class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if the `$get` method is a constant.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
* into configuration function (other modules) and it is not interceptable by
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Decoration of service, allows the decorator to intercept the service instance creation. The
* returned instance may be the original instance, or a new instance which delegates to the
* original instance.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instantiated. The function is called using the {@link AUTO.$injector#invoke
* injector.invoke} method and is therefore fully injectable. Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*/
function createInjector(modulesToLoad) {
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache, function() {
throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
})),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(servicename) {
var provider = providerInjector.get(servicename + providerSuffix);
return instanceInjector.invoke(provider.$get, provider);
}));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
}
}
function provider(name, provider_) {
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, value) { return factory(name, valueFn(value)); }
function constant(name, value) {
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad){
var runBlocks = [];
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
try {
if (isString(module)) {
var moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
var invokeArgs = invokeQueue[i],
provider = providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
} else if (isFunction(module)) {
runBlocks.push(providerInjector.invoke(module));
} else if (isArray(module)) {
runBlocks.push(providerInjector.invoke(module));
} else {
assertArgFn(module, 'module');
}
} catch (e) {
if (isArray(module)) {
module = module[module.length - 1];
}
if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
// Safari & FF's stack traces don't contain error.message content unlike those of Chrome and IE
// So if stack doesn't contain message, we create a new string that contains both.
// Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
e = e.message + '\n' + e.stack;
}
throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", module, e.stack || e.message || e);
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals){
var args = [],
$inject = annotate(fn),
length, i,
key;
for(i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key);
}
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key)
);
}
if (!fn.$inject) {
// this means that we must be an array.
fn = fn[length];
}
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
switch (self ? -1 : args.length) {
case 0: return fn();
case 1: return fn(args[0]);
case 2: return fn(args[0], args[1]);
case 3: return fn(args[0], args[1], args[2]);
case 4: return fn(args[0], args[1], args[2], args[3]);
case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
default: return fn.apply(self, args);
}
}
function instantiate(Type, locals) {
var Constructor = function() {},
instance, returnedValue;
// Check if Type is annotated and use just the given function at n-1 as parameter
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
returnedValue = invoke(Type, instance, locals);
return isObject(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate,
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
}
/**
* @ngdoc function
* @name ng.$anchorScroll
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks current value of `$location.hash()` and scroll to related element,
* according to rules specified in
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
*
* It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// helper function to get first anchor from a NodeList
// can't use filter.filter, as it accepts only instances of Array
// and IE can't convert NodeList to an array using [].slice
// TODO(vojta): use filter if we change it to accept lists as well
function getFirstAnchor(list) {
var result = null;
forEach(list, function(element) {
if (!result && lowercase(element.nodeName) === 'a') result = element;
});
return result;
}
function scroll() {
var hash = $location.hash(), elm;
// empty hash, scroll to the top of the page
if (!hash) $window.scrollTo(0, 0);
// element with given id
else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') $window.scrollTo(0, 0);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $location.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
function autoScrollWatchAction() {
$rootScope.$evalAsync(scroll);
});
}
return scroll;
}];
}
var $animateMinErr = minErr('$animate');
/**
* @ngdoc object
* @name ng.$animateProvider
*
* @description
* Default implementation of $animate that doesn't perform any animations, instead just synchronously performs DOM
* updates and calls done() callbacks.
*
* In order to enable animations the ngAnimate module has to be loaded.
*
* To see the functional implementation check out src/ngAnimate/animate.js
*/
var $AnimateProvider = ['$provide', function($provide) {
this.$$selectors = {};
/**
* @ngdoc function
* @name ng.$animateProvider#register
* @methodOf ng.$animateProvider
*
* @description
* Registers a new injectable animation factory function. The factory function produces the animation object which
* contains callback functions for each event that is expected to be animated.
*
* * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` must be called once the
* element animation is complete. If a function is returned then the animation service will use this function to
* cancel the animation whenever a cancel event is triggered.
*
*
*<pre>
* return {
* eventFn : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction() {
* //code to cancel the animation
* }
* }
* }
*</pre>
*
* @param {string} name The name of the animation.
* @param {function} factory The factory function that will be executed to return the animation object.
*/
this.register = function(name, factory) {
var key = name + '-animation';
if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
"Expecting class selector starting with '.' got '{0}'.", name);
this.$$selectors[name.substr(1)] = key;
$provide.factory(key, factory);
};
this.$get = ['$timeout', function($timeout) {
/**
* @ngdoc object
* @name ng.$animate
*
* @description
* The $animate service provides rudimentary DOM manipulation functions to insert, remove, move elements within
* the DOM as well as adding and removing classes. This service is the core service used by the ngAnimate $animator
* service which provides high-level animation hooks for CSS and JavaScript.
*
* $animate is available in the AngularJS core, however, the ngAnimate module must be included to enable full out
* animation support. Otherwise, $animate will only perform simple DOM manipulation operations.
*
* To learn more about enabling animation support, click here to visit the {@link ngAnimate ngAnimate module page}
* as well as the {@link ngAnimate.$animate ngAnimate $animate service page}.
*/
return {
/**
* @ngdoc function
* @name ng.$animate#enter
* @methodOf ng.$animate
* @function
*
* @description
* Inserts the element into the DOM either after the `after` element or within the `parent` element. Once complete,
* the done() callback will be fired (if provided).
*
* @param {jQuery/jqLite element} element the element which will be inserted into the DOM
* @param {jQuery/jqLite element} parent the parent element which will append the element as a child (if the after element is not present)
* @param {jQuery/jqLite element} after the sibling element which will append the element after itself
* @param {function=} done callback function that will be called after the element has been inserted into the DOM
*/
enter : function(element, parent, after, done) {
var afterNode = after && after[after.length - 1];
var parentNode = parent && parent[0] || afterNode && afterNode.parentNode;
// IE does not like undefined so we have to pass null.
var afterNextSibling = (afterNode && afterNode.nextSibling) || null;
forEach(element, function(node) {
parentNode.insertBefore(node, afterNextSibling);
});
$timeout(done || noop, 0, false);
},
/**
* @ngdoc function
* @name ng.$animate#leave
* @methodOf ng.$animate
* @function
*
* @description
* Removes the element from the DOM. Once complete, the done() callback will be fired (if provided).
*
* @param {jQuery/jqLite element} element the element which will be removed from the DOM
* @param {function=} done callback function that will be called after the element has been removed from the DOM
*/
leave : function(element, done) {
element.remove();
$timeout(done || noop, 0, false);
},
/**
* @ngdoc function
* @name ng.$animate#move
* @methodOf ng.$animate
* @function
*
* @description
* Moves the position of the provided element within the DOM to be placed either after the `after` element or inside of the `parent` element.
* Once complete, the done() callback will be fired (if provided).
*
* @param {jQuery/jqLite element} element the element which will be moved around within the DOM
* @param {jQuery/jqLite element} parent the parent element where the element will be inserted into (if the after element is not present)
* @param {jQuery/jqLite element} after the sibling element where the element will be positioned next to
* @param {function=} done the callback function (if provided) that will be fired after the element has been moved to it's new position
*/
move : function(element, parent, after, done) {
// Do not remove element before insert. Removing will cause data associated with the
// element to be dropped. Insert will implicitly do the remove.
this.enter(element, parent, after, done);
},
/**
* @ngdoc function
* @name ng.$animate#addClass
* @methodOf ng.$animate
* @function
*
* @description
* Adds the provided className CSS class value to the provided element. Once complete, the done() callback will be fired (if provided).
*
* @param {jQuery/jqLite element} element the element which will have the className value added to it
* @param {string} className the CSS class which will be added to the element
* @param {function=} done the callback function (if provided) that will be fired after the className value has been added to the element
*/
addClass : function(element, className, done) {
className = isString(className) ?
className :
isArray(className) ? className.join(' ') : '';
element.addClass(className);
$timeout(done || noop, 0, false);
},
/**
* @ngdoc function
* @name ng.$animate#removeClass
* @methodOf ng.$animate
* @function
*
* @description
* Removes the provided className CSS class value from the provided element. Once complete, the done() callback will be fired (if provided).
*
* @param {jQuery/jqLite element} element the element which will have the className value removed from it
* @param {string} className the CSS class which will be removed from the element
* @param {function=} done the callback function (if provided) that will be fired after the className value has been removed from the element
*/
removeClass : function(element, className, done) {
className = isString(className) ?
className :
isArray(className) ? className.join(' ') : '';
element.removeClass(className);
$timeout(done || noop, 0, false);
},
enabled : noop
};
}];
}];
/**
* ! This is a private undocumented service !
*
* @name ng.$browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while(outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn){ pollFn(); });
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @name ng.$browser#addPollFn
* @methodOf ng.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn){ pollFn(); });
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href,
baseElement = document.find('base'),
replacedUrl = null;
/**
* @name ng.$browser#url
* @methodOf ng.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
// setter
if (url) {
if (lastBrowserUrl == url) return;
lastBrowserUrl = url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else {
history.pushState(null, '', url);
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
baseElement.attr('href', baseElement.attr('href'));
}
} else {
if (replace) {
location.replace(url);
replacedUrl = url;
} else {
location.href = url;
replacedUrl = null;
}
}
return self;
// getter
} else {
// - the replacedUrl is a workaround for an IE8-9 issue with location.replace method that doesn't update
// location.href synchronously
// - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return replacedUrl || location.href.replace(/%27/g,"'");
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @name ng.$browser#onUrlChange
* @methodOf ng.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=}
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : '';
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
var cookiePath = self.baseHref();
/**
* @name ng.$browser#cookies
* @methodOf ng.$browser
*
* @param {string=} name Cookie name
* @param {string=} value Cookie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
// per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
// - 300 cookies
// - 20 cookies per unique domain
// - 4096 bytes per cookie
if (cookieLength > 4096) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
cookieLength + " > 4096 bytes)!");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
var name = unescape(cookie.substring(0, index));
// the first value that is seen for a cookie is the most
// specific one. values for the same cookie name that
// follow are for less specific paths.
if (lastCookies[name] === undefined) {
lastCookies[name] = unescape(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
}
};
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
* @param {function()} fn A function, who's execution should be deferred.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchronously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name ng.$browser#defer.cancel
* @methodOf ng.$browser.defer
*
* @description
* Cancels a deferred task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider(){
this.$get = ['$window', '$log', '$sniffer', '$document',
function( $window, $log, $sniffer, $document){
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc object
* @name ng.$cacheFactory
*
* @description
* Factory that constructs cache objects and gives access to them.
*
* <pre>
*
* var cache = $cacheFactory('cacheId');
* expect($cacheFactory.get('cacheId')).toBe(cache);
* expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
*
* cache.put("key", "value");
* cache.put("another key", "another value");
*
* expect(cache.info()).toEqual({id: 'cacheId', size: 2}); // Since we've specified no options on creation
*
* </pre>
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
*
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
return caches[cacheId] = {
put: function(key, value) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
return value;
},
get: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
return data[key];
},
remove: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
delete data[key];
size--;
},
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
/**
* @ngdoc method
* @name ng.$cacheFactory#info
* @methodOf ng.$cacheFactory
*
* @description
* Get information about all the of the caches that have been created
*
* @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
*/
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
/**
* @ngdoc method
* @name ng.$cacheFactory#get
* @methodOf ng.$cacheFactory
*
* @description
* Get access to a cache object by the `cacheId` used when it was created.
*
* @param {string} cacheId Name or id of a cache to access.
* @returns {object} Cache object identified by the cacheId or undefined if no such cache.
*/
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* The first time a template is used, it is loaded in the template cache for quick retrieval. You can
* load templates directly into the cache in a `script` tag, or by consuming the `$templateCache`
* service directly.
*
* Adding via the `script` tag:
* <pre>
* <html ng-app>
* <head>
* <script type="text/ng-template" id="templateId.html">
* This is the content of the template
* </script>
* </head>
* ...
* </html>
* </pre>
*
* **Note:** the `script` tag containing the template does not need to be included in the `head` of the document, but
* it must be below the `ng-app` definition.
*
* Adding via the $templateCache service:
*
* <pre>
* var myApp = angular.module('myApp', []);
* myApp.run(function($templateCache) {
* $templateCache.put('templateId.html', 'This is the content of the template');
* });
* </pre>
*
* To retrieve the template later, simply use it in your HTML:
* <pre>
* <div ng-include=" 'templateId.html' "></div>
* </pre>
*
* or get it via Javascript:
* <pre>
* $templateCache.get('templateId.html')
* </pre>
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
*
* The compilation is a process of walking the DOM tree and trying to match DOM elements to
* {@link ng.$compileProvider#directive directives}. For each match it
* executes corresponding template function and collects the
* instance functions into a single template function which is then returned.
*
* The template function can then be used once to produce the view or as it is the case with
* {@link ng.directive:ngRepeat repeater} many-times, in which
* case each call results in a view that is a DOM clone of the original template.
*
<doc:example module="compile">
<doc:source>
<script>
// declare a new module, and inject the $compileProvider
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
function Ctrl($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}
</script>
<div ng-controller="Ctrl">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</doc:source>
<doc:scenario>
it('should auto compile', function() {
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
expect(element('div[compile]').text()).toBe('Angular!');
});
</doc:scenario>
</doc:example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
* @param {number} maxPriority only apply directives lower then given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* Calling the linking function returns the element of the template. It is either the original element
* passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var element = $compile('<p>{{total}}</p>')(scope);
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var templateHTML = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
var $compileMinErr = minErr('$compile');
/**
* @ngdoc service
* @name ng.$compileProvider
* @function
*
* @description
*/
$CompileProvider.$inject = ['$provide'];
function $CompileProvider($provide) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/,
imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;
// Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
// The assumption is that future DOM event attribute names will begin with
// 'on' and be composed of only English letters.
var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]*|formaction)$/;
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directive with the compiler.
*
* @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
* <code>ng-bind</code>).
* @param {function|Array} directiveFactory An injectable directive factory function. See {@link guide/directive} for more
* info.
* @returns {ng.$compileProvider} Self for chaining.
*/
this.directive = function registerDirective(name, directiveFactory) {
if (isString(name)) {
assertArg(directiveFactory, 'directiveFactory');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'A';
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
/**
* @ngdoc function
* @name ng.$compileProvider#aHrefSanitizationWhitelist
* @methodOf ng.$compileProvider
* @function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.aHrefSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
aHrefSanitizationWhitelist = regexp;
return this;
}
return aHrefSanitizationWhitelist;
};
/**
* @ngdoc function
* @name ng.$compileProvider#imgSrcSanitizationWhitelist
* @methodOf ng.$compileProvider
* @function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during img[src] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into an
* absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` regular
* expression. If a match is found, the original url is written into the dom. Otherwise, the
* absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.imgSrcSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
imgSrcSanitizationWhitelist = regexp;
return this;
}
return imgSrcSanitizationWhitelist;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
'$controller', '$rootScope', '$document', '$sce', '$$urlUtils', '$animate',
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
$controller, $rootScope, $document, $sce, $$urlUtils, $animate) {
var Attributes = function(element, attr) {
this.$$element = element;
this.$attr = attr || {};
};
Attributes.prototype = {
$normalize: directiveNormalize,
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$addClass
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Adds the CSS class value specified by the classVal parameter to the element. If animations
* are enabled then an animation will be triggered for the class addition.
*
* @param {string} classVal The className value that will be added to the element
*/
$addClass : function(classVal) {
if(classVal && classVal.length > 0) {
$animate.addClass(this.$$element, classVal);
}
},
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$removeClass
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Removes the CSS class value specified by the classVal parameter from the element. If animations
* are enabled then an animation will be triggered for the class removal.
*
* @param {string} classVal The className value that will be removed from the element
*/
$removeClass : function(classVal) {
if(classVal && classVal.length > 0) {
$animate.removeClass(this.$$element, classVal);
}
},
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
//special case for class attribute addition + removal
//so that class changes can tap into the animation
//hooks provided by the $animate service
if(key == 'class') {
value = value || '';
var current = this.$$element.attr('class') || '';
this.$removeClass(tokenDifference(current, value).join(' '));
this.$addClass(tokenDifference(value, current).join(' '));
} else {
var booleanKey = getBooleanAttrName(this.$$element[0], key),
normalizedVal,
nodeName;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
nodeName = nodeName_(this.$$element);
// sanitize a[href] and img[src] values
if ((nodeName === 'A' && key === 'href') ||
(nodeName === 'IMG' && key === 'src')) {
// NOTE: $$urlUtils.resolve() doesn't support IE < 8 so we don't sanitize for that case.
if (!msie || msie >= 8 ) {
normalizedVal = $$urlUtils.resolve(value);
if (normalizedVal !== '') {
if ((key === 'href' && !normalizedVal.match(aHrefSanitizationWhitelist)) ||
(key === 'src' && !normalizedVal.match(imgSrcSanitizationWhitelist))) {
this[key] = value = 'unsafe:' + normalizedVal;
}
}
}
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
}
// fire observers
var $$observers = this.$$observers;
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
function tokenDifference(str1, str2) {
var values = [],
tokens1 = str1.split(/\s+/),
tokens2 = str2.split(/\s+/);
outer:
for(var i=0;i<tokens1.length;i++) {
var token = tokens1[i];
for(var j=0;j<tokens2.length;j++) {
if(token == tokens2[j]) continue outer;
}
values.push(token);
}
return values;
};
},
/**
* Observe an interpolated attribute.
* The observer will never be called, if given attribute is not interpolated.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(*)} fn Function that will be called whenever the attribute value changes.
* @returns {function(*)} the `fn` Function passed in.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = {})),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return fn;
}
};
var urlSanitizationNode = $document[0].createElement('a'),
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
? identity
: function denormalizeTemplate(template) {
return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
},
NG_ATTR_BINDING = /^ngAttr[A-Z]/;
return compile;
//================================
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective) {
if (!($compileNodes instanceof jqLite)) {
// jquery always rewraps, whereas we need to preserve the original selector so that we can modify it.
$compileNodes = jqLite($compileNodes);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNodes, function(node, index){
if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
$compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
}
});
var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective);
return function publicLinkFn(scope, cloneConnectFn){
assertArg(scope, 'scope');
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
var $linkNode = cloneConnectFn
? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
: $compileNodes;
// Attach scope only to non-text nodes.
for(var i = 0, ii = $linkNode.length; i<ii; i++) {
var node = $linkNode[i];
if (node.nodeType == 1 /* element */ || node.nodeType == 9 /* document */) {
$linkNode.eq(i).data('$scope', scope);
}
}
safeAddClass($linkNode, 'ng-scope');
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
return $linkNode;
};
}
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch(e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes or NodeList to compile
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the
* rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} max directive priority
* @returns {?function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective) {
var linkFns = [],
nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
for(var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, i == 0 ? maxPriority : undefined, ignoreDirective);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
: null;
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !nodeList[i].childNodes || !nodeList[i].childNodes.length)
? null
: compileNodes(nodeList[i].childNodes,
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
linkFns.push(nodeLinkFn);
linkFns.push(childLinkFn);
linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn, i, ii, n;
// copy nodeList so that linking doesn't break due to live list updates.
var stableNodeList = [];
for (i = 0, ii = nodeList.length; i < ii; i++) {
stableNodeList.push(nodeList[i]);
}
for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
node = stableNodeList[n];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new(isObject(nodeLinkFn.scope));
jqLite(node).data('$scope', childScope);
} else {
childScope = scope;
}
childTranscludeFn = nodeLinkFn.transclude;
if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
nodeLinkFn(childLinkFn, childScope, node, $rootElement,
(function(transcludeFn) {
return function(cloneFn) {
var transcludeScope = scope.$new();
transcludeScope.$$transcluded = true;
return transcludeFn(transcludeScope, cloneFn).
on('$destroy', bind(transcludeScope, transcludeScope.$destroy));
};
})(childTranscludeFn || transcludeFn)
);
} else {
nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
}
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
}
}
}
}
/**
* Looks for directives on the given node and adds them to the directive collection which is
* sorted.
*
* @param node Node to search.
* @param directives An array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs The shared attrs object which is used to populate the normalized attributes.
* @param {number=} maxPriority Max directive priority.
*/
function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch(nodeType) {
case 1: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
// iterate over the attributes
for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
var attrStartName;
var attrEndName;
var index;
attr = nAttrs[j];
if (!msie || msie >= 8 || attr.specified) {
name = attr.name;
// support ngAttr attribute binding
ngAttrName = directiveNormalize(name);
if (NG_ATTR_BINDING.test(ngAttrName)) {
name = ngAttrName.substr(6).toLowerCase();
}
if ((index = ngAttrName.lastIndexOf('Start')) != -1 && index == ngAttrName.length - 5) {
attrStartName = name;
attrEndName = name.substr(0, name.length - 5) + 'end';
name = name.substr(0, name.length - 6);
}
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
attrs[nName] = value = trim((msie && name == 'href')
? decodeURIComponent(node.getAttribute(name, 2))
: attr.value);
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
addAttrInterpolateDirective(node, directives, value, nName);
addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, attrEndName);
}
}
// use class as directive
className = node.className;
if (isString(className) && className !== '') {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case 3: /* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case 8: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Given a node with an directive-start it collects all of the siblings until it find directive-end.
* @param node
* @param attrStart
* @param attrEnd
* @returns {*}
*/
function groupScan(node, attrStart, attrEnd) {
var nodes = [];
var depth = 0;
if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
var startNode = node;
do {
if (!node) {
throw $compileMinErr('uterdir', "Unterminated attribute, found '{0}' but no matching '{1}' found.", attrStart, attrEnd);
}
if (node.nodeType == 1 /** Element **/) {
if (node.hasAttribute(attrStart)) depth++;
if (node.hasAttribute(attrEnd)) depth--;
}
nodes.push(node);
node = node.nextSibling;
} while (depth > 0);
} else {
nodes.push(node);
}
return jqLite(nodes);
}
/**
* Wrapper for linking function which converts normal linking function into a grouped
* linking function.
* @param linkFn
* @param attrStart
* @param attrEnd
* @returns {Function}
*/
function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
return function(scope, element, attrs, controllers) {
element = groupScan(element[0], attrStart, attrEnd);
return linkFn(scope, element, attrs, controllers);
}
}
/**
* Once the directives have been collected, their compile functions are executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached.
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {JQLite} jqCollection If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace nodes on it.
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection, originalReplaceDirective) {
var terminalPriority = -Number.MAX_VALUE,
preLinkFns = [],
postLinkFns = [],
newScopeDirective = null,
newIsolateScopeDirective = null,
templateDirective = null,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
transcludeDirective,
replaceDirective = originalReplaceDirective,
childTranscludeFn = transcludeFn,
controllerDirectives,
linkFn,
directiveValue;
// executes all directives on the current element
for(var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
var attrStart = directive.$$start;
var attrEnd = directive.$$end;
// collect multiblock sections
if (attrStart) {
$compileNode = groupScan(compileNode, attrStart, attrEnd)
}
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode);
if (isObject(directiveValue)) {
safeAddClass($compileNode, 'ng-isolate-scope');
newIsolateScopeDirective = directive;
}
safeAddClass($compileNode, 'ng-scope');
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (directiveValue = directive.controller) {
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
transcludeDirective = directive;
terminalPriority = directive.priority;
if (directiveValue == 'element') {
$template = groupScan(compileNode, attrStart, attrEnd)
$compileNode = templateAttrs.$$element =
jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' '));
compileNode = $compileNode[0];
replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority,
replaceDirective && replaceDirective.name);
} else {
$template = jqLite(JQLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if (directive.template) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
directiveValue = (isFunction(directive.template))
? directive.template($compileNode, templateAttrs)
: directive.template;
directiveValue = denormalizeTemplate(directiveValue);
if (directive.replace) {
replaceDirective = directive;
$template = jqLite('<div>' +
trim(directiveValue) +
'</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", directiveName, '');
}
replaceWith(jqCollection, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that were already applied and those that weren't
// - collect directives from the template, add them to the second group and sort them
// - append the second group with new directives to the first group
directives = directives.concat(
collectDirectives(
compileNode,
directives.splice(i + 1, directives.length - (i + 1)),
newTemplateAttrs
)
);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
if (directive.replace) {
replaceDirective = directive;
}
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
nodeLinkFn, $compileNode, templateAttrs, jqCollection, childTranscludeFn);
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn, attrStart, attrEnd);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post, attrStart, attrEnd) {
if (pre) {
if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
pre.require = directive.require;
preLinkFns.push(pre);
}
if (post) {
if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
post.require = directive.require;
postLinkFns.push(post);
}
}
function getControllers(require, $element) {
var value, retrievalMethod = 'data', optional = false;
if (isString(require)) {
while((value = require.charAt(0)) == '^' || value == '?') {
require = require.substr(1);
if (value == '^') {
retrievalMethod = 'inheritedData';
}
optional = optional || value == '?';
}
value = $element[retrievalMethod]('$' + require + 'Controller');
if (!value && !optional) {
throw $compileMinErr('ctreq', "Controller '{0}', required by directive '{1}', can't be found!", require, directiveName);
}
return value;
} else if (isArray(require)) {
value = [];
forEach(require, function(require) {
value.push(getControllers(require, $element));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
var attrs, $element, i, ii, linkFn, controller;
if (compileNode === linkNode) {
attrs = templateAttrs;
} else {
attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
}
$element = attrs.$$element;
if (newIsolateScopeDirective) {
var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
var parentScope = scope.$parent || scope;
forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
var match = definition.match(LOCAL_REGEXP) || [],
attrName = match[3] || scopeName,
optional = (match[2] == '?'),
mode = match[1], // @, =, or &
lastValue,
parentGet, parentSet;
scope.$$isolateBindings[scopeName] = mode + attrName;
switch (mode) {
case '@': {
attrs.$observe(attrName, function(value) {
scope[scopeName] = value;
});
attrs.$$observers[attrName].$$scope = parentScope;
if( attrs[attrName] ) {
// If the attribute has been provided then we trigger an interpolation to ensure the value is there for use in the link fn
scope[scopeName] = $interpolate(attrs[attrName])(parentScope);
}
break;
}
case '=': {
if (optional && !attrs[attrName]) {
return;
}
parentGet = $parse(attrs[attrName]);
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] = parentGet(parentScope);
throw $compileMinErr('nonassign', "Expression '{0}' used with directive '{1}' is non-assignable!",
attrs[attrName], newIsolateScopeDirective.name);
};
lastValue = scope[scopeName] = parentGet(parentScope);
scope.$watch(function parentValueWatch() {
var parentValue = parentGet(parentScope);
if (parentValue !== scope[scopeName]) {
// we are out of sync and need to copy
if (parentValue !== lastValue) {
// parent changed and it has precedence
lastValue = scope[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope, parentValue = lastValue = scope[scopeName]);
}
}
return parentValue;
});
break;
}
case '&': {
parentGet = $parse(attrs[attrName]);
scope[scopeName] = function(locals) {
return parentGet(parentScope, locals);
};
break;
}
default: {
throw $compileMinErr('iscp', "Invalid isolate scope definition for directive '{0}'. Definition: {... {1}: '{2}' ...}",
newIsolateScopeDirective.name, scopeName, definition);
}
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
}, controllerInstance;
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
controllerInstance = $controller(controller, locals);
$element.data(
'$' + directive.name + 'Controller',
controllerInstance);
if (directive.controllerAs) {
locals.$scope[directive.controllerAs] = controllerInstance;
}
});
}
// PRELINKING
for(i = 0, ii = preLinkFns.length; i < ii; i++) {
try {
linkFn = preLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for(i = 0, ii = postLinkFns.length; i < ii; i++) {
try {
linkFn = postLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, endAttrName) {
if (name === ignoreDirective) return null;
var match = null;
if (hasDirectives.hasOwnProperty(name)) {
for(var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i<ii; i++) {
try {
directive = directives[i];
if ( (maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
if (startAttrName) {
directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
}
tDirectives.push(directive);
match = directive;
}
} catch(e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key]) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
$rootElement, childTranscludeFn) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
// The fact that we have to copy and patch the directive seems wrong!
derivedSyncDirective = extend({}, origAsyncDirective, {
controller: null, templateUrl: null, transclude: null, scope: null, replace: null
}),
templateUrl = (isFunction(origAsyncDirective.templateUrl))
? origAsyncDirective.templateUrl($compileNode, tAttrs)
: origAsyncDirective.templateUrl;
$compileNode.html('');
$http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
content = denormalizeTemplate(content);
if (origAsyncDirective.replace) {
$template = jqLite('<div>' + trim(content) + '</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}",
origAsyncDirective.name, templateUrl);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
collectDirectives(compileNode, directives, tempTemplateAttrs);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn, $compileNode, origAsyncDirective);
forEach($rootElement, function(node, i) {
if (node == compileNode) {
$rootElement[i] = $compileNode[0];
}
});
afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
while(linkQueue.length) {
var scope = linkQueue.shift(),
beforeTemplateLinkNode = linkQueue.shift(),
linkRootElement = linkQueue.shift(),
controller = linkQueue.shift(),
linkNode = $compileNode[0];
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode = JQLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
}
afterTemplateNodeLinkFn(
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller),
scope, linkNode, $rootElement, controller
);
}
linkQueue = null;
}).
error(function(response, code, headers, config) {
throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
if (linkQueue) {
linkQueue.push(scope);
linkQueue.push(node);
linkQueue.push(rootElement);
linkQueue.push(controller);
} else {
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
}, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
return b.priority - a.priority;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
if (previousDirective) {
throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
previousDirective.name, directive.name, what, startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: valueFn(function textInterpolateLinkFn(scope, node) {
var parent = node.parent(),
bindings = parent.data('$binding') || [];
bindings.push(interpolateFn);
safeAddClass(parent.data('$binding', bindings), 'ng-binding');
scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
node[0].nodeValue = value;
});
})
});
}
}
function getTrustedContext(node, attrNormalizedName) {
// maction[xlink:href] can source SVG. It's not limited to <maction>.
if (attrNormalizedName == "xlinkHref" ||
(nodeName_(node) != "IMG" && (attrNormalizedName == "src" ||
attrNormalizedName == "ngSrc"))) {
return $sce.RESOURCE_URL;
}
}
function addAttrInterpolateDirective(node, directives, value, name) {
var interpolateFn = $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
if (name === "multiple" && nodeName_(node) === "SELECT") {
throw $compileMinErr("selmulti", "Binding to the 'multiple' attribute is not supported. Element: {0}",
startingTag(node));
}
directives.push({
priority: 100,
compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
throw $compileMinErr('nodomevents',
"Interpolations for HTML DOM event attributes are disallowed. Please use the ng- " +
"versions (such as ng-click instead of onclick) instead.");
}
// we need to interpolate again, in case the attribute value has been updated
// (e.g. by another directive's compile function)
interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
// if attribute was updated so that there is no interpolation going on we don't want to
// register any observers
if (!interpolateFn) return;
attr[name] = interpolateFn(scope);
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function interpolateFnWatchAction(value) {
attr.$set(name, value);
});
})
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep the shell,
* but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, elementsToRemove, newNode) {
var firstElementToRemove = elementsToRemove[0],
removeCount = elementsToRemove.length,
parent = firstElementToRemove.parentNode,
i, ii;
if ($rootElement) {
for(i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == firstElementToRemove) {
$rootElement[i++] = newNode;
for (var j = i, j2 = j + removeCount - 1,
jj = $rootElement.length;
j < jj; j++, j2++) {
if (j2 < jj) {
$rootElement[j] = $rootElement[j2];
} else {
delete $rootElement[j];
}
}
$rootElement.length -= removeCount - 1;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, firstElementToRemove);
}
var fragment = document.createDocumentFragment();
fragment.appendChild(firstElementToRemove);
newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
var element = elementsToRemove[k];
jqLite(element).remove(); // must do this way to clean up expando
fragment.appendChild(element);
delete elementsToRemove[k];
}
elementsToRemove[0] = newNode;
elementsToRemove.length = 1
}
}];
}
var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* All of these will become 'myDirective':
* my:Directive
* my-directive
* x-my-directive
* data-my:directive
*
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc object
* @name ng.$compile.directive.Attributes
* @description
*
* A shared object between directive compile / linking functions which contains normalized DOM element
* attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
* since all of these are treated as equivalent in Angular:
*
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
*/
/**
* @ngdoc property
* @name ng.$compile.directive.Attributes#$attr
* @propertyOf ng.$compile.directive.Attributes
* @returns {object} A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$set
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to. The value can be an interpolated string.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {},
CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
if (isObject(name)) {
extend(controllers, name)
} else {
controllers[name] = constructor;
}
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
* a service, so that one can override this service with {@link https://gist.github.com/1649788
* BC version}.
*/
return function(expression, locals) {
var instance, match, constructor, identifier;
if(isString(expression)) {
match = expression.match(CNTRL_REG),
constructor = match[1],
identifier = match[3];
expression = controllers.hasOwnProperty(constructor)
? controllers[constructor]
: getter(locals.$scope, constructor, true) || getter($window, constructor, true);
assertArgFn(expression, constructor, true);
}
instance = $injector.instantiate(expression, locals);
if (identifier) {
if (!(locals && typeof locals.$scope == 'object')) {
throw minErr('$controller')('noscp', "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", constructor || expression.name, identifier);
}
locals.$scope[identifier] = instance;
}
return instance;
};
}];
}
/**
* @ngdoc object
* @name ng.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
* element.
*/
function $DocumentProvider(){
this.$get = ['$window', function(window){
return jqLite(window.document);
}];
}
/**
* @ngdoc function
* @name ng.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log) {
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = {}, key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val;
} else {
parsed[key] = val;
}
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers Http headers getter fn.
* @param {(function|Array.<function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, fns) {
if (isFunction(fns))
return fns(data, headers);
forEach(fns, function(fn) {
data = fn(data, headers);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/,
CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data, true);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: CONTENT_TYPE_APPLICATION_JSON,
put: CONTENT_TYPE_APPLICATION_JSON,
patch: CONTENT_TYPE_APPLICATION_JSON
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
};
/**
* Are order by request. I.E. they are applied in the same order as
* array on request, but revers order on response.
*/
var interceptorFactories = this.interceptors = [];
/**
* For historical reasons, response interceptors ordered by the order in which
* they are applied to response. (This is in revers to interceptorFactories)
*/
var responseInterceptorFactories = this.responseInterceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', '$$urlUtils',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector, $$urlUtils) {
var defaultCache = $cacheFactory('$http');
/**
* Interceptors stored in reverse order. Inner interceptors before outer interceptors.
* The reversal is needed so that we can build up the interception chain around the
* server request.
*/
var reversedInterceptors = [];
forEach(interceptorFactories, function(interceptorFactory) {
reversedInterceptors.unshift(isString(interceptorFactory)
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
});
forEach(responseInterceptorFactories, function(interceptorFactory, index) {
var responseFn = isString(interceptorFactory)
? $injector.get(interceptorFactory)
: $injector.invoke(interceptorFactory);
/**
* Response interceptors go before "around" interceptors (no real reason, just
* had to pick one.) But they are already reversed, so we can't use unshift, hence
* the splice.
*/
reversedInterceptors.splice(index, 0, {
response: function(response) {
return responseFn($q.when(response));
},
responseError: function(response) {
return responseFn($q.reject(response));
}
});
});
/**
* @ngdoc function
* @name ng.$http
* @requires $httpBackend
* @requires $browser
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
* it is important to familiarize yourself with these APIs and the guarantees they provide.
*
*
* # General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an HTTP request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* <pre>
* $http({method: 'GET', url: '/someUrl'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* </pre>
*
* Since the returned value of calling the $http function is a `promise`, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the API signature and type info below for more
* details.
*
* A response status code between 200 and 299 is considered a success status and
* will result in the success callback being called. Note that if the response is a redirect,
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be
* called for such responses.
*
* # Shortcut methods
*
* Since all invocations of the $http service require passing in an HTTP method and URL, and
* POST/PUT requests require request data to be provided as well, shortcut methods
* were created:
*
* <pre>
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* </pre>
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
*
*
* # Setting HTTP Headers
*
* The $http service will automatically add certain HTTP headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from these configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with the lowercased HTTP method name as the key, e.g.
* `$httpProvider.defaults.headers.get['My-Header']='value'`.
*
* Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same
* fashion.
*
*
* # Transforming Requests and Responses
*
* Both requests and responses can be transformed using transform functions. By default, Angular
* applies these transformations:
*
* Request transformations:
*
* - If the `data` property of the request configuration object contains an object, serialize it into
* JSON format.
*
* Response transformations:
*
* - If XSRF prefix is detected, strip it (see Security Considerations section below).
* - If JSON response is detected, deserialize it using a JSON parser.
*
* To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and
* `$httpProvider.defaults.transformResponse` properties. These properties are by default an
* array of transform functions, which allows you to `push` or `unshift` a new transformation function into the
* transformation chain. You can also decide to completely override any default transformations by assigning your
* transformation functions to these properties directly without the array wrapper.
*
* Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or
* `transformResponse` properties of the configuration object passed into `$http`.
*
*
* # Caching
*
* To enable caching, set the configuration property `cache` to `true`. When the cache is
* enabled, `$http` stores the response from the server in local cache. Next time the
* response is served from the cache without sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same URL that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response from the first request.
*
* A custom default cache built with $cacheFactory can be provided in $http.defaults.cache.
* To skip it, set configuration property `cache` to `false`.
*
*
* # Interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication, or any kind of synchronous or
* asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
* able to intercept requests before they are handed to the server and
* responses before they are handed over to the application code that
* initiated these requests. The interceptors leverage the {@link ng.$q
* promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
*
* The interceptors are service factories that are registered with the `$httpProvider` by
* adding them to the `$httpProvider.interceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor.
*
* There are two kinds of interceptors (and two kinds of rejection interceptors):
*
* * `request`: interceptors get called with http `config` object. The function is free to modify
* the `config` or create a new one. The function needs to return the `config` directly or as a
* promise.
* * `requestError`: interceptor gets called when a previous interceptor threw an error or resolved
* with a rejection.
* * `response`: interceptors get called with http `response` object. The function is free to modify
* the `response` or create a new one. The function needs to return the `response` directly or as a
* promise.
* * `responseError`: interceptor gets called when a previous interceptor threw an error or resolved
* with a rejection.
*
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return {
* // optional method
* 'request': function(config) {
* // do something on success
* return config || $q.when(config);
* },
*
* // optional method
* 'requestError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* },
*
*
*
* // optional method
* 'response': function(response) {
* // do something on success
* return response || $q.when(response);
* },
*
* // optional method
* 'responseError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* };
* }
* });
*
* $httpProvider.interceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
* return {
* 'request': function(config) {
* // same as above
* },
* 'response': function(response) {
* // same as above
* }
* });
* </pre>
*
* # Response interceptors (DEPRECATED)
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication or any kind of synchronous or
* asynchronous preprocessing of received responses, it is desirable to be able to intercept
* responses for http requests before they are handed over to the application code that
* initiated these requests. The response interceptors leverage the {@link ng.$q
* promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
*
* The interceptors are service factories that are registered with the $httpProvider by
* adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor — a function that
* takes a {@link ng.$q promise} and returns the original or a new promise.
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return function(promise) {
* return promise.then(function(response) {
* // do something on success
* }, function(response) {
* // do something on error
* if (canRecover(response)) {
* return responseOrNewPromise
* }
* return $q.reject(response);
* });
* }
* });
*
* $httpProvider.responseInterceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
* return function(promise) {
* // same as above
* }
* });
* </pre>
*
*
* # Security Considerations
*
* When designing web applications, consider security threats from:
*
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON vulnerability}
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
*
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON vulnerability} allows third party website to turn your JSON resource URL into
* {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
*
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
* an unauthorized site can gain your user's private data. Angular provides a mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
* JavaScript that runs on your domain could read the cookie, your server can be assured that
* the XHR came from JavaScript running on your domain. The header will not be set for
* cross-domain requests.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have sent the request. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript from making
* up its own tokens). We recommend that the token is a digest of your site's authentication
* cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security.
*
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
* properties of either $httpProvider.defaults, or the per-request config object.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to
* `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings or functions which return strings representing
* HTTP headers to send to the server. If the return value of a function is null, the header will
* not be sent.
* - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
* - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
* - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body and headers and returns its transformed (typically deserialized) version.
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
* that should abort the request when resolved.
* - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
* requests with credentials} for more information.
* - **responseType** - `{string}` - see {@link
* https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}.
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example>
<file name="index.html">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button ng-click="fetch()">fetch</button><br>
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="scenario.js">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</file>
</example>
*/
function $http(requestConfig) {
var config = {
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse
};
var headers = mergeHeaders(requestConfig);
extend(config, requestConfig);
config.headers = headers;
config.method = uppercase(config.method);
var xsrfValue = $$urlUtils.isSameOrigin(config.url)
? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}
var serverRequest = function(config) {
headers = config.headers;
var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
// strip content-type if data is undefined
if (isUndefined(config.data)) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header];
}
});
}
if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
config.withCredentials = defaults.withCredentials;
}
// send request
return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
};
var chain = [serverRequest, undefined];
var promise = $q.when(config);
// apply interceptors
forEach(reversedInterceptors, function(interceptor) {
if (interceptor.request || interceptor.requestError) {
chain.unshift(interceptor.request, interceptor.requestError);
}
if (interceptor.response || interceptor.responseError) {
chain.push(interceptor.response, interceptor.responseError);
}
});
while(chain.length) {
var thenFn = chain.shift();
var rejectFn = chain.shift();
promise = promise.then(thenFn, rejectFn);
}
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response, {
data: transformData(response.data, response.headers, config.transformResponse)
});
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
function mergeHeaders(config) {
var defHeaders = defaults.headers,
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName;
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
// execute if header value is function
execHeaders(defHeaders);
execHeaders(reqHeaders);
// using for-in instead of forEach to avoid unecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName);
for (reqHeaderName in reqHeaders) {
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
continue defaultHeadersIteration;
}
}
reqHeaders[defHeaderName] = defHeaders[defHeaderName];
}
return reqHeaders;
function execHeaders(headers) {
var headerContent;
forEach(headers, function(headerFn, header) {
if (isFunction(headerFn)) {
headerContent = headerFn();
if (headerContent != null) {
headers[header] = headerContent;
} else {
delete headers[header];
}
}
});
}
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name ng.$http#get
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `GET` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#delete
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `DELETE` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#head
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `HEAD` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#jsonp
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `JSONP` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* Should contain `JSON_CALLBACK` string.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name ng.$http#post
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `POST` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#put
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `PUT` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put');
/**
* @ngdoc property
* @name ng.$http#defaults
* @propertyOf ng.$http
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers, withCredentials as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = defaults;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request.
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData, reqHeaders) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') {
cache = isObject(config.cache) ? config.cache
: isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (cachedResp) {
if (cachedResp.then) {
// cached request has already been sent, but there is no response yet
cachedResp.then(removePendingReq, removePendingReq);
return cachedResp;
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
} else {
resolvePromise(cachedResp, 200, {});
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, send the request to the backend
if (!cachedResp) {
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials, config.responseType);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString)]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
resolvePromise(response, status, headersString);
if (!$rootScope.$$phase) $rootScope.$apply();
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config
});
}
function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value == null || value == undefined) return;
if (!isArray(value)) value = [value];
forEach(value, function(v) {
if (isObject(v)) {
v = toJson(v);
}
parts.push(encodeUriQuery(key) + '=' +
encodeUriQuery(v));
});
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
}];
}
var XHR = window.XMLHttpRequest || function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc object
* @name ng.$httpBackend
* @requires $browser
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks,
$document[0], $window.location.protocol.replace(':', ''));
}];
}
function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
var status;
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
};
var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, status || -2);
}
delete callbacks[callbackId];
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
// In IE6 and 7, this might be called synchronously when xhr.send below is called and the
// response is in the cache. the promise api will ensure that to the app code the api is
// always async
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var responseHeaders = xhr.getAllResponseHeaders();
// TODO(vojta): remove once Firefox 21 gets released.
// begin: workaround to overcome Firefox CORS http response headers bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=608735
// Firefox already patched in nightly. Should land in Firefox 21.
// CORS "simple response headers" http://www.w3.org/TR/cors/
var value,
simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type",
"Expires", "Last-Modified", "Pragma"];
if (!responseHeaders) {
responseHeaders = "";
forEach(simpleHeaders, function (header) {
var value = xhr.getResponseHeader(header);
if (value) {
responseHeaders += header + ": " + value + "\n";
}
});
}
// end of the workaround.
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response and responseType properties were introduced in XHR Level2 spec (supported by IE10)
completeRequest(callback,
status || xhr.status,
(xhr.responseType ? xhr.response : xhr.responseText),
responseHeaders);
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
if (responseType) {
xhr.responseType = responseType;
}
xhr.send(post || '');
}
if (timeout > 0) {
var timeoutId = $browserDefer(timeoutRequest, timeout);
} else if (timeout && timeout.then) {
timeout.then(timeoutRequest);
}
function timeoutRequest() {
status = -1;
jsonpDone && jsonpDone();
xhr && xhr.abort();
}
function completeRequest(callback, status, response, headersString) {
// URL_MATCH is defined in src/service/location.js
var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1];
// cancel timeout and subsequent timeout promise resolution
timeoutId && $browserDefer.cancel(timeoutId);
jsonpDone = xhr = null;
// fix status code for file protocol (it's always 0)
status = (protocol == 'file') ? (response ? 200 : 404) : status;
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status == 1223 ? 204 : status;
callback(status, response, headersString);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'),
doneWrapper = function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type = 'text/javascript';
script.src = url;
if (msie) {
script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload = script.onerror = doneWrapper;
}
rawDocument.body.appendChild(script);
return doneWrapper;
}
}
var $interpolateMinErr = minErr('$interpolate');
/**
* @ngdoc object
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
*
* @example
<doc:example>
<doc:source>
<script>
var myApp = angular.module('App', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('//');
$interpolateProvider.endSymbol('//');
});
function Controller($scope) {
$scope.label = "Interpolation Provider Sample";
}
</script>
<div ng-app="App" ng-controller="Controller">
//label//
</div>
</doc:source>
</doc:example>
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name ng.$interpolateProvider#startSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @param {string=} value new value to set the starting symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.startSymbol = function(value){
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name ng.$interpolateProvider#endSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @param {string=} value new value to set the ending symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.endSymbol = function(value){
if (value) {
endSymbol = value;
return this;
} else {
return endSymbol;
}
};
this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
* @requires $sce
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
<pre>
var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
</pre>
*
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @param {string=} trustedContext when provided, the returned function passes the interpolated
* result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
* trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
* provides Strict Contextual Escaping for details.
* @returns {function(context)} an interpolation function which is used to compute the interpolated
* string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
function $interpolate(text, mustHaveExpression, trustedContext) {
var startIndex,
endIndex,
index = 0,
parts = [],
length = text.length,
hasInterpolation = false,
fn,
exp,
concat = [];
while(index < length) {
if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
(index != startIndex) && parts.push(text.substring(index, startIndex));
parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
fn.exp = exp;
index = endIndex + endSymbolLength;
hasInterpolation = true;
} else {
// we did not find anything, so we have to add the remainder to the parts array
(index != length) && parts.push(text.substring(index));
index = length;
}
}
if (!(length = parts.length)) {
// we added, nothing, must have been an empty string.
parts.push('');
length = 1;
}
// Concatenating expressions makes it hard to reason about whether some combination of concatenated
// values are unsafe to use and could easily lead to XSS. By requiring that a single
// expression be used for iframe[src], object[src], etc., we ensure that the value that's used
// is assigned or constructed by some JS code somewhere that is more testable or make it
// obvious that you bound the value to some user controlled value. This helps reduce the load
// when auditing for XSS issues.
if (trustedContext && parts.length > 1) {
throw $interpolateMinErr('noconcat',
"Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
"interpolations that concatenate multiple expressions when a trusted value is " +
"required. See http://docs.angularjs.org/api/ng.$sce", text);
}
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
try {
for(var i = 0, ii = length, part; i<ii; i++) {
if (typeof (part = parts[i]) == 'function') {
part = part(context);
if (trustedContext) {
part = $sce.getTrusted(trustedContext, part);
} else {
part = $sce.valueOf(part);
}
if (part == null || part == undefined) {
part = '';
} else if (typeof part != 'string') {
part = toJson(part);
}
}
concat[i] = part;
}
return concat.join('');
}
catch(err) {
var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
$exceptionHandler(newErr);
}
};
fn.exp = text;
fn.parts = parts;
return fn;
}
}
/**
* @ngdoc method
* @name ng.$interpolate#startSymbol
* @methodOf ng.$interpolate
* @description
* Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
*
* Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.startSymbol = function() {
return startSymbol;
}
/**
* @ngdoc method
* @name ng.$interpolate#endSymbol
* @methodOf ng.$interpolate
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.endSymbol = function() {
return endSymbol;
}
return $interpolate;
}];
}
/**
* @ngdoc object
* @name ng.$locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider(){
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
};
}
var SERVER_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
var $locationMinErr = minErr('$location');
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function matchUrl(url, obj) {
var match = SERVER_MATCH.exec(url);
obj.$$protocol = match[1];
obj.$$host = match[3];
obj.$$port = int(match[5]) || DEFAULT_PORTS[match[1]] || null;
}
function matchAppUrl(url, obj) {
var match = PATH_MATCH.exec(url);
obj.$$path = decodeURIComponent(match[1]);
obj.$$search = parseKeyValue(match[3]);
obj.$$hash = decodeURIComponent(match[5] || '');
// make sure path starts with '/';
if (obj.$$path && obj.$$path.charAt(0) != '/') obj.$$path = '/' + obj.$$path;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
}
/**
*
* @param {string} begin
* @param {string} whole
* @param {string} otherwise
* @returns {string} returns text from whole after begin or otherwise if it does not begin with expected string.
*/
function beginsWith(begin, whole, otherwise) {
return whole.indexOf(begin) == 0 ? whole.substr(begin.length) : otherwise;
}
function stripHash(url) {
var index = url.indexOf('#');
return index == -1 ? url : url.substr(0, index);
}
function stripFile(url) {
return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
}
/* return the server only (scheme://host:port) */
function serverBase(url) {
return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
}
/**
* LocationHtml5Url represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} appBase application base URL
* @param {string} basePrefix url path prefix
*/
function LocationHtml5Url(appBase, basePrefix) {
this.$$html5 = true;
basePrefix = basePrefix || '';
var appBaseNoFile = stripFile(appBase);
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse = function(url) {
var parsed = {}
matchUrl(url, parsed);
var pathUrl = beginsWith(appBaseNoFile, url);
if (!isString(pathUrl)) {
throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, appBaseNoFile);
}
matchAppUrl(pathUrl, parsed);
extend(this, parsed);
if (!this.$$path) {
this.$$path = '/';
}
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
};
this.$$rewrite = function(url) {
var appUrl, prevAppUrl;
if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
prevAppUrl = appUrl;
if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
} else {
return appBase + prevAppUrl;
}
} else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
return appBaseNoFile + appUrl;
} else if (appBaseNoFile == url + '/') {
return appBaseNoFile;
}
}
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when developer doesn't opt into html5 mode.
* It also serves as the base class for html5 mode fallback on legacy browsers.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangUrl(appBase, hashPrefix) {
var appBaseNoFile = stripFile(appBase);
matchUrl(appBase, this);
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
? beginsWith(hashPrefix, withoutBaseUrl)
: (this.$$html5)
? withoutBaseUrl
: '';
if (!isString(withoutHashUrl)) {
throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, hashPrefix);
}
matchAppUrl(withoutHashUrl, this);
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
};
this.$$rewrite = function(url) {
if(stripHash(appBase) == stripHash(url)) {
return url;
}
}
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is enabled but the browser
* does not support it.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangInHtml5Url(appBase, hashPrefix) {
this.$$html5 = true;
LocationHashbangUrl.apply(this, arguments);
var appBaseNoFile = stripFile(appBase);
this.$$rewrite = function(url) {
var appUrl;
if ( appBase == stripHash(url) ) {
return url;
} else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
return appBase + hashPrefix + appUrl;
} else if ( appBaseNoFile === url + '/') {
return appBaseNoFile;
}
}
}
LocationHashbangInHtml5Url.prototype =
LocationHashbangUrl.prototype =
LocationHtml5Url.prototype = {
/**
* Are we in html5 mode?
* @private
*/
$$html5: false,
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name ng.$location#absUrl
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name ng.$location#url
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @param {string=} replace The path that will be changed
* @return {string} url
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
if (match[2] || match[1]) this.search(match[3] || '');
this.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name ng.$location#protocol
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name ng.$location#host
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name ng.$location#port
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name ng.$location#path
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
* @param {string=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name ng.$location#search
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or hash object. Hash object
* may contain an array of values, which will be decoded as duplicates in the url.
* @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
* single search parameter. If the value is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
switch (arguments.length) {
case 0:
return this.$$search;
case 1:
if (isString(search)) {
this.$$search = parseKeyValue(search);
} else if (isObject(search)) {
this.$$search = search;
} else {
throw $locationMinErr('isrcharg', 'The first argument of the `$location#search()` call must be a string or an object.');
}
break;
default:
if (paramValue == undefined || paramValue == null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name ng.$location#hash
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
* @param {string=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name ng.$location#replace
* @methodOf ng.$location
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc object
* @name ng.$location
*
* @requires $browser
* @requires $sniffer
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
* Services: Using $location}
*/
/**
* @ngdoc object
* @name ng.$locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider(){
var hashPrefix = '',
html5Mode = false;
/**
* @ngdoc property
* @name ng.$locationProvider#hashPrefix
* @methodOf ng.$locationProvider
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc property
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
* @param {string=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isDefined(mode)) {
html5Mode = mode;
return this;
} else {
return html5Mode;
}
};
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
LocationMode,
baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
initialUrl = $browser.url(),
appBase;
if (html5Mode) {
appBase = serverBase(initialUrl) + (baseHref || '/');
LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
} else {
appBase = stripHash(initialUrl);
LocationMode = LocationHashbangUrl;
}
$location = new LocationMode(appBase, '#' + hashPrefix);
$location.$$parse($location.$$rewrite(initialUrl));
$rootElement.on('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (event.ctrlKey || event.metaKey || event.which == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (lowercase(elm[0].nodeName) !== 'a') {
// ignore rewriting if no A tag (reached root element, or no parent - removed from document)
if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
}
var absHref = elm.prop('href');
var rewrittenUrl = $location.$$rewrite(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
event.preventDefault();
if (rewrittenUrl != $browser.url()) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
}
}
});
// rewrite hashbang url <> html5 url
if ($location.absUrl() != initialUrl) {
$browser.url($location.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if ($location.absUrl() != newUrl) {
if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) {
$browser.url($location.absUrl());
return;
}
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
$location.$$parse(newUrl);
afterLocationChange(oldUrl);
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
});
// update browser
var changeCounter = 0;
$rootScope.$watch(function $locationWatch() {
var oldUrl = $browser.url();
var currentReplace = $location.$$replace;
if (!changeCounter || oldUrl != $location.absUrl()) {
changeCounter++;
$rootScope.$evalAsync(function() {
if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
defaultPrevented) {
$location.$$parse(oldUrl);
} else {
$browser.url($location.absUrl(), currentReplace);
afterLocationChange(oldUrl);
}
});
}
$location.$$replace = false;
return changeCounter;
});
return $location;
function afterLocationChange(oldUrl) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
}
}];
}
/**
* @ngdoc object
* @name ng.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* @example
<example>
<file name="script.js">
function LogCtrl($scope, $log) {
$scope.$log = $log;
$scope.message = 'Hello World!';
}
</file>
<file name="index.html">
<div ng-controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
</div>
</file>
</example>
*/
/**
* @ngdoc object
* @name ng.$logProvider
* @description
* Use the `$logProvider` to configure how the application logs messages
*/
function $LogProvider(){
var debug = true,
self = this;
/**
* @ngdoc property
* @name ng.$logProvider#debugEnabled
* @methodOf ng.$logProvider
* @description
* @param {string=} flag enable or disable debug level messages
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.debugEnabled = function(flag) {
if (isDefined(flag)) {
debug = flag;
return this;
} else {
return debug;
}
};
this.$get = ['$window', function($window){
return {
/**
* @ngdoc method
* @name ng.$log#log
* @methodOf ng.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error'),
/**
* @ngdoc method
* @name ng.$log#debug
* @methodOf ng.$log
*
* @description
* Write a debug message
*/
debug: (function () {
var fn = consoleLog('debug');
return function() {
if (debug) {
fn.apply(self, arguments);
}
}
}())
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop;
if (logFn.apply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2);
}
}
}];
}
var $parseMinErr = minErr('$parse');
// Sandboxing Angular Expressions
// ------------------------------
// Angular expressions are generally considered safe because these expressions only have direct access to $scope and
// locals. However, one can obtain the ability to execute arbitrary JS code by obtaining a reference to native JS
// functions such as the Function constructor.
//
// As an example, consider the following Angular expression:
//
// {}.toString.constructor(alert("evil JS code"))
//
// We want to prevent this type of access. For the sake of performance, during the lexing phase we disallow any "dotted"
// access to any member named "constructor".
//
// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor while evaluating
// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor while evaluating
// the expression, which is a stronger but more expensive test. Since reflective calls are expensive anyway, this is not
// such a big deal compared to static dereferencing.
//
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits against the
// expression language, but not to prevent exploits that were enabled by exposing sensitive JavaScript or browser apis
// on Scope. Exposing such objects on a Scope is never a good practice and therefore we are not even trying to protect
// against interaction with an object explicitly exposed in this way.
//
// A developer could foil the name check by aliasing the Function constructor under a different name on the scope.
//
// In general, it is not possible to access a Window object from an angular expression unless a window or some DOM
// object that has a reference to window is published onto a Scope.
function ensureSafeMemberName(name, fullExpression) {
if (name === "constructor") {
throw $parseMinErr('isecfld',
'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}', fullExpression);
}
return name;
};
function ensureSafeObject(obj, fullExpression) {
// nifty check if obj is Function that is fast and works across iframes and other contexts
if (obj && obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}', fullExpression);
} else {
return obj;
}
}
var OPERATORS = {
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
undefined:noop,
'+':function(self, locals, a,b){
a=a(self, locals); b=b(self, locals);
if (isDefined(a)) {
if (isDefined(b)) {
return a + b;
}
return a;
}
return isDefined(b)?b:undefined;},
'-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
'=':noop,
'===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
'!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
'==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
'!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
'<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
'>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
'<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
'>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
'&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
'&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
// '|':function(self, locals, a,b){return a|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
function lex(text, csp){
var tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=='{' &&
(token=tokens[tokens.length-1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:?')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
ch3 = ch2 + peek(2),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2],
fn3 = OPERATORS[ch3];
if (fn3) {
tokens.push({index:index, text:ch3, fn:fn3});
index += 3;
} else if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index += 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
index += 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek(i) {
var num = i || 1;
return index + num < text.length ? text.charAt(index + num) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
var colStr = (isDefined(start) ?
"s " + start + "-" + index + " [" + text.substring(start, end) + "]"
: " " + end);
throw $parseMinErr('lexerr', "Lexer Error: {0} at column{1} in expression [{2}].",
error, colStr, text);
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function() {return number;}});
}
function readIdent() {
var ident = "",
start = index,
lastDot, peekIndex, methodName, ch;
while (index < text.length) {
ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
if (ch == '.') lastDot = index;
ident += ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = index;
while(peekIndex < text.length) {
ch = text.charAt(peekIndex);
if (ch == '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
index = peekIndex;
break;
}
if(isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index:start,
text:ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, csp, text);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value, text);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index:lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
index++;
tokens.push({
index:start,
text:rawString,
string:string,
json:true,
fn:function() { return string; }
});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp){
var ZERO = valueFn(0),
value,
tokens = lex(text, csp),
assignment = _assignment,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain;
if(json){
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
filterChain =
function() { throwError("is not valid json", {text:text, index:0}); };
value = primary();
} else {
value = statements();
}
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
value.literal = !!value.literal;
value.constant = !!value.constant;
return value;
///////////////////////////////////
function throwError(msg, token) {
throw $parseMinErr('syntax',
"Syntax Error: Token '{0}' {1} at column {2} of the expression [{3}] starting at [{4}].",
token.text, msg, (token.index + 1), text, text.substring(token.index));
}
function peekToken() {
if (tokens.length === 0)
throw $parseMinErr('ueoe', "Unexpected end of expression: {0}", text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t==e1 || t==e2 || t==e3 || t==e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return extend(function(self, locals) {
return fn(self, locals, right);
}, {
constant:right.constant
});
}
function ternaryFn(left, middle, right){
return extend(function(self, locals){
return left(self, locals) ? middle(self, locals) : right(self, locals);
}, {
constant: left.constant && middle.constant && right.constant
});
}
function binaryFn(left, fn, right) {
return extend(function(self, locals) {
return fn(self, locals, left, right);
}, {
constant:left.constant && right.constant
});
}
function statements() {
var statements = [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length == 1
? statements[0]
: function(self, locals){
var value;
for ( var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement)
value = statement(self, locals);
}
return value;
};
}
}
}
function _filterChain() {
var left = expression();
var token;
while(true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token = expect();
var fn = $filter(token.text);
var argsFn = [];
while(true) {
if ((token = expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke = function(self, locals, input){
var args = [input];
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left = ternary();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", token);
}
right = ternary();
return function(scope, locals){
return left.assign(scope, right(scope, locals), locals);
};
} else {
return left;
}
}
function ternary() {
var left = logicalOR();
var middle;
var token;
if((token = expect('?'))){
middle = ternary();
if((token = expect(':'))){
return ternaryFn(left, middle, ternary());
}
else {
throwError('expected :', token);
}
}
else {
return left;
}
}
function logicalOR() {
var left = logicalAND();
var token;
while(true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left = relational();
var token;
if ((token = expect('==','!=','===','!=='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left = multiplicative();
var token;
while ((token = expect('+','-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left = unary();
var token;
while ((token = expect('*','/','%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary = filterChain();
consume(')');
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
if (token.json) {
primary.constant = primary.literal = true;
}
}
var next, context;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field, csp, text);
return extend(
function(scope, locals, self) {
return getter(self || object(scope, locals), locals);
},
{
assign:function(scope, value, locals) {
return setter(object(scope, locals), field, value, text);
}
}
);
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(
function(self, locals){
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
if (!o) return undefined;
v = ensureSafeObject(o[i], text);
if (v && v.then) {
p = v;
if (!('$$v' in v)) {
p.$$v = undefined;
p.then(function(val) { p.$$v = val; });
}
v = v.$$v;
}
return v;
}, {
assign:function(self, value, locals){
var key = indexFn(self, locals);
// prevent overwriting of Function.constructor which would break ensureSafeObject check
return ensureSafeObject(obj(self, locals), text)[key] = value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(scope, locals){
var args = [],
context = contextGetter ? contextGetter(scope, locals) : scope;
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](scope, locals));
}
var fnPtr = fn(scope, locals, context) || noop;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns = [];
var allConstant = true;
if (peekToken().text != ']') {
do {
var elementFn = expression();
elementFns.push(elementFn);
if (!elementFn.constant) {
allConstant = false;
}
} while (expect(','));
}
consume(']');
return extend(function(self, locals){
var array = [];
for ( var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
}, {
literal:true,
constant:allConstant
});
}
function object () {
var keyValues = [];
var allConstant = true;
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({key:key, value:value});
if (!value.constant) {
allConstant = false;
}
} while (expect(','));
}
consume('}');
return extend(function(self, locals){
var object = {};
for ( var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
object[keyValue.key] = keyValue.value(self, locals);
}
return object;
}, {
literal:true,
constant:allConstant
});
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue, fullExp) {
var element = path.split('.'), key;
for (var i = 0; element.length > 1; i++) {
key = ensureSafeMemberName(element.shift(), fullExp);
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
if (obj.then) {
if (!("$$v" in obj)) {
(function(promise) {
promise.then(function(val) { promise.$$v = val; }); }
)(obj);
}
if (obj.$$v === undefined) {
obj.$$v = {};
}
obj = obj.$$v;
}
}
key = ensureSafeMemberName(element.shift(), fullExp);
obj[key] = setValue;
return setValue;
}
var getterFnCache = {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) {
ensureSafeMemberName(key0, fullExp);
ensureSafeMemberName(key1, fullExp);
ensureSafeMemberName(key2, fullExp);
ensureSafeMemberName(key3, fullExp);
ensureSafeMemberName(key4, fullExp);
return function(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
promise;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
return pathVal;
};
}
function getterFn(path, csp, fullExp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (csp) {
fn = (pathKeysLength < 6)
? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp)
: function(scope, locals) {
var i = 0, val;
do {
val = cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], fullExp
)(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
}
} else {
var code = 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
ensureSafeMemberName(key, fullExp);
code += 'if(s === null || s === undefined) return s;\n' +
'l=s;\n' +
's='+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
'if (s && s.then) {\n' +
' if (!("$$v" in s)) {\n' +
' p=s;\n' +
' p.$$v = undefined;\n' +
' p.then(function(v) {p.$$v=v;});\n' +
'}\n' +
' s=s.$$v\n' +
'}\n';
});
code += 'return s;';
fn = Function('s', 'k', code); // s=scope, k=locals
fn.toString = function() { return code; };
}
return getterFnCache[path] = fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The returned function also has the following properties:
* * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
* literal.
* * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
* constant literals.
* * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
* set to a function to change its value on the given context.
*
*/
function $ParseProvider() {
var cache = {};
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
return function(exp) {
switch(typeof exp) {
case 'string':
return cache.hasOwnProperty(exp)
? cache[exp]
: cache[exp] = parser(exp, false, $filter, $sniffer.csp);
case 'function':
return exp;
default:
return noop;
}
};
}];
}
/**
* @ngdoc service
* @name ng.$q
* @requires $rootScope
*
* @description
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise APIs are to
* asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
*
* <pre>
* // for the purpose of this example let's assume that variables `$q` and `scope` are
* // available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* // since this fn executes async in a future turn of the event loop, we need to wrap
* // our code into an $apply call so that the model changes are properly observed.
* scope.$apply(function() {
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* });
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* });
* </pre>
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of
* [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as APIs
* that can be used for signaling the successful or unsuccessful completion of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
* or rejected, `then` calls one of the success or error callbacks asynchronously as soon as the result
* is available. The callbacks are called with a single argument: the result or rejection reason.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback` or `errorCallback`.
*
* - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
*
* - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
* but to do so without modifying the final value. This is useful to release resources or do some
* clean-up that needs to be done whether the promise was rejected or resolved. See the [full
* specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
* more information.
*
* Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
* property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
* make your code IE8 compatible.
*
* # Chaining promises
*
* Because calling the `then` method of a promise returns a new derived promise, it is easily possible
* to create a chain of promises:
*
* <pre>
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and its value
* // will be the result of promiseA incremented by 1
* </pre>
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful APIs like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are three main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - $q promises are recognized by the templating engine in angular, which means that in templates
* you can treat promises attached to a scope as if they were the resulting values.
* - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*
* # Testing
*
* <pre>
* it('should simulate promise', inject(function($q, $rootScope) {
* var deferred = $q.defer();
* var promise = deferred.promise;
* var resolvedValue;
*
* promise.then(function(value) { resolvedValue = value; });
* expect(resolvedValue).toBeUndefined();
*
* // Simulate resolving of promise
* deferred.resolve(123);
* // Note that the 'then' function does not get called synchronously.
* // This is because we want the promise API to always be async, whether or not
* // it got called synchronously or asynchronously.
* expect(resolvedValue).toBeUndefined();
*
* // Propagate promise resolution to 'then' functions using $apply().
* $rootScope.$apply();
* expect(resolvedValue).toEqual(123);
* });
* </pre>
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
/**
* @ngdoc
* @name ng.$q#defer
* @methodOf ng.$q
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
var pending = [],
value, deferred;
deferred = {
resolve: function(val) {
if (pending) {
var callbacks = pending;
pending = undefined;
value = ref(val);
if (callbacks.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
value.then(callback[0], callback[1], callback[2]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
notify: function(progress) {
if (pending) {
var callbacks = pending;
if (pending.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
callback[2](progress);
}
});
}
}
},
promise: {
then: function(callback, errback, progressback) {
var result = defer();
var wrappedCallback = function(value) {
try {
result.resolve((callback || defaultCallback)(value));
} catch(e) {
result.reject(e);
exceptionHandler(e);
}
};
var wrappedErrback = function(reason) {
try {
result.resolve((errback || defaultErrback)(reason));
} catch(e) {
result.reject(e);
exceptionHandler(e);
}
};
var wrappedProgressback = function(progress) {
try {
result.notify((progressback || defaultCallback)(progress));
} catch(e) {
exceptionHandler(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
} else {
value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
}
return result.promise;
},
"catch": function(callback) {
return this.then(null, callback);
},
"finally": function(callback) {
function makePromise(value, resolved) {
var result = defer();
if (resolved) {
result.resolve(value);
} else {
result.reject(value);
}
return result.promise;
}
function handleCallback(value, isResolved) {
var callbackOutput = null;
try {
callbackOutput = (callback ||defaultCallback)();
} catch(e) {
return makePromise(e, false);
}
if (callbackOutput && callbackOutput.then) {
return callbackOutput.then(function() {
return makePromise(value, isResolved);
}, function(error) {
return makePromise(error, false);
});
} else {
return makePromise(value, isResolved);
}
}
return this.then(function(value) {
return handleCallback(value, true);
}, function(error) {
return handleCallback(error, false);
});
}
}
};
return deferred;
};
var ref = function(value) {
if (value && value.then) return value;
return {
then: function(callback) {
var result = defer();
nextTick(function() {
result.resolve(callback(value));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#reject
* @methodOf ng.$q
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* <pre>
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* </pre>
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
return {
then: function(callback, errback) {
var result = defer();
nextTick(function() {
result.resolve((errback || defaultErrback)(reason));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#when
* @methodOf ng.$q
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with an object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a promise of the passed value or promise
*/
var when = function(value, callback, errback, progressback) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
return (callback || defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback = function(reason) {
try {
return (errback || defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedProgressback = function(progress) {
try {
return (progressback || defaultCallback)(progress);
} catch (e) {
exceptionHandler(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
}, function(progress) {
if (done) return;
result.notify(wrappedProgressback(progress));
});
});
return result.promise;
};
function defaultCallback(value) {
return value;
}
function defaultErrback(reason) {
return reject(reason);
}
/**
* @ngdoc
* @name ng.$q#all
* @methodOf ng.$q
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
* each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
function all(promises) {
var deferred = defer(),
counter = 0,
results = isArray(promises) ? [] : {};
forEach(promises, function(promise, key) {
counter++;
ref(promise).then(function(value) {
if (results.hasOwnProperty(key)) return;
results[key] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (results.hasOwnProperty(key)) return;
deferred.reject(reason);
});
});
if (counter === 0) {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope are heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive in terms of speed as well as memory:
* - No closures, instead use prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the beginning (shift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using an array would be slow since inserts in middle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc object
* @name ng.$rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc function
* @name ng.$rootScopeProvider#digestTtl
* @methodOf ng.$rootScopeProvider
* @description
*
* Sets the number of digest iterations the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc object
* @name ng.$rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide
* event processing life-cycle. See {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider(){
var TTL = 10;
var $rootScopeMinErr = minErr('$rootScope');
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
this.$get = ['$injector', '$exceptionHandler', '$parse',
function( $injector, $exceptionHandler, $parse) {
/**
* @ngdoc function
* @name ng.$rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link AUTO.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* <pre>
* <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
child.name = "World";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be provided
* for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy when unit-testing and having
* the need to override a default service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this['this'] = this.$root = this;
this.$$destroyed = false;
this.$$asyncQueue = [];
this.$$listeners = {};
this.$$isolateBindings = {};
}
/**
* @ngdoc property
* @name ng.$rootScope.Scope#$id
* @propertyOf ng.$rootScope.Scope
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
* debugging.
*/
Scope.prototype = {
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$new
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
* {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
* hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for
* the scope and its child scopes to be permanently detached from the parent and thus stop
* participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate if true then the scope does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not see parent scope properties.
* When creating widgets it is useful for the widget to not accidentally read parent
* state.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
var Child,
child;
if (isolate) {
child = new Scope();
child.$root = this.$root;
// ensure that there is just one async queue per $rootScope and it's children
child.$$asyncQueue = this.$$asyncQueue;
} else {
Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These will then show up as class
// name in the debugger.
Child.prototype = this;
child = new Child();
child.$id = nextUid();
}
child['this'] = child;
child.$$listeners = {};
child.$parent = this;
child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
}
return child;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watch
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and
* should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()}
* reruns when it detects changes the `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression` are not equal (with the exception of the initial run,
* see below). The inequality is determined according to
* {@link angular.equals} function. To save the value of the object for later comparison, the
* {@link angular.copy} function is used. It also means that watching complex options will
* have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
* is achieved by rerunning the watchers until no changes are detected. The rerun iteration
* limit is 10 to prevent an infinite loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
* can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is
* detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
* # Example
* <pre>
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a
* call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {(function()|string)=} listener Callback called whenever the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
*
* @param {boolean=} objectEquality Compare object for equality rather than for reference.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
};
// in the case user pass string, we need to compile it, do we really need this ?
if (!isFunction(listener)) {
var listenFn = compileToFn(listener || noop, 'listener');
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
}
if (typeof watchExp == 'string' && get.constant) {
var originalFn = watcher.fn;
watcher.fn = function(newVal, oldVal, scope) {
originalFn.call(this, newVal, oldVal, scope);
arrayRemove(array, watcher);
};
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
arrayRemove(array, watcher);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watchCollection
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Shallow watches the properties of an object and fires whenever any of the properties change
* (for arrays this implies watching the array items, for object maps this implies watching the properties).
* If a change is detected the `listener` callback is fired.
*
* - The `obj` collection is observed via standard $watch operation and is examined on every call to $digest() to
* see if any items have been added, removed, or moved.
* - The `listener` is called whenever anything within the `obj` has changed. Examples include adding new items
* into the object or array, removing and moving items around.
*
*
* # Example
* <pre>
$scope.names = ['igor', 'matias', 'misko', 'james'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function(newNames, oldNames) {
$scope.dataCount = newNames.length;
});
expect($scope.dataCount).toEqual(4);
$scope.$digest();
//still at 4 ... no changes
expect($scope.dataCount).toEqual(4);
$scope.names.pop();
$scope.$digest();
//now there's been a change
expect($scope.dataCount).toEqual(3);
* </pre>
*
*
* @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The expression value
* should evaluate to an object or an array which is observed on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the collection will trigger
* a call to the `listener`.
*
* @param {function(newCollection, oldCollection, scope)} listener a callback function that is fired with both
* the `newCollection` and `oldCollection` as parameters.
* The `newCollection` object is the newly modified data obtained from the `obj` expression and the
* `oldCollection` object is a copy of the former collection data.
* The `scope` refers to the current scope.
*
* @returns {function()} Returns a de-registration function for this listener. When the de-registration function is executed
* then the internal watch operation is terminated.
*/
$watchCollection: function(obj, listener) {
var self = this;
var oldValue;
var newValue;
var changeDetected = 0;
var objGetter = $parse(obj);
var internalArray = [];
var internalObject = {};
var oldLength = 0;
function $watchCollectionWatch() {
newValue = objGetter(self);
var newLength, key;
if (!isObject(newValue)) {
if (oldValue !== newValue) {
oldValue = newValue;
changeDetected++;
}
} else if (isArrayLike(newValue)) {
if (oldValue !== internalArray) {
// we are transitioning from something which was not an array into array.
oldValue = internalArray;
oldLength = oldValue.length = 0;
changeDetected++;
}
newLength = newValue.length;
if (oldLength !== newLength) {
// if lengths do not match we need to trigger change notification
changeDetected++;
oldValue.length = oldLength = newLength;
}
// copy the items to oldValue and look for changes.
for (var i = 0; i < newLength; i++) {
if (oldValue[i] !== newValue[i]) {
changeDetected++;
oldValue[i] = newValue[i];
}
}
} else {
if (oldValue !== internalObject) {
// we are transitioning from something which was not an object into object.
oldValue = internalObject = {};
oldLength = 0;
changeDetected++;
}
// copy the items to oldValue and look for changes.
newLength = 0;
for (key in newValue) {
if (newValue.hasOwnProperty(key)) {
newLength++;
if (oldValue.hasOwnProperty(key)) {
if (oldValue[key] !== newValue[key]) {
changeDetected++;
oldValue[key] = newValue[key];
}
} else {
oldLength++;
oldValue[key] = newValue[key];
changeDetected++;
}
}
}
if (oldLength > newLength) {
// we used to have more keys, need to find them and destroy them.
changeDetected++;
for(key in oldValue) {
if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
oldLength--;
delete oldValue[key];
}
}
}
}
return changeDetected;
}
function $watchCollectionAction() {
listener(newValue, oldValue, self);
}
return this.$watch($watchCollectionWatch, $watchCollectionAction);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$digest
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children.
* Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the
* `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are
* firing. This means that it is possible to get into an infinite loop. This function will throw
* `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10.
*
* Usually you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider#directive directives}.
* Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
* {@link ng.$compileProvider#directive directives}) will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()}
* with no `listener`.
*
* You may have a need to call `$digest()` from within unit-tests, to simulate the scope
* life-cycle.
*
* # Example
* <pre>
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue = this.$$asyncQueue,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg;
beginPhase('$digest');
do { // "while dirty" loop
dirty = false;
current = target;
while(asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
$exceptionHandler(e);
}
}
do { // "traverse the scopes" loop
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if (watch && (value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value == 'number' && typeof last == 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
watch.last = watch.eq ? copy(value) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
logMsg = (isFunction(watch.exp))
? 'fn: ' + (watch.exp.name || watch.exp.toString())
: watch.exp;
logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
watchLog[logIdx].push(logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
if(dirty && !(ttl--)) {
clearPhase();
throw $rootScopeMinErr('infdig',
'{0} $digest() iterations reached. Aborting!\nWatchers fired in the last 5 iterations: {1}',
TTL, toJson(watchLog));
}
} while (dirty || asyncQueue.length);
clearPhase();
},
/**
* @ngdoc event
* @name ng.$rootScope.Scope#$destroy
* @eventOf ng.$rootScope.Scope
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$destroy
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Removes the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it chance to
* perform any necessary cleanup.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
$destroy: function() {
// we can't destroy the root scope or a scope that has been already destroyed
if ($rootScope == this || this.$$destroyed) return;
var parent = this.$parent;
this.$broadcast('$destroy');
this.$$destroyed = true;
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
// This is bogus code that works around Chrome's GC leak
// see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
this.$$childTail = null;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$eval
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the `expression` on the current scope returning the result. Any exceptions in the
* expression are propagated (uncaught). This is useful when evaluating Angular expressions.
*
* # Example
* <pre>
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* </pre>
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$evalAsync
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
*
* - it will execute in the current script execution context (before any DOM rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
*/
$evalAsync: function(expr) {
this.$$asyncQueue.push(expr);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$apply
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular framework.
* (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life-cycle
* of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* <pre>
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* </pre>
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression
* was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$on
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
* event life cycle.
*
* The event listener function format is: `function(event, args...)`. The `event` object
* passed into the listener has the following attributes:
*
* - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
* - `currentScope` - `{Scope}`: the current scope which is handling the event.
* - `name` - `{string}`: Name of the event.
* - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event
* propagation (available only for events that were `$emit`-ed).
* - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true.
* - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
*
* @param {string} name Event name to listen on.
* @param {function(event, args...)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
namedListeners[indexOf(namedListeners, listener)] = null;
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$emit
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event traverses upwards toward the root scope and calls all registered
* listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i=0, length=namedListeners.length; i<length; i++) {
// if listeners were deregistered, defragment the array
if (!namedListeners[i]) {
namedListeners.splice(i, 1);
i--;
length--;
continue;
}
try {
namedListeners[i].apply(null, listenerArgs);
if (stopPropagation) return event;
} catch (e) {
$exceptionHandler(e);
}
}
//traverse upwards
scope = scope.$parent;
} while (scope);
return event;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$broadcast
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event propagates to all direct and indirect scopes of the current scope and
* calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to broadcast.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
listeners, i, length;
//down while you can, then up and next sibling or up and next sibling until back at root
do {
current = next;
event.currentScope = current;
listeners = current.$$listeners[name] || [];
for (i=0, length = listeners.length; i<length; i++) {
// if listeners were deregistered, defragment the array
if (!listeners[i]) {
listeners.splice(i, 1);
i--;
length--;
continue;
}
try {
listeners[i].apply(null, listenerArgs);
} catch(e) {
$exceptionHandler(e);
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
return event;
}
};
var $rootScope = new Scope();
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function compileToFn(exp, name) {
var fn = $parse(exp);
assertArgFn(fn, name);
return fn;
}
/**
* function used as an initial value for watchers.
* because it's unique we can easily tell it apart from other values
*/
function initWatchVal() {}
}];
}
var $sceMinErr = minErr('$sce');
var SCE_CONTEXTS = {
HTML: 'html',
CSS: 'css',
URL: 'url',
// RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
// url. (e.g. ng-include, script src, templateUrl)
RESOURCE_URL: 'resourceUrl',
JS: 'js'
};
/**
* @ngdoc service
* @name ng.$sceDelegate
* @function
*
* @description
*
* `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
* Contextual Escaping (SCE)} services to AngularJS.
*
* Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
* the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
* because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
* override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
* work because `$sce` delegates to `$sceDelegate` for these operations.
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
*
* The default instance of `$sceDelegate` should work out of the box with little pain. While you
* can override it completely to change the behavior of `$sce`, the common case would
* involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
* your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
* templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
* $sceDelegateProvider.resourceUrlWhitelist} and {@link
* ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*/
/**
* @ngdoc object
* @name ng.$sceDelegateProvider
* @description
*
* The $sceDelegateProvider provider allows developers to configure the {@link ng.$sceDelegate
* $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
* that URLs used for sourcing Angular templates are safe. Refer {@link
* ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
* {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*
* Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
*/
function $SceDelegateProvider() {
this.SCE_CONTEXTS = SCE_CONTEXTS;
// Resource URLs can also be trusted by policy.
var resourceUrlWhitelist = ['self'],
resourceUrlBlacklist = [];
/**
* @ngdoc function
* @name ng.sceDelegateProvider#resourceUrlWhitelist
* @methodOf ng.$sceDelegateProvider
* @function
*
* @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
* provided. This must be an array.
*
* Each element of this array must either be a regex or the special string `'self'`.
*
* When a regex is used, it is matched against the normalized / absolute URL of the resource
* being tested.
*
* The **special string** `'self'` can be used to match against all URLs of the same domain as the
* application document with the same protocol (allows sourcing https resources from http documents.)
*
* Please note that **an empty whitelist array will block all URLs**!
*
* @return {Array} the currently set whitelist array.
*
* The **default value** when no whitelist has been explicitly set is `['self']`.
*
* @description
* Sets/Gets the whitelist of trusted resource URLs.
*/
this.resourceUrlWhitelist = function (value) {
if (arguments.length) {
resourceUrlWhitelist = value;
}
return resourceUrlWhitelist;
};
/**
* @ngdoc function
* @name ng.sceDelegateProvider#resourceUrlBlacklist
* @methodOf ng.$sceDelegateProvider
* @function
*
* @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
* provided. This must be an array.
*
* Each element of this array must either be a regex or the special string `'self'` (see
* `resourceUrlWhitelist` for meaning - it's only really useful there.)
*
* When a regex is used, it is matched against the normalized / absolute URL of the resource
* being tested.
*
* The typical usage for the blacklist is to **block [open redirects](http://cwe.mitre.org/data/definitions/601.html)**
* served by your domain as these would otherwise be trusted but actually return content from the redirected
* domain.
*
* Finally, **the blacklist overrides the whitelist** and has the final say.
*
* @return {Array} the currently set blacklist array.
*
* The **default value** when no whitelist has been explicitly set is the empty array (i.e. there is
* no blacklist.)
*
* @description
* Sets/Gets the blacklist of trusted resource URLs.
*/
this.resourceUrlBlacklist = function (value) {
if (arguments.length) {
resourceUrlBlacklist = value;
}
return resourceUrlBlacklist;
};
// Helper functions for matching resource urls by policy.
function isCompatibleProtocol(documentProtocol, resourceProtocol) {
return ((documentProtocol === resourceProtocol) ||
(documentProtocol === "http:" && resourceProtocol === "https:"));
}
this.$get = ['$log', '$document', '$injector', '$$urlUtils', function(
$log, $document, $injector, $$urlUtils) {
var htmlSanitizer = function htmlSanitizer(html) {
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
};
if ($injector.has('$sanitize')) {
htmlSanitizer = $injector.get('$sanitize');
}
function matchUrl(matcher, parsedUrl) {
if (matcher === 'self') {
return $$urlUtils.isSameOrigin(parsedUrl);
} else {
return !!parsedUrl.href.match(matcher);
}
}
function isResourceUrlAllowedByPolicy(url) {
var parsedUrl = $$urlUtils.resolve(url.toString(), true);
var i, n, allowed = false;
// Ensure that at least one item from the whitelist allows this url.
for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
allowed = true;
break;
}
}
if (allowed) {
// Ensure that no item from the blacklist blocked this url.
for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
allowed = false;
break;
}
}
}
return allowed;
}
function generateHolderType(base) {
var holderType = function TrustedValueHolderType(trustedValue) {
this.$$unwrapTrustedValue = function() {
return trustedValue;
};
};
if (base) {
holderType.prototype = new base();
}
holderType.prototype.valueOf = function sceValueOf() {
return this.$$unwrapTrustedValue();
}
holderType.prototype.toString = function sceToString() {
return this.$$unwrapTrustedValue().toString();
}
return holderType;
}
var trustedValueHolderBase = generateHolderType(),
byType = {};
byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
/**
* @ngdoc method
* @name ng.$sceDelegate#trustAs
* @methodOf ng.$sceDelegate
*
* @description
* Returns an object that is trusted by angular for use in specified strict
* contextual escaping contexts (such as ng-html-bind-unsafe, ng-include, any src
* attribute interpolation, any dom event binding attribute interpolation
* such as for onclick, etc.) that uses the provided value.
* See {@link ng.$sce $sce} for enabling strict contextual escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resourceUrl, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
function trustAs(type, trustedValue) {
var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (!constructor) {
throw $sceMinErr('icontext', 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
type, trustedValue);
}
if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
return trustedValue;
}
// All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
// mutable objects, we ensure here that the value passed in is actually a string.
if (typeof trustedValue !== 'string') {
throw $sceMinErr('itype',
'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
type);
}
return new constructor(trustedValue);
}
/**
* @ngdoc method
* @name ng.$sceDelegate#valueOf
* @methodOf ng.$sceDelegate
*
* @description
* If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
* ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
*
* If the passed parameter is not a value that had been returned by {@link
* ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
*
* @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
* call or anything else.
* @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns `value`
* unchanged.
*/
function valueOf(maybeTrusted) {
if (maybeTrusted instanceof trustedValueHolderBase) {
return maybeTrusted.$$unwrapTrustedValue();
} else {
return maybeTrusted;
}
}
/**
* @ngdoc method
* @name ng.$sceDelegate#getTrusted
* @methodOf ng.$sceDelegate
*
* @description
* Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and returns the
* originally supplied value if the queried context type is a supertype of the created type. If
* this condition isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} call.
* @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
*/
function getTrusted(type, maybeTrusted) {
if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
return maybeTrusted;
}
var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (constructor && maybeTrusted instanceof constructor) {
return maybeTrusted.$$unwrapTrustedValue();
}
// If we get here, then we may only take one of two actions.
// 1. sanitize the value for the requested type, or
// 2. throw an exception.
if (type === SCE_CONTEXTS.RESOURCE_URL) {
if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
return maybeTrusted;
} else {
throw $sceMinErr('insecurl',
'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', maybeTrusted.toString());
}
} else if (type === SCE_CONTEXTS.HTML) {
return htmlSanitizer(maybeTrusted);
}
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
}
return { trustAs: trustAs,
getTrusted: getTrusted,
valueOf: valueOf };
}];
}
/**
* @ngdoc object
* @name ng.$sceProvider
* @description
*
* The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
* - enable/disable Strict Contextual Escaping (SCE) in a module
* - override the default implementation with a custom delegate
*
* Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
*/
/**
* @ngdoc service
* @name ng.$sce
* @function
*
* @description
*
* `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
*
* # Strict Contextual Escaping
*
* Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
* contexts to result in a value that is marked as safe to use for that context One example of such
* a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer to these
* contexts as privileged or SCE contexts.
*
* As of version 1.2, Angular ships with SCE enabled by default.
*
* Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
* one to execute arbitrary javascript by the use of the expression() syntax. Refer
* <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
* You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
* to the top of your HTML document.
*
* SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
* security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
*
* Here's an example of a binding in a privileged context:
*
* <pre class="prettyprint">
* <input ng-model="userHtml">
* <div ng-bind-html="{{userHtml}}">
* </pre>
*
* Notice that `ng-bind-html` is bound to `{{userHtml}}` controlled by the user. With SCE
* disabled, this application allows the user to render arbitrary HTML into the DIV.
* In a more realistic example, one may be rendering user comments, blog articles, etc. via
* bindings. (HTML is just one example of a context where rendering user controlled input creates
* security vulnerabilities.)
*
* For the case of HTML, you might use a library, either on the client side, or on the server side,
* to sanitize unsafe HTML before binding to the value and rendering it in the document.
*
* How would you ensure that every place that used these types of bindings was bound to a value that
* was sanitized by your library (or returned as safe for rendering by your server?) How can you
* ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
* properties/fields and forgot to update the binding to the sanitized value?
*
* To be secure by default, you want to ensure that any such bindings are disallowed unless you can
* determine that something explicitly says it's safe to use a value for binding in that
* context. You can then audit your code (a simple grep would do) to ensure that this is only done
* for those values that you can easily tell are safe - because they were received from your server,
* sanitized by your library, etc. You can organize your codebase to help with this - perhaps
* allowing only the files in a specific directory to do this. Ensuring that the internal API
* exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
*
* In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} (and shorthand
* methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to obtain values that will be
* accepted by SCE / privileged contexts.
*
*
* ## How does it work?
*
* In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
* $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
* ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
* {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
*
* As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
* ng.$sce#parseHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
* simplified):
*
* <pre class="prettyprint">
* var ngBindHtmlDirective = ['$sce', function($sce) {
* return function(scope, element, attr) {
* scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
* element.html(value || '');
* });
* };
* }];
* </pre>
*
* ## Impact on loading templates
*
* This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
* `templateUrl`'s specified by {@link guide/directive directives}.
*
* By default, Angular only loads templates from the same domain and protocol as the application
* document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
* protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
* them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
*
* *Please note*:
* The browser's
* {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
* Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)}
* policy apply in addition to this and may further restrict whether the template is successfully
* loaded. This means that without the right CORS policy, loading templates from a different domain
* won't work on all browsers. Also, loading templates from `file://` URL does not work on some
* browsers.
*
* ## This feels like too much overhead for the developer?
*
* It's important to remember that SCE only applies to interpolation expressions.
*
* If your expressions are constant literals, they're automatically trusted and you don't need to
* call `$sce.trustAs` on them. (e.g.
* `<div ng-html-bind-unsafe="'<b>implicitly trusted</b>'"></div>`) just works.
*
* Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
* through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
*
* The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
* templates in `ng-include` from your application's domain without having to even know about SCE.
* It blocks loading templates from other domains or loading templates over http from an https
* served document. You can change these by setting your own custom {@link
* ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
* ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
*
* This significantly reduces the overhead. It is far easier to pay the small overhead and have an
* application that's secure and can be audited to verify that with much more ease than bolting
* security onto an application later.
*
* ## What trusted context types are supported?<a name="contexts"></a>
*
* | Context | Notes |
* |=====================|================|
* | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. |
* | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
* | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't consititute an SCE context. |
* | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contens are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
* | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
*
* ## Show me an example.
*
*
*
* @example
<example module="mySceApp">
<file name="index.html">
<div ng-controller="myAppController as myCtrl">
<i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
<b>User comments</b><br>
By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when $sanitize is available. If $sanitize isn't available, this results in an error instead of an exploit.
<div class="well">
<div ng-repeat="userComment in myCtrl.userComments">
<b>{{userComment.name}}</b>:
<span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
<br>
</div>
</div>
</div>
</file>
<file name="script.js">
var mySceApp = angular.module('mySceApp', ['ngSanitize']);
mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
var self = this;
$http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
self.userComments = userComments;
});
self.explicitlyTrustedHtml = $sce.trustAsHtml(
'<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
'sanitization."">Hover over this text.</span>');
});
</file>
<file name="test_data.json">
[
{ "name": "Alice",
"htmlComment": "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
},
{ "name": "Bob",
"htmlComment": "<i>Yes!</i> Am I the only other one?"
}
]
</file>
<file name="scenario.js">
describe('SCE doc demo', function() {
it('should sanitize untrusted values', function() {
expect(element('.htmlComment').html()).toBe('<span>Is <i>anyone</i> reading this?</span>');
});
it('should NOT sanitize explicitly trusted values', function() {
expect(element('#explicitlyTrustedHtml').html()).toBe(
'<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
'sanitization."">Hover over this text.</span>');
});
});
</file>
</example>
*
*
*
* ## Can I disable SCE completely?
*
* Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
* for little coding overhead. It will be much harder to take an SCE disabled application and
* either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
* for cases where you have a lot of existing code that was written before SCE was introduced and
* you're migrating them a module at a time.
*
* That said, here's how you can completely disable SCE:
*
* <pre class="prettyprint">
* angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
* // Completely disable SCE. For demonstration purposes only!
* // Do not use in new projects.
* $sceProvider.enabled(false);
* });
* </pre>
*
*/
function $SceProvider() {
var enabled = true;
/**
* @ngdoc function
* @name ng.sceProvider#enabled
* @methodOf ng.$sceProvider
* @function
*
* @param {boolean=} value If provided, then enables/disables SCE.
* @return {boolean} true if SCE is enabled, false otherwise.
*
* @description
* Enables/disables SCE and returns the current value.
*/
this.enabled = function (value) {
if (arguments.length) {
enabled = !!value;
}
return enabled;
};
/* Design notes on the default implementation for SCE.
*
* The API contract for the SCE delegate
* -------------------------------------
* The SCE delegate object must provide the following 3 methods:
*
* - trustAs(contextEnum, value)
* This method is used to tell the SCE service that the provided value is OK to use in the
* contexts specified by contextEnum. It must return an object that will be accepted by
* getTrusted() for a compatible contextEnum and return this value.
*
* - valueOf(value)
* For values that were not produced by trustAs(), return them as is. For values that were
* produced by trustAs(), return the corresponding input value to trustAs. Basically, if
* trustAs is wrapping the given values into some type, this operation unwraps it when given
* such a value.
*
* - getTrusted(contextEnum, value)
* This function should return the a value that is safe to use in the context specified by
* contextEnum or throw and exception otherwise.
*
* NOTE: This contract deliberately does NOT state that values returned by trustAs() must be opaque
* or wrapped in some holder object. That happens to be an implementation detail. For instance,
* an implementation could maintain a registry of all trusted objects by context. In such a case,
* trustAs() would return the same object that was passed in. getTrusted() would return the same
* object passed in if it was found in the registry under a compatible context or throw an
* exception otherwise. An implementation might only wrap values some of the time based on
* some criteria. getTrusted() might return a value and not throw an exception for special
* constants or objects even if not wrapped. All such implementations fulfill this contract.
*
*
* A note on the inheritance model for SCE contexts
* ------------------------------------------------
* I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
* is purely an implementation details.
*
* The contract is simply this:
*
* getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
* will also succeed.
*
* Inheritance happens to capture this in a natural way. In some future, we
* may not use inheritance anymore. That is OK because no code outside of
* sce.js and sceSpecs.js would need to be aware of this detail.
*/
this.$get = ['$parse', '$document', '$sceDelegate', function(
$parse, $document, $sceDelegate) {
// Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
// the "expression(javascript expression)" syntax which is insecure.
if (enabled && msie) {
var documentMode = $document[0].documentMode;
if (documentMode !== undefined && documentMode < 8) {
throw $sceMinErr('iequirks',
'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
}
}
var sce = copy(SCE_CONTEXTS);
/**
* @ngdoc function
* @name ng.sce#isEnabled
* @methodOf ng.$sce
* @function
*
* @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
* have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
*
* @description
* Returns a boolean indicating if SCE is enabled.
*/
sce.isEnabled = function () {
return enabled;
};
sce.trustAs = $sceDelegate.trustAs;
sce.getTrusted = $sceDelegate.getTrusted;
sce.valueOf = $sceDelegate.valueOf;
if (!enabled) {
sce.trustAs = sce.getTrusted = function(type, value) { return value; },
sce.valueOf = identity
}
/**
* @ngdoc method
* @name ng.$sce#parse
* @methodOf ng.$sce
*
* @description
* Converts Angular {@link guide/expression expression} into a function. This is like {@link
* ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
* wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
* *result*)}
*
* @param {string} type The kind of SCE context in which this result will be used.
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
sce.parseAs = function sceParseAs(type, expr) {
var parsed = $parse(expr);
if (parsed.literal && parsed.constant) {
return parsed;
} else {
return function sceParseAsTrusted(self, locals) {
return sce.getTrusted(type, parsed(self, locals));
}
}
};
/**
* @ngdoc method
* @name ng.$sce#trustAs
* @methodOf ng.$sce
*
* @description
* Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns an object
* that is trusted by angular for use in specified strict contextual escaping contexts (such as
* ng-html-bind-unsafe, ng-include, any src attribute interpolation, any dom event binding
* attribute interpolation such as for onclick, etc.) that uses the provided value. See *
* {@link ng.$sce $sce} for enabling strict contextual escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resource_url, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
/**
* @ngdoc method
* @name ng.$sce#trustAsHtml
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.trustAsHtml(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
* $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name ng.$sce#trustAsUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.trustAsUrl(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
* $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name ng.$sce#trustAsResourceUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.trustAsResourceUrl(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the return
* value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name ng.$sce#trustAsJs
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.trustAsJs(value)` → {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
* $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name ng.$sce#getTrusted
* @methodOf ng.$sce
*
* @description
* Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, takes
* the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the originally supplied
* value if the queried context type is a supertype of the created type. If this condition
* isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} call.
* @returns {*} The value the was originally provided to {@link ng.$sce#trustAs `$sce.trustAs`} if
* valid in this context. Otherwise, throws an exception.
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedHtml
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedHtml(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedCss
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedCss(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedUrl(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedResourceUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedResourceUrl(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to pass to `$sceDelegate.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedJs
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedJs(value)` → {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsHtml
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsHtml(expression string)` → {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsCss
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsCss(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsUrl(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsResourceUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsResourceUrl(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsJs
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsJs(value)` → {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
// Shorthand delegations.
var parse = sce.parseAs,
getTrusted = sce.getTrusted,
trustAs = sce.trustAs;
angular.forEach(SCE_CONTEXTS, function (enumValue, name) {
var lName = lowercase(name);
sce[camelCase("parse_as_" + lName)] = function (expr) {
return parse(enumValue, expr);
}
sce[camelCase("get_trusted_" + lName)] = function (value) {
return getTrusted(enumValue, value);
}
sce[camelCase("trust_as_" + lName)] = function (value) {
return trustAs(enumValue, value);
}
});
return sce;
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
* @requires $document
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
* @property {boolean} transitions Does the browser support CSS transition events ?
* @property {boolean} animations Does the browser support CSS animation events ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', '$document', function($window, $document) {
var eventSupport = {},
android = int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
document = $document[0] || {},
vendorPrefix,
vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
bodyStyle = document.body && document.body.style,
transitions = false,
animations = false,
match;
if (bodyStyle) {
for(var prop in bodyStyle) {
if(match = vendorRegex.exec(prop)) {
vendorPrefix = match[0];
vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
break;
}
}
transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
if (android && (!transitions||!animations)) {
transitions = isString(document.body.style.webkitTransition);
animations = isString(document.body.style.webkitAnimation);
}
}
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
history: !!($window.history && $window.history.pushState && !(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!document.documentMode || document.documentMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
csp: document.securityPolicy ? document.securityPolicy.isActive : false,
vendorPrefix: vendorPrefix,
transitions : transitions,
animations : animations
};
}];
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
function($rootScope, $browser, $q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc function
* @name ng.$timeout
* @requires $browser
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise, which will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, whose execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*/
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId, cleanup;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
if (!skipApply) $rootScope.$apply();
}, delay);
cleanup = function() {
delete deferreds[promise.$$timeoutId];
};
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
promise.then(cleanup, cleanup);
return promise;
}
/**
* @ngdoc function
* @name ng.$timeout#cancel
* @methodOf ng.$timeout
*
* @description
* Cancels a task associated with the `promise`. As a result of this, the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
function $$UrlUtilsProvider() {
this.$get = [function() {
var urlParsingNode = document.createElement("a"),
// NOTE: The usage of window and document instead of $window and $document here is
// deliberate. This service depends on the specific behavior of anchor nodes created by the
// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
// cause us to break tests. In addition, when the browser resolves a URL for XHR, it
// doesn't know about mocked locations and resolves URLs to the real document - which is
// exactly the behavior needed here. There is little value is mocking these our for this
// service.
originUrl = resolve(window.location.href, true);
/**
* @description
* Normalizes and optionally parses a URL.
*
* NOTE: This is a private service. The API is subject to change unpredictably in any commit.
*
* Implementation Notes for non-IE browsers
* ----------------------------------------
* Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
* results both in the normalizing and parsing of the URL. Normalizing means that a relative
* URL will be resolved into an absolute URL in the context of the application document.
* Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
* properties are all populated to reflect the normalized URL. This approach has wide
* compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
*
* Implementation Notes for IE
* ---------------------------
* IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
* browsers. However, the parsed components will not be set if the URL assigned did not specify
* them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
* work around that by performing the parsing in a 2nd step by taking a previously normalized
* URL (e.g. by assining to a.href) and assigning it a.href again. This correctly populates the
* properties such as protocol, hostname, port, etc.
*
* IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
* uses the inner HTML approach to assign the URL as part of an HTML snippet -
* http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
* Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
* Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
* method and IE < 8 is unsupported.
*
* References:
* http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
* http://url.spec.whatwg.org/#urlutils
* https://github.com/angular/angular.js/pull/2902
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* @param {string} url The URL to be parsed.
* @param {boolean=} parse When true, returns an object for the parsed URL. Otherwise, returns
* a single string that is the normalized URL.
* @returns {object|string} When parse is true, returns the normalized URL as a string.
* Otherwise, returns an object with the following members.
*
* | member name | Description |
* |===============|================|
* | href | A normalized version of the provided URL if it was not an absolute URL |
* | protocol | The protocol including the trailing colon |
* | host | The host and port (if the port is non-default) of the normalizedUrl |
*
* These fields from the UrlUtils interface are currently not needed and hence not returned.
*
* | member name | Description |
* |===============|================|
* | hostname | The host without the port of the normalizedUrl |
* | pathname | The path following the host in the normalizedUrl |
* | hash | The URL hash if present |
* | search | The query string |
*
*/
function resolve(url, parse) {
var href = url;
if (msie) {
// Normalize before parse. Refer Implementation Notes on why this is
// done in two steps on IE.
urlParsingNode.setAttribute("href", href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
if (!parse) {
return urlParsingNode.href;
}
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol,
host: urlParsingNode.host
// Currently unused and hence commented out.
// hostname: urlParsingNode.hostname,
// port: urlParsingNode.port,
// pathname: urlParsingNode.pathname,
// hash: urlParsingNode.hash,
// search: urlParsingNode.search
};
}
return {
resolve: resolve,
/**
* Parse a request URL and determine whether this is a same-origin request as the application document.
*
* @param {string|object} requestUrl The url of the request as a string that will be resolved
* or a parsed URL object.
* @returns {boolean} Whether the request is for the same origin as the application document.
*/
isSameOrigin: function isSameOrigin(requestUrl) {
var parsed = (typeof requestUrl === 'string') ? resolve(requestUrl, true) : requestUrl;
return (parsed.protocol === originUrl.protocol &&
parsed.host === originUrl.host);
}
};
}];
}
/**
* @ngdoc object
* @name ng.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overridden, removed or mocked for testing.
*
* Expressions, like the one defined for the `ngClick` directive in the example
* below, are evaluated with respect to the current scope. Therefore, there is
* no risk of inadvertently coding in a dependency on a global value in such an
* expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope, $window) {
$scope.$window = $window;
$scope.greeting = 'Hello, World!';
}
</script>
<div ng-controller="Ctrl">
<input type="text" ng-model="greeting" />
<button ng-click="$window.alert(greeting)">ALERT</button>
</div>
</doc:source>
<doc:scenario>
it('should display the greeting in the input box', function() {
input('greeting').enter('Hello, E2E Tests');
// If we click the button it will block the test runner
// element(':button').click();
});
</doc:scenario>
</doc:example>
*/
function $WindowProvider(){
this.$get = valueFn(window);
}
/**
* @ngdoc object
* @name ng.$filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To
* achieve this a filter definition consists of a factory function which is annotated with dependencies and is
* responsible for creating a filter function.
*
* <pre>
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* </pre>
*
* The filter function is registered with the `$injector` under the filter name suffix with `Filter`.
* <pre>
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* </pre>
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
* Guide.
*/
/**
* @ngdoc method
* @name ng.$filterProvider#register
* @methodOf ng.$filterProvider
* @description
* Register filter factory function.
*
* @param {String} name Name of the filter.
* @param {function} fn The filter factory function which is injectable.
*/
/**
* @ngdoc function
* @name ng.$filter
* @function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression [| filter_name[:parameter_value] ... ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
function register(name, factory) {
return $provide.factory(name + suffix, factory);
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
}
}];
////////////////////////////////////////
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name ng.filter:filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the value of `expression`
* string. All strings or objects with string properties in `array` that contain this string
* will be returned. The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filters. The function is
* called for each element of `array`. The final result is an array of those elements that
* the predicate returned true for.
*
* @param {function(expected, actual)|true|undefined} comparator Comparator which is used in
* determining if the expected value (from the filter expression) and actual value (from
* the object in the array) should be considered a match.
*
* Can be one of:
*
* - `function(expected, actual)`:
* The function will be given the object value and the predicate value to compare and
* should return true if the item should be included in filtered result.
*
* - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`.
* this is essentially strict comparison of expected and actual.
*
* - `false|undefined`: A short hand for a function which will look for a substring match in case
* insensitive way.
*
* @example
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
<hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"><br>
Equality <input type="checkbox" ng-model="strict"><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:search:strict">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', function() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Julie', 'Juliette']);
});
it('should use a equal comparison when comparator is true', function() {
input('search.name').enter('Julie');
input('strict').check();
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Julie']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression, comperator) {
if (!isArray(array)) return array;
var predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
switch(typeof comperator) {
case "function":
break;
case "boolean":
if(comperator == true) {
comperator = function(obj, text) {
return angular.equals(obj, text);
}
break;
}
default:
comperator = function(obj, text) {
text = (''+text).toLowerCase();
return (''+obj).toLowerCase().indexOf(text) > -1
};
}
var search = function(obj, text){
if (typeof text == 'string' && text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return comperator(obj, text);
case "object":
switch (typeof text) {
case "object":
return comperator(obj, text);
break;
default:
for ( var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
break;
}
return false;
case "array":
for ( var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
expression = {$:expression};
case "object":
for (var key in expression) {
if (key == '$') {
(function() {
if (!expression[key]) return;
var path = key
predicates.push(function(value) {
return search(value, expression[path]);
});
})();
} else {
(function() {
if (!expression[key]) return;
var path = key;
predicates.push(function(value) {
return search(getter(value,path), expression[path]);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered = [];
for ( var j = 0; j < array.length; j++) {
var value = array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
}
}
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount = 1234.56;
}
</script>
<div ng-controller="Ctrl">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} fractionSize Number of decimal places to round the number to.
* If this is not provided then the fraction size is computed from the current locale's number
* formatting pattern. In the case of the default locale, it will be 3.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val = 1234.56789;
}
</script>
<div ng-controller="Ctrl">
Enter number: <input ng-model='val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
var hasExponent = false;
if (numStr.indexOf('e') !== -1) {
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
numStr = '0';
} else {
formatedText = numStr;
hasExponent = true;
}
}
if (!hasExponent) {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var i = 0; i < pos; i++) {
if ((pos - i)%group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
} else {
if (fractionSize > 0 && number > -1 && number < 1) {
formatedText = number.toFixed(fractionSize);
}
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
offset = offset || 0;
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12 ) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var zone = -1 * date.getTimezoneOffset();
var paddedZone = (zone >= 0) ? "+" : "";
paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
padNumber(Math.abs(zone % 60), 2);
return paddedZone;
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
// while ISO 8601 requires fractions to be prefixed with `.` or `,`
// we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
sss: dateGetter('Milliseconds', 3),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING = /^\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h 'o''clock'"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
* specified in the string input, the time is considered to be in the local timezone.
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
// 1 2 3 4 5 6 7 8 9 10 11
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0,
dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
timeSetter = match[8] ? date.setUTCHours : date.setHours;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
var h = int(match[4]||0) - tzHour;
var m = int(match[5]||0) - tzMin
var s = int(match[6]||0);
var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
timeSetter.call(date, h, m, s, ms);
return date;
}
return string;
}
return function(date, format) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = int(date);
} else {
date = jsonStringToDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while(format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc function
* @name ng.filter:limitTo
* @function
*
* @description
* Creates a new array or string containing only a specified number of elements. The elements
* are taken from either the beginning or the end of the source array or string, as specified by
* the value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array|string} input Source array or string to be limited.
* @param {string|number} limit The length of the returned array or string. If the `limit` number
* is positive, `limit` number of items from the beginning of the source array/string are copied.
* If the number is negative, `limit` number of items from the end of the source array/string
* are copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
* had less than `limit` elements.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.letters = "abcdefghi";
$scope.numLimit = 3;
$scope.letterLimit = 3;
}
</script>
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
<p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
<p>Output letters: {{ letters | limitTo:letterLimit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the number array to first three items', function() {
expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3');
expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3');
expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]');
expect(binding('letters | limitTo:letterLimit')).toEqual('abc');
});
it('should update the output when -3 is entered', function() {
input('numLimit').enter(-3);
input('letterLimit').enter(-3);
expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]');
expect(binding('letters | limitTo:letterLimit')).toEqual('ghi');
});
it('should not exceed the maximum size of input array', function() {
input('numLimit').enter(100);
input('letterLimit').enter(100);
expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]');
expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter(){
return function(input, limit) {
if (!isArray(input) && !isString(input)) return input;
limit = int(limit);
if (isString(input)) {
//NaN check on limit
if (limit) {
return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
} else {
return "";
}
}
var out = [],
i, n;
// if abs(limit) exceeds maximum length, trim it
if (limit > input.length)
limit = input.length;
else if (limit < -input.length)
limit = -input.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = input.length + limit;
n = input.length;
}
for (; i<n; i++) {
out.push(input[i]);
}
return out;
}
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* @param {boolean=} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]
$scope.predicate = '-age';
}
</script>
<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('-age');
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate', function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
return function(array, sortPredicate, reverseOrder) {
if (!isArray(array)) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
sortPredicate = map(sortPredicate, function(predicate){
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
get = $parse(predicate);
}
return reverseComparator(function(a,b){
return compare(get(a),get(b));
}, descending);
});
var arrayCopy = [];
for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2){
for ( var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending)
? function(a,b){return comp(b,a);}
: comp;
}
function compare(v1, v2){
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
if (t1 == "string") v1 = v1.toLowerCase();
if (t1 == "string") v2 = v2.toLowerCase();
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
}
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/**
* @ngdoc directive
* @name ng.directive:a
* @restrict E
*
* @description
* Modifies the default behavior of html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* `<a href="" ng-click="model.$save()">Save</a>`
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
if (msie <= 8) {
// turn <a href ng-click="..">link</a> into a stylable link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!attr.href && !attr.name) {
attr.$set('href', '');
}
// add a comment node to anchors to workaround IE bug that causes element content to be reset
// to new attribute content if attribute is updated with value containing @ and element also
// contains value with @
// see issue #1949
element.append(document.createComment('IE fix'));
}
return function(scope, element) {
element.on('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr('href')) {
event.preventDefault();
}
});
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngHref
* @restrict A
*
* @description
* Using Angular markup like {{hash}} in an href attribute makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ngHref` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <a href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example uses `link` variable inside `href` attribute:
<doc:example>
<doc:source>
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</doc:source>
<doc:scenario>
it('should execute ng-click but not reload when href without value', function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng-click but not reload when href empty string', function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe(undefined);
});
it('should only change url when only ng-href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe('6');
element('#link-6').click();
expect(browser().location().url()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrc
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrcset
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrcset` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
* </pre>
*
* @element IMG
* @param {template} ngSrcset any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngDisabled
* @restrict A
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* <pre>
* <div ng-init="scope = { isDisabled: false }">
* <button disabled="{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specs do not require browsers to preserve the special attributes such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngDisabled` directive.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngDisabled Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngChecked` directive.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngChecked Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngReadonly` directive.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduced the `ngSelected` directive.
* @example
<doc:example>
<doc:source>
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element OPTION
* @param {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngOpen
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as open.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngOpen` directive.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" ng-model="open"><br/>
<details id="details" ng-open="open">
<summary>Show/Hide me</summary>
</details>
</doc:source>
<doc:scenario>
it('should toggle open', function() {
expect(element('#details').prop('open')).toBeFalsy();
input('open').check();
expect(element('#details').prop('open')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element DETAILS
* @param {string} expression Angular expression that will be evaluated.
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
// binding to multiple is not supported
if (propName == "multiple") return;
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 100,
compile: function() {
return function(scope, element, attr) {
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
attr.$set(attrName, !!value);
});
};
}
};
};
});
// ng-src, ng-srcset, ng-href are interpolated
forEach(['src', 'srcset', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
if (!value)
return;
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect.
// we use attr[attrName] value since $set can sanitize the url.
if (msie) element.prop(attrName, attr[attrName]);
});
}
};
};
});
var nullFormCtrl = {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop,
$setPristine: noop
};
/**
* @ngdoc object
* @name ng.directive:form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containing forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
*
* @property {Object} $error Is an object hash, containing references to all invalid controls or
* forms, where:
*
* - keys are validation tokens (error names) — such as `required`, `url` or `email`),
* - values are arrays of controls or forms that are invalid with given error.
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope'];
function FormController(element, attrs) {
var form = this,
parentForm = element.parent().controller('form') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
errors = form.$error = {},
controls = [];
// init state
form.$name = attrs.name || attrs.ngForm;
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:form.FormController#$addControl
* @methodOf ng.directive:form.FormController
*
* @description
* Register a control with the form.
*
* Input elements using ngModelController do this automatically when they are linked.
*/
form.$addControl = function(control) {
controls.push(control);
if (control.$name && !form.hasOwnProperty(control.$name)) {
form[control.$name] = control;
}
};
/**
* @ngdoc function
* @name ng.directive:form.FormController#$removeControl
* @methodOf ng.directive:form.FormController
*
* @description
* Deregister a control from the form.
*
* Input elements using ngModelController do this automatically when they are destroyed.
*/
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(errors, function(queue, validationToken) {
form.$setValidity(validationToken, true, control);
});
arrayRemove(controls, control);
};
/**
* @ngdoc function
* @name ng.directive:form.FormController#$setValidity
* @methodOf ng.directive:form.FormController
*
* @description
* Sets the validity of a form control.
*
* This method will also propagate to parent forms.
*/
form.$setValidity = function(validationToken, isValid, control) {
var queue = errors[validationToken];
if (isValid) {
if (queue) {
arrayRemove(queue, control);
if (!queue.length) {
invalidCount--;
if (!invalidCount) {
toggleValidCss(isValid);
form.$valid = true;
form.$invalid = false;
}
errors[validationToken] = false;
toggleValidCss(true, validationToken);
parentForm.$setValidity(validationToken, true, form);
}
}
} else {
if (!invalidCount) {
toggleValidCss(isValid);
}
if (queue) {
if (includes(queue, control)) return;
} else {
errors[validationToken] = queue = [];
invalidCount++;
toggleValidCss(false, validationToken);
parentForm.$setValidity(validationToken, false, form);
}
queue.push(control);
form.$valid = false;
form.$invalid = true;
}
};
/**
* @ngdoc function
* @name ng.directive:form.FormController#$setDirty
* @methodOf ng.directive:form.FormController
*
* @description
* Sets the form to a dirty state.
*
* This method can be called to add the 'ng-dirty' class and set the form to a dirty
* state (ng-dirty class). This method will also propagate to parent forms.
*/
form.$setDirty = function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
parentForm.$setDirty();
};
/**
* @ngdoc function
* @name ng.directive:form.FormController#$setPristine
* @methodOf ng.directive:form.FormController
*
* @description
* Sets the form to its pristine state.
*
* This method can be called to remove the 'ng-dirty' class and set the form to its pristine
* state (ng-pristine class). This method will also propagate to all the controls contained
* in this form.
*
* Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
* saving or resetting it.
*/
form.$setPristine = function () {
element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
form.$dirty = false;
form.$pristine = true;
forEach(controls, function(control) {
control.$setPristine();
});
};
}
/**
* @ngdoc directive
* @name ng.directive:ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name ng.directive:form
* @restrict E
*
* @description
* Directive that instantiates
* {@link ng.directive:form.FormController FormController}.
*
* If `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In angular forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this
* reason angular provides {@link ng.directive:ngForm `ngForm`} alias
* which behaves identical to `<form>` but allows form nesting.
*
*
* # CSS classes
* - `ng-valid` Is set if the form is valid.
* - `ng-invalid` Is set if the form is invalid.
* - `ng-pristine` Is set if the form is pristine.
* - `ng-dirty` Is set if the form is dirty.
*
*
* # Submitting a form and preventing default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in application specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This
* is because of the following form submission rules coming from the html spec:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.userType = 'guest';
}
</script>
<form name="myForm" ng-controller="Ctrl">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('userType').enter('');
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var formDirectiveFactory = function(isNgForm) {
return ['$timeout', function($timeout) {
var formDirective = {
name: 'form',
restrict: 'E',
controller: FormController,
compile: function() {
return {
pre: function(scope, formElement, attr, controller) {
if (!attr.action) {
// we can't use jq events because if a form is destroyed during submission the default
// action is not prevented. see #1238
//
// IE 9 is not affected because it doesn't fire a submit event and try to do a full
// page reload if the form was destroyed by submission of the form via a click handler
// on a button in the form. Looks like an IE9 specific bug.
var preventDefaultListener = function(event) {
event.preventDefault
? event.preventDefault()
: event.returnValue = false; // IE
};
addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
// unregister the preventDefault listener so that we don't not leak memory but in a
// way that will achieve the prevention of the default action.
formElement.on('$destroy', function() {
$timeout(function() {
removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
}, 0, false);
});
}
var parentFormCtrl = formElement.parent().controller('form'),
alias = attr.name || attr.ngForm;
if (alias) {
setter(scope, alias, controller, alias);
}
if (parentFormCtrl) {
formElement.on('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
setter(scope, alias, undefined, alias);
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
}
};
}
};
return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective;
}];
};
var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType = {
/**
* @ngdoc inputType
* @name ng.directive:input.text
*
* @description
* Standard HTML text input with angular data binding.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Adds `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trimming the
* input.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'guest';
$scope.word = /^\s*\w*\s*$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required ng-trim="false">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if multi word', function() {
input('text').enter('hello world');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should not be trimmed', function() {
input('text').enter('untrimmed ');
expect(binding('text')).toEqual('untrimmed ');
expect(binding('myForm.input.$valid')).toEqual('true');
});
</doc:scenario>
</doc:example>
*/
'text': textInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.number
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value = 12;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.number">
Not valid number!</span>
<tt>value = {{value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('value').enter('');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if over max', function() {
input('value').enter('123');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'number': numberInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.url
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'http://google.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('http://google.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not url', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'url': urlInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.email
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'me@example.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('me@example.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not email', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'email': emailInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.radio
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.color = 'blue';
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" value="green"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('color')).toEqual('blue');
input('color').select('red');
expect(binding('color')).toEqual('red');
});
</doc:scenario>
</doc:example>
*/
'radio': radioInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.checkbox
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngTrueValue The value to which the expression should be set when selected.
* @param {string=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}
</script>
<form name="myForm" ng-controller="Ctrl">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
input('value1').check();
input('value2').check();
expect(binding('value1')).toEqual('false');
expect(binding('value2')).toEqual('NO');
});
</doc:scenario>
</doc:example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop
};
function isEmpty(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener = function() {
var value = element.val();
// By default we will trim the value
// If the attribute ng-trim exists we will avoid trimming
// e.g. <input ng-model="foo" ng-trim="false">
if (toBoolean(attr.ngTrim || 'T')) {
value = trim(value);
}
if (ctrl.$viewValue !== value) {
scope.$apply(function() {
ctrl.$setViewValue(value);
});
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.on('input', listener);
} else {
var timeout;
var deferListener = function() {
if (!timeout) {
timeout = $browser.defer(function() {
listener();
timeout = null;
});
}
};
element.on('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
deferListener();
});
// if user paste into input using mouse, we need "change" event to catch it
element.on('change', listener);
// if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
if ($sniffer.hasEvent('paste')) {
element.on('paste cut', deferListener);
}
}
ctrl.$render = function() {
element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern = attr.ngPattern,
patternValidator,
match;
var validate = function(regexp, value) {
if (isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
match = pattern.match(/^\/(.*)\/([gim]*)$/);
if (match) {
pattern = new RegExp(match[1], match[2]);
patternValidator = function(value) {
return validate(pattern, value)
};
} else {
patternValidator = function(value) {
var patternObj = scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw minErr('ngPattern')('noregexp',
'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
patternObj, startingTag(element));
}
return validate(patternObj, value);
};
}
ctrl.$formatters.push(patternValidator);
ctrl.$parsers.push(patternValidator);
}
// min length validator
if (attr.ngMinlength) {
var minlength = int(attr.ngMinlength);
var minLengthValidator = function(value) {
if (!isEmpty(value) && value.length < minlength) {
ctrl.$setValidity('minlength', false);
return undefined;
} else {
ctrl.$setValidity('minlength', true);
return value;
}
};
ctrl.$parsers.push(minLengthValidator);
ctrl.$formatters.push(minLengthValidator);
}
// max length validator
if (attr.ngMaxlength) {
var maxlength = int(attr.ngMaxlength);
var maxLengthValidator = function(value) {
if (!isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
};
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty = isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value === '' ? null : (empty ? value : parseFloat(value));
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
ctrl.$formatters.push(function(value) {
return isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var min = parseFloat(attr.min);
var minValidator = function(value) {
if (!isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
if (attr.max) {
var max = parseFloat(attr.max);
var maxValidator = function(value) {
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
ctrl.$formatters.push(function(value) {
if (isEmpty(value) || isNumber(value)) {
ctrl.$setValidity('number', true);
return value;
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var urlValidator = function(value) {
if (isEmpty(value) || URL_REGEXP.test(value)) {
ctrl.$setValidity('url', true);
return value;
} else {
ctrl.$setValidity('url', false);
return undefined;
}
};
ctrl.$formatters.push(urlValidator);
ctrl.$parsers.push(urlValidator);
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var emailValidator = function(value) {
if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
ctrl.$formatters.push(emailValidator);
ctrl.$parsers.push(emailValidator);
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
element.on('click', function() {
if (element[0].checked) {
scope.$apply(function() {
ctrl.$setViewValue(attr.value);
});
}
});
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function checkboxInputType(scope, element, attr, ctrl) {
var trueValue = attr.ngTrueValue,
falseValue = attr.ngFalseValue;
if (!isString(trueValue)) trueValue = true;
if (!isString(falseValue)) falseValue = false;
element.on('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
ctrl.$formatters.push(function(value) {
return value === trueValue;
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name ng.directive:textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*/
/**
* @ngdoc directive
* @name ng.directive:input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {boolean=} ngRequired Sets `required` attribute if set to true
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}
</script>
<div ng-controller="Ctrl">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if empty when required', function() {
input('user.name').enter('');
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be valid if empty when min length is set', function() {
input('user.last').enter('');
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if less than required min length', function() {
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be invalid if longer than max length', function() {
input('user.last').enter('some ridiculously long name');
expect(binding('user'))
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attr, ctrl) {
if (ctrl) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
$browser);
}
}
};
}];
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty';
/**
* @ngdoc object
* @name ng.directive:ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bound to.
* @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
the control reads value from the DOM. Each function is called, in turn, passing the value
through to the next. Used to sanitize / convert the value as well as validation.
For validation, the parsers should update the validity state using
{@link ng.directive:ngModel.NgModelController#$setValidity $setValidity()},
and return `undefined` for invalid values.
*
* @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
the model value changes. Each function is called, in turn, passing the value through to the
next. Used to format / convert values for display in the control and validation.
* <pre>
* function formatter(value) {
* if (value) {
* return value.toUpperCase();
* }
* }
* ngModel.$formatters.push(formatter);
* </pre>
* @property {Object} $error An object hash with all errors as keys.
*
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The controller contains
* services for data-binding, validation, CSS update, value formatting and parsing. It
* specifically does not contain any logic which deals with DOM rendering or listening to
* DOM events. The `NgModelController` is meant to be extended by other directives where, the
* directive provides DOM manipulation and the `NgModelController` provides the data-binding.
* Note that you cannot use `NgModelController` in a directive with an isolated scope,
* as, in that case, the `ng-model` value gets put into the isolated scope and does not get
* propogated to the parent scope.
*
*
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* <example module="customControl">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if( attrs.stripBr && html == '<br>' ) {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
});
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="scenario.js">
it('should data-bind and become invalid', function() {
var contentEditable = element('[contenteditable]');
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
function($scope, $exceptionHandler, $attr, $element, $parse) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$name = $attr.name;
var ngModelGet = $parse($attr.ngModel),
ngModelSet = ngModelGet.assign;
if (!ngModelSet) {
throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
$attr.ngModel, startingTag($element));
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$render
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*/
this.$render = noop;
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
$error = this.$error = {}; // keep invalid keys here
// Setup initial state of the control
$element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setValidity
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Change the validity state, and notifies the form when the control changes validity. (i.e. it
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or formatter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
* to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
*/
this.$setValidity = function(validationErrorKey, isValid) {
if ($error[validationErrorKey] === !isValid) return;
if (isValid) {
if ($error[validationErrorKey]) invalidCount--;
if (!invalidCount) {
toggleValidCss(true);
this.$valid = true;
this.$invalid = false;
}
} else {
toggleValidCss(false);
this.$invalid = true;
this.$valid = false;
invalidCount++;
}
$error[validationErrorKey] = !isValid;
toggleValidCss(isValid, validationErrorKey);
parentForm.$setValidity(validationErrorKey, isValid, this);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setPristine
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Sets the control to its pristine state.
*
* This method can be called to remove the 'ng-dirty' class and set the control to its pristine
* state (ng-pristine class).
*/
this.$setPristine = function () {
this.$dirty = false;
this.$pristine = true;
$element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Read a value from view.
*
* This method should be called from within a DOM event handler.
* For example {@link ng.directive:input input} or
* {@link ng.directive:select select} directives call it.
*
* It internally calls all `$parsers` (including validators) and updates the `$modelValue` and the actual model path.
* Lastly it calls all registered change listeners.
*
* @param {string} value Value from the view.
*/
this.$setViewValue = function(value) {
this.$viewValue = value;
// change to dirty
if (this.$pristine) {
this.$dirty = true;
this.$pristine = false;
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
parentForm.$setDirty();
}
forEach(this.$parsers, function(fn) {
value = fn(value);
});
if (this.$modelValue !== value) {
this.$modelValue = value;
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
listener();
} catch(e) {
$exceptionHandler(e);
}
})
}
};
// model -> value
var ctrl = this;
$scope.$watch(function ngModelWatch() {
var value = ngModelGet($scope);
// if scope model value and ngModel value are out of sync
if (ctrl.$modelValue !== value) {
var formatters = ctrl.$formatters,
idx = formatters.length;
ctrl.$modelValue = value;
while(idx--) {
value = formatters[idx](value);
}
if (ctrl.$viewValue !== value) {
ctrl.$viewValue = value;
ctrl.$render();
}
}
});
}];
/**
* @ngdoc directive
* @name ng.directive:ngModel
*
* @element input
*
* @description
* Is a directive that tells Angular to do two-way data binding. It works together with `input`,
* `select`, `textarea` and even custom form controls that use {@link ng.directive:ngModel.NgModelController
* NgModelController} exposed by this directive.
*
* `ngModel` is responsible for:
*
* - binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require,
* - providing validation behavior (i.e. required, number, email, url),
* - keeping state of the control (valid/invalid, dirty/pristine, validation errors),
* - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
* - register the control with parent {@link ng.directive:form form}.
*
* Note: `ngModel` will try to bind to the property given by evaluating the expression on the
* current scope. If the property doesn't already exist on this scope, it will be created
* implicitly and added to the scope.
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link ng.directive:input.text text}
* - {@link ng.directive:input.checkbox checkbox}
* - {@link ng.directive:input.radio radio}
* - {@link ng.directive:input.number number}
* - {@link ng.directive:input.email email}
* - {@link ng.directive:input.url url}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
*/
var ngModelDirective = function() {
return {
require: ['ngModel', '^?form'],
controller: NgModelController,
link: function(scope, element, attr, ctrls) {
// notify others, especially parent forms
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
formCtrl.$addControl(modelCtrl);
element.on('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
* @restrict E
*
* @description
* Evaluate given expression when user changes the input.
* The expression is not evaluated when the value change is coming from the model.
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }
* </script>
* <div ng-controller="Controller">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* debug = {{confirmed}}<br />
* counter = {{counter}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should evaluate the expression if changing from view', function() {
* expect(binding('counter')).toEqual('0');
* element('#ng-change-example1').click();
* expect(binding('counter')).toEqual('1');
* expect(binding('confirmed')).toEqual('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element('#ng-change-example2').click();
* expect(binding('counter')).toEqual('0');
* expect(binding('confirmed')).toEqual('true');
* });
* </doc:scenario>
* </doc:example>
*/
var ngChangeDirective = valueFn({
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective = function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngList
*
* @description
* Text input that converts between comma-separated string into an array of strings.
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value. If
* specified in form `/something/` then the value will be converted into a regular expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names = ['igor', 'misko', 'vojta'];
}
</script>
<form name="myForm" ng-controller="Ctrl">
List: <input name="namesInput" ng-model="names" ng-list required>
<span class="error" ng-show="myForm.namesInput.$error.required">
Required!</span>
<br>
<tt>names = {{names}}</tt><br/>
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
expect(element('span.error').css('display')).toBe('none');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
expect(element('span.error').css('display')).not().toBe('none');
});
</doc:scenario>
</doc:example>
*/
var ngListDirective = function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match = /\/(.*)\//.exec(attr.ngList),
separator = match && new RegExp(match[1]) || attr.ngList || ',';
var parse = function(viewValue) {
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(', ');
}
return undefined;
});
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
var ngValueDirective = function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(value) {
attr.$set('value', value);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* It is preferrable to use `ngBind` instead of `{{ expression }}` when a template is momentarily
* displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
* element attribute, it makes the bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name = 'Whirled';
}
</script>
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text content should be replaced with the interpolation of the template
* in the `ngBindTemplate` attribute.
* Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
* expressions. This directive is needed since some HTML elements
* (such as TITLE and OPTION) cannot contain SPAN elements.
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}
</script>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
}
}];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtml
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
* ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
* is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
* core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to
* an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
* under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
*
* Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
* will have an exception (instead of an exploit.)
*
* @element ANY
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlDirective = ['$sce', function($sce) {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function ngBindHtmlWatchAction(value) {
element.html(value || '');
});
};
}];
function classDirective(name, selector) {
name = 'ngClass' + name;
return function() {
return {
restrict: 'AC',
link: function(scope, element, attr) {
var oldVal = undefined;
scope.$watch(attr[name], ngClassWatchAction, true);
attr.$observe('class', function(value) {
ngClassWatchAction(scope.$eval(attr[name]));
});
if (name !== 'ngClass') {
scope.$watch('$index', function($index, old$index) {
var mod = $index & 1;
if (mod !== old$index & 1) {
if (mod === selector) {
addClass(scope.$eval(attr[name]));
} else {
removeClass(scope.$eval(attr[name]));
}
}
});
}
function ngClassWatchAction(newVal) {
if (selector === true || scope.$index % 2 === selector) {
if (oldVal && !equals(newVal,oldVal)) {
removeClass(oldVal);
}
addClass(newVal);
}
oldVal = copy(newVal);
}
function removeClass(classVal) {
attr.$removeClass(flattenClasses(classVal));
}
function addClass(classVal) {
attr.$addClass(flattenClasses(classVal));
}
function flattenClasses(classVal) {
if(isArray(classVal)) {
return classVal.join(' ');
} else if (isObject(classVal)) {
var classes = [], i = 0;
forEach(classVal, function(v, k) {
if (v) {
classes.push(k);
}
});
return classes.join(' ');
}
return classVal;
};
}
};
};
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
*
* @description
* The `ngClass` allows you to set CSS classes on HTML an element, dynamically, by databinding
* an expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the
* new classes are added.
*
* @animations
* add - happens just before the class is applied to the element
* remove - happens just before the class is removed from the element
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values. In the case of a map, the
* names of the properties whose values are truthy will be added as css classes to the
* element.
*
* @example Example that demostrates basic bindings via ngClass directive.
<example>
<file name="index.html">
<p ng-class="{strike: strike, bold: bold, red: red}">Map Syntax Example</p>
<input type="checkbox" ng-model="bold"> bold
<input type="checkbox" ng-model="strike"> strike
<input type="checkbox" ng-model="red"> red
<hr>
<p ng-class="style">Using String Syntax</p>
<input type="text" ng-model="style" placeholder="Type: bold strike red">
<hr>
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1" placeholder="Type: bold"><br>
<input ng-model="style2" placeholder="Type: strike"><br>
<input ng-model="style3" placeholder="Type: red"><br>
</file>
<file name="style.css">
.strike {
text-decoration: line-through;
}
.bold {
font-weight: bold;
}
.red {
color: red;
}
</file>
<file name="scenario.js">
it('should let you toggle the class', function() {
expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/bold/);
expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/red/);
input('bold').check();
expect(element('.doc-example-live p:first').prop('className')).toMatch(/bold/);
input('red').check();
expect(element('.doc-example-live p:first').prop('className')).toMatch(/red/);
});
it('should let you toggle string example', function() {
expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('');
input('style').enter('red');
expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('red');
});
it('array example should have 3 classes', function() {
expect(element('.doc-example-live p:last').prop('className')).toBe('');
input('style1').enter('bold');
input('style2').enter('strike');
input('style3').enter('red');
expect(element('.doc-example-live p:last').prop('className')).toBe('bold strike red');
});
</file>
</example>
## Animations
Example that demostrates how addition and removal of classes can be animated.
<example animations="true">
<file name="index.html">
<input type="button" value="set" ng-click="myVar='my-class'">
<input type="button" value="clear" ng-click="myVar=''">
<br>
<span ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.my-class-add, .my-class-remove {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.my-class,
.my-class-add.my-class-add-active {
color: red;
font-size:3em;
}
.my-class-remove.my-class-remove-active {
font-size:1.0em;
color:black;
}
</file>
<file name="scenario.js">
it('should check ng-class', function() {
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
});
</file>
</example>
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but typically a fine-grained application is
* preferred in order to benefit from progressive rendering of the browser view.
*
* `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
* display: none !important;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head section of the html file;
* alternatively, the css rule (above) must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() {
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ng.directive:ngController
*
* @description
* The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — The Model is data in scope properties; scopes are attached to the DOM.
* * View — The template (HTML with data bindings) is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class has
* methods that typically express the business logic behind the application.
*
* Note that an alternative way to define controllers is via the {@link ngRoute.$route $route} service.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible constructor function or an
* {@link guide/expression expression} that on the current scope evaluates to a
* constructor function. The controller instance can further be published into the scope
* by adding `as localName` the controller name attribute.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
* for a manual update. The example is included in two different declaration styles based on
* your style preferences.
<doc:example>
<doc:source>
<script>
function SettingsController1() {
this.name = "John Smith";
this.contacts = [
{type: 'phone', value: '408 555 1212'},
{type: 'email', value: 'john.smith@example.org'} ];
};
SettingsController1.prototype.greet = function() {
alert(this.name);
};
SettingsController1.prototype.addContact = function() {
this.contacts.push({type: 'email', value: 'yourname@example.org'});
};
SettingsController1.prototype.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
SettingsController1.prototype.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
</script>
<div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
Name: <input type="text" ng-model="settings.name"/>
[ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in settings.contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="settings.clearContact(contact)">clear</a>
| <a href="" ng-click="settings.removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller as', function() {
expect(element('#ctrl-as-exmpl>:input').val()).toBe('John Smith');
expect(element('#ctrl-as-exmpl li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('#ctrl-as-exmpl li:nth-child(2) input').val())
.toBe('john.smith@example.org');
element('#ctrl-as-exmpl li:first a:contains("clear")').click();
expect(element('#ctrl-as-exmpl li:first input').val()).toBe('');
element('#ctrl-as-exmpl li:last a:contains("add")').click();
expect(element('#ctrl-as-exmpl li:nth-child(3) input').val())
.toBe('yourname@example.org');
});
</doc:scenario>
</doc:example>
<doc:example>
<doc:source>
<script>
function SettingsController2($scope) {
$scope.name = "John Smith";
$scope.contacts = [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'john.smith@example.org'} ];
$scope.greet = function() {
alert(this.name);
};
$scope.addContact = function() {
this.contacts.push({type:'email', value:'yourname@example.org'});
};
$scope.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
$scope.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
}
</script>
<div id="ctrl-exmpl" ng-controller="SettingsController2">
Name: <input type="text" ng-model="name"/>
[ <a href="" ng-click="greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="clearContact(contact)">clear</a>
| <a href="" ng-click="removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function() {
expect(element('#ctrl-exmpl>:input').val()).toBe('John Smith');
expect(element('#ctrl-exmpl li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('#ctrl-exmpl li:nth-child(2) input').val())
.toBe('john.smith@example.org');
element('#ctrl-exmpl li:first a:contains("clear")').click();
expect(element('#ctrl-exmpl li:first input').val()).toBe('');
element('#ctrl-exmpl li:last a:contains("add")').click();
expect(element('#ctrl-exmpl li:nth-child(3) input').val())
.toBe('yourname@example.org');
});
</doc:scenario>
</doc:example>
*/
var ngControllerDirective = [function() {
return {
scope: true,
controller: '@'
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
* @priority 1000
*
* @element html
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
*
* This is necessary when developing things like Google Chrome Extensions.
*
* CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
* For us to be compatible, we just need to implement the "getterFn" in $parse without violating
* any of these restrictions.
*
* AngularJS uses `Function(string)` generated functions as a speed optimization. By applying `ngCsp`
* it is be possible to opt into the CSP compatible mode. When this mode is on AngularJS will
* evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
* be raised.
*
* In order to use this feature put `ngCsp` directive on the root element of the application.
*
* @example
* This example shows how to apply the `ngCsp` directive to the `html` tag.
<pre>
<!doctype html>
<html ng-app ng-csp>
...
...
</html>
</pre>
*/
var ngCspDirective = ['$sniffer', function($sniffer) {
return {
priority: 1000,
compile: function() {
$sniffer.csp = true;
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*/
var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return function(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}];
}
);
/**
* @ngdoc directive
* @name ng.directive:ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* dblclick. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngKeydown
*
* @description
* Specify custom behavior on keydown event.
*
* @element ANY
* @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
* keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngKeyup
*
* @description
* Specify custom behavior on keyup event.
*
* @element ANY
* @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
* keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngKeypress
*
* @description
* Specify custom behavior on keypress event.
*
* @element ANY
* @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
* keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page) **but only if the form does not contain an `action`
* attribute**.
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if (this.text) {
this.list.push(this.text);
this.text = '';
}
};
}
</script>
<form ng-submit="submit()" ng-controller="Ctrl">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</doc:source>
<doc:scenario>
it('should check ng-submit', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
});
it('should ignore empty strings', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngFocus
*
* @description
* Specify custom behavior on focus event.
*
* @element window, input, select, textarea, a
* @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
* focus. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngBlur
*
* @description
* Specify custom behavior on blur event.
*
* @element window, input, select, textarea, a
* @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
* blur. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngIf
* @restrict A
*
* @description
* The `ngIf` directive removes and recreates a portion of the DOM tree (HTML)
* conditionally based on **"falsy"** and **"truthy"** values, respectively, evaluated within
* an {expression}. In other words, if the expression assigned to **ngIf evaluates to a false
* value** then **the element is removed from the DOM** and **if true** then **a clone of the
* element is reinserted into the DOM**.
*
* `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
* element in the DOM rather than changing its visibility via the `display` css property. A common
* case when this difference is significant is when using css selectors that rely on an element's
* position within the DOM (HTML), such as the `:first-child` or `:last-child` pseudo-classes.
*
* Note that **when an element is removed using ngIf its scope is destroyed** and **a new scope
* is created when the element is restored**. The scope created within `ngIf` inherits from
* its parent scope using
* {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}.
* An important implication of this is if `ngModel` is used within `ngIf` to bind to
* a javascript primitive defined in the parent scope. In this case any modifications made to the
* variable within the child scope will override (hide) the value in the parent scope.
*
* Also, `ngIf` recreates elements using their compiled state. An example scenario of this behavior
* is if an element's class attribute is directly modified after it's compiled, using something like
* jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
* the added class will be lost because the original compiled state is used to regenerate the element.
*
* Additionally, you can provide animations via the ngAnimate module to animate the **enter**
* and **leave** effects.
*
* @animations
* enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container
* leave - happens just before the ngIf contents are removed from the DOM
*
* @element ANY
* @scope
* @param {expression} ngIf If the {@link guide/expression expression} is falsy then
* the element is removed from the DOM tree (HTML).
*
* @example
<example animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
Show when checked:
<span ng-if="checked" class="animate-if">
I'm removed when the checkbox is unchecked.
</span>
</file>
<file name="animations.css">
.animate-if {
background:white;
border:1px solid black;
padding:10px;
}
.animate-if.ng-enter, .animate-if.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.animate-if.ng-enter,
.animate-if.ng-leave.ng-leave-active {
opacity:0;
}
.animate-if.ng-enter.ng-enter-active,
.animate-if.ng-leave {
opacity:1;
}
</file>
</example>
*/
var ngIfDirective = ['$animate', function($animate) {
return {
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'A',
compile: function (element, attr, transclude) {
return function ($scope, $element, $attr) {
var childElement, childScope;
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
if (childElement) {
$animate.leave(childElement);
childElement = undefined;
}
if (childScope) {
childScope.$destroy();
childScope = undefined;
}
if (toBoolean(value)) {
childScope = $scope.$new();
transclude(childScope, function (clone) {
childElement = clone;
$animate.enter(clone, $element.parent(), $element);
});
}
});
}
}
}
}];
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that:
*
* - by default, the template URL is restricted to the same domain and protocol as the
* application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on it. To load templates from other domains and/or protocols,
* you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
* {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. Refer Angular's {@link
* ng.$sce Strict Contextual Escaping}.
* - in addition, the browser's
* {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
* Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing
* (CORS)} policy apply that may further restrict whether the template is successfully loaded.
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for `file://`
* access on some browsers)
*
* @animations
* enter - animation is used to bring new content into the browser.
* leave - animation is used to animate existing content away.
*
* The enter and leave animation occur concurrently.
*
* @scope
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example animations="true">
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div class="example-animate-container">
<div class="include-example" ng-include="template.url"></div>
</div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'}
, { name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="animations.css">
.example-animate-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.example-animate-container > div {
padding:10px;
}
.include-example.ng-enter, .include-example.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
display:block;
padding:10px;
}
.include-example.ng-enter {
top:-50px;
}
.include-example.ng-enter.ng-enter-active {
top:0;
}
.include-example.ng-leave {
top:0;
}
.include-example.ng-leave.ng-leave-active {
top:50px;
}
</file>
<file name="scenario.js">
it('should load template1.html', function() {
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
select('template').option('1');
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
select('template').option('');
expect(element('.doc-example-live [ng-include]')).toBe(undefined);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentRequested
* @eventOf ng.directive:ngInclude
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted every time the ngInclude content is requested.
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
* @eventOf ng.directive:ngInclude
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var NG_INCLUDE_PRIORITY = 500;
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animate', '$sce',
function($http, $templateCache, $anchorScroll, $compile, $animate, $sce) {
return {
restrict: 'ECA',
terminal: true,
priority: NG_INCLUDE_PRIORITY,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
element.html('');
var anchor = jqLite(document.createComment(' ngInclude: ' + srcExp + ' '));
element.replaceWith(anchor);
return function(scope) {
var changeCounter = 0,
currentScope,
currentElement;
var cleanupLastIncludeContent = function() {
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if(currentElement) {
$animate.leave(currentElement);
currentElement = null;
}
};
scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) return;
var newScope = scope.$new();
cleanupLastIncludeContent();
currentScope = newScope;
currentElement = element.clone();
currentElement.html(response);
$animate.enter(currentElement, null, anchor);
$compile(currentElement, false, NG_INCLUDE_PRIORITY - 1)(currentScope);
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
currentScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId === changeCounter) cleanupLastIncludeContent();
});
scope.$emit('$includeContentRequested');
} else {
cleanupLastIncludeContent();
}
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInit
*
* @description
* The `ngInit` directive specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function() {
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</doc:scenario>
</doc:example>
*/
var ngInitDirective = ngDirective({
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
* @priority 1000
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) is present, but the one
* wrapped in `ngNonBindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng-non-bindable', function() {
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/**
* @ngdoc directive
* @name ng.directive:ngPluralize
* @restrict EA
*
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js, but can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a plural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. There are examples of plural categories
* and explicit number rules throughout the rest of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object.
*
* The following example shows how to configure ngPluralize:
*
* <pre>
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its corresponding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}
</script>
<div ng-controller="Ctrl">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function() {
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function() {
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
var BRACE = /{}/g;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp) || {},
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
isWhen = /^when(Minus)?(.+)$/;
forEach(attr, function(expression, attributeName) {
if (isWhen.test(attributeName)) {
whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
element.attr(attr.$attr[attributeName]);
}
});
forEach(whens, function(expression, key) {
whensExpFns[key] =
$interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
offset + endSymbol));
});
scope.$watch(function ngPluralizeWatch() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!(value in whens)) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function ngPluralizeWatchAction(newVal) {
element.text(newVal);
});
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* | Variable | Type | Details |
* |-----------|-----------------|-----------------------------------------------------------------------------|
* | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
* | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
* | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
* | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
* | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
* | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
*
*
* # Special repeat start and end points
* To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
* the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
* The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
* up to and including the ending HTML tag where **ng-repeat-end** is placed.
*
* The example below makes use of this feature:
* <pre>
* <header ng-repeat-start="item in items">
* Header {{ item }}
* </header>
* <div class="body">
* Body {{ item }}
* </div>
* <footer ng-repeat-end>
* Footer {{ item }}
* </footer>
* </pre>
*
* And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
* <pre>
* <header>
* Header A
* </header>
* <div class="body">
* Body A
* </div>
* <footer>
* Footer A
* </footer>
* <header>
* Header B
* </header>
* <div class="body">
* Body B
* </div>
* <footer>
* Footer B
* </footer>
* </pre>
*
* The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
* as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
*
* @animations
* enter - when a new item is added to the list or when an item is revealed after a filter
* leave - when an item is removed from the list or when an item is filtered out
* move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `album in artist.albums`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
* which can be used to associate the objects in the collection with the DOM elements. If no tracking function
* is specified the ng-repeat associates elements by identity in the collection. It is an error to have
* more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
* mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
* before specifying a tracking expression.
*
* For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements
* will be associated by item identity in the array.
*
* For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
* `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
* with the corresponding item in the array by identity. Moving the same object in array would move the DOM
* element in the same way ian the DOM.
*
* For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
* case the object identity does not matter. Two objects are considered equivalent as long as their `id`
* property is same.
*
* For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
* to items in conjunction with a tracking expression.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<example animations="true">
<file name="index.html">
<div ng-init="friends = [
{name:'John', age:25, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:28, gender:'girl'},
{name:'Joy', age:15, gender:'girl'},
{name:'Mary', age:28, gender:'girl'},
{name:'Peter', age:95, gender:'boy'},
{name:'Sebastian', age:50, gender:'boy'},
{name:'Erika', age:27, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:60, gender:'girl'}
]">
I have {{friends.length}} friends. They are:
<input type="search" ng-model="q" placeholder="filter friends..." />
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="friend in friends | filter:q">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</file>
<file name="animations.css">
.example-animate-container {
background:white;
border:1px solid black;
list-style:none;
margin:0;
padding:0;
}
.example-animate-container > li {
padding:10px;
list-style:none;
}
.animate-repeat.ng-enter,
.animate-repeat.ng-leave,
.animate-repeat.ng-move {
-webkit-transition:all linear 0.5s;
-moz-transition:all linear 0.5s;
-o-transition:all linear 0.5s;
transition:all linear 0.5s;
}
.animate-repeat.ng-enter {
line-height:0;
opacity:0;
padding-top:0;
padding-bottom:0;
}
.animate-repeat.ng-enter.ng-enter-active {
line-height:20px;
opacity:1;
padding:10px;
}
.animate-repeat.ng-leave {
opacity:1;
line-height:20px;
padding:10px;
}
.animate-repeat.ng-leave.ng-leave-active {
opacity:0;
line-height:0;
padding-top:0;
padding-bottom:0;
}
.animate-repeat.ng-move { }
.animate-repeat.ng-move.ng-move-active { }
</file>
<file name="scenario.js">
it('should render initial data set', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(10);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Jessie","30"]);
expect(r.row(9)).toEqual(["10","Samantha","60"]);
expect(binding('friends.length')).toBe("10");
});
it('should update repeater when filter predicate changes', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(10);
input('q').enter('ma');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","Mary","28"]);
expect(r.row(1)).toEqual(["2","Samantha","60"]);
});
</file>
</example>
*/
var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
var NG_REMOVED = '$$NG_REMOVED';
var ngRepeatMinErr = minErr('ngRepeat');
return {
transclude: 'element',
priority: 1000,
terminal: true,
compile: function(element, attr, linker) {
return function($scope, $element, $attr){
var expression = $attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),
trackByExp, trackByExpGetter, trackByIdFn, trackByIdArrayFn, trackByIdObjFn, lhs, rhs, valueIdentifier, keyIdentifier,
hashFnLocals = {$id: hashKey};
if (!match) {
throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
lhs = match[1];
rhs = match[2];
trackByExp = match[4];
if (trackByExp) {
trackByExpGetter = $parse(trackByExp);
trackByIdFn = function(key, value, index) {
// assign key, value, and $index to the locals so that they can be used in hash functions
if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
hashFnLocals[valueIdentifier] = value;
hashFnLocals.$index = index;
return trackByExpGetter($scope, hashFnLocals);
};
} else {
trackByIdArrayFn = function(key, value) {
return hashKey(value);
}
trackByIdObjFn = function(key) {
return key;
}
}
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
lhs);
}
valueIdentifier = match[3] || match[1];
keyIdentifier = match[2];
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
var lastBlockMap = {};
//watch props
$scope.$watchCollection(rhs, function ngRepeatAction(collection){
var index, length,
previousNode = $element[0], // current position of the node
nextNode,
// Same as lastBlockMap but it has the current state. It will become the
// lastBlockMap on the next iteration.
nextBlockMap = {},
arrayLength,
childScope,
key, value, // key/value of iteration
trackById,
collectionKeys,
block, // last object information {scope, element, id}
nextBlockOrder = [];
if (isArrayLike(collection)) {
collectionKeys = collection;
trackByIdFn = trackByIdFn || trackByIdArrayFn;
} else {
trackByIdFn = trackByIdFn || trackByIdObjFn;
// if object, extract keys, sort them and use to determine order of iteration over obj props
collectionKeys = [];
for (key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
collectionKeys.push(key);
}
}
collectionKeys.sort();
}
arrayLength = collectionKeys.length;
// locate existing items
length = nextBlockOrder.length = collectionKeys.length;
for(index = 0; index < length; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
trackById = trackByIdFn(key, value, index);
if(lastBlockMap.hasOwnProperty(trackById)) {
block = lastBlockMap[trackById]
delete lastBlockMap[trackById];
nextBlockMap[trackById] = block;
nextBlockOrder[index] = block;
} else if (nextBlockMap.hasOwnProperty(trackById)) {
// restore lastBlockMap
forEach(nextBlockOrder, function(block) {
if (block && block.startNode) lastBlockMap[block.id] = block;
});
// This is a duplicate and we need to throw an error
throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
expression, trackById);
} else {
// new never before seen block
nextBlockOrder[index] = { id: trackById };
nextBlockMap[trackById] = false;
}
}
// remove existing items
for (key in lastBlockMap) {
if (lastBlockMap.hasOwnProperty(key)) {
block = lastBlockMap[key];
$animate.leave(block.elements);
forEach(block.elements, function(element) { element[NG_REMOVED] = true});
block.scope.$destroy();
}
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0, length = collectionKeys.length; index < length; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
block = nextBlockOrder[index];
if (block.startNode) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = block.scope;
nextNode = previousNode;
do {
nextNode = nextNode.nextSibling;
} while(nextNode && nextNode[NG_REMOVED]);
if (block.startNode == nextNode) {
// do nothing
} else {
// existing item which got moved
$animate.move(block.elements, null, jqLite(previousNode));
}
previousNode = block.endNode;
} else {
// new item which we don't know about
childScope = $scope.$new();
}
childScope[valueIdentifier] = value;
if (keyIdentifier) childScope[keyIdentifier] = key;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === (arrayLength - 1));
childScope.$middle = !(childScope.$first || childScope.$last);
childScope.$odd = !(childScope.$even = index%2==0);
if (!block.startNode) {
linker(childScope, function(clone) {
$animate.enter(clone, null, jqLite(previousNode));
previousNode = clone;
block.scope = childScope;
block.startNode = clone[0];
block.elements = clone;
block.endNode = clone[clone.length - 1];
nextBlockMap[block.id] = block;
});
}
}
lastBlockMap = nextBlockMap;
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` directive shows and hides the given HTML element conditionally based on the expression
* provided to the ngShow attribute. The show and hide mechanism is a achieved by removing and adding
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is a predefined CSS class present
* in AngularJS which sets the display style to none (using an !important flag).
*
* <pre>
* <!-- when $scope.myValue is truthy (element is visible) -->
* <div ng-show="myValue"></div>
*
* <!-- when $scope.myValue is falsy (element is hidden) -->
* <div ng-show="myValue" class="ng-hide"></div>
* </pre>
*
* When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute
* on the element causing it to become hidden. When true, the ng-hide CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding .ng-hide
*
* If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
* restating the styles for the .ng-hide class in CSS:
* <pre>
* .ng-hide {
* //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
* display:block!important;
*
* //this is just another form of hiding an element
* position:absolute;
* top:-9999px;
* left:-9999px;
* }
* </pre>
*
* Just remember to include the important flag so the CSS override will function.
*
* ## A note about animations with ngShow
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works similar to the animation system present with ngClass, however, the
* only difference is that you must also include the !important flag to override the display property so
* that you can perform an animation when the element is hidden during the time of the animation.
*
* <pre>
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* transition:0.5s linear all;
* display:block!important;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* </pre>
*
* @animations
* addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible
* removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<example animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked"><br/>
<div>
Show:
<div class="check-element animate-show" ng-show="checked">
<span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-show" ng-hide="checked">
<span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="animations.css">
.animate-show.ng-hide-add,
.animate-show.ng-hide-remove {
-webkit-transition:all linear 0.5s;
-moz-transition:all linear 0.5s;
-o-transition:all linear 0.5s;
transition:all linear 0.5s;
display:block!important;
}
.animate-show.ng-hide-add.ng-hide-add-active,
.animate-show.ng-hide-remove {
line-height:0;
opacity:0;
padding:0 10px;
}
.animate-show.ng-hide-add,
.animate-show.ng-hide-remove.ng-hide-remove-active {
line-height:20px;
opacity:1;
padding:10px;
border:1px solid black;
background:white;
}
.check-element {
padding:10px;
border:1px solid black;
background:white;
}
</file>
<file name="scenario.js">
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</file>
</example>
*/
var ngShowDirective = ['$animate', function($animate) {
return function(scope, element, attr) {
scope.$watch(attr.ngShow, function ngShowWatchAction(value){
$animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
});
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` directive shows and hides the given HTML element conditionally based on the expression
* provided to the ngHide attribute. The show and hide mechanism is a achieved by removing and adding
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is a predefined CSS class present
* in AngularJS which sets the display style to none (using an !important flag).
*
* <pre>
* <!-- when $scope.myValue is truthy (element is hidden) -->
* <div ng-hide="myValue"></div>
*
* <!-- when $scope.myValue is falsy (element is visible) -->
* <div ng-hide="myValue" class="ng-hide"></div>
* </pre>
*
* When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute
* on the element causing it to become hidden. When false, the ng-hide CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding .ng-hide
*
* If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
* restating the styles for the .ng-hide class in CSS:
* <pre>
* .ng-hide {
* //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
* display:block!important;
*
* //this is just another form of hiding an element
* position:absolute;
* top:-9999px;
* left:-9999px;
* }
* </pre>
*
* Just remember to include the important flag so the CSS override will function.
*
* ## A note about animations with ngHide
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works similar to the animation system present with ngClass, however, the
* only difference is that you must also include the !important flag to override the display property so
* that you can perform an animation when the element is hidden during the time of the animation.
*
* <pre>
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* transition:0.5s linear all;
* display:block!important;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* </pre>
*
* @animations
* removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
* addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
* the element is shown or hidden respectively.
*
* @example
<example animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked"><br/>
<div>
Show:
<div class="check-element animate-hide" ng-show="checked">
<span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-hide" ng-hide="checked">
<span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="animations.css">
.animate-hide.ng-hide-add,
.animate-hide.ng-hide-remove {
-webkit-transition:all linear 0.5s;
-moz-transition:all linear 0.5s;
-o-transition:all linear 0.5s;
transition:all linear 0.5s;
display:block!important;
}
.animate-hide.ng-hide-add.ng-hide-add-active,
.animate-hide.ng-hide-remove {
line-height:0;
opacity:0;
padding:0 10px;
}
.animate-hide.ng-hide-add,
.animate-hide.ng-hide-remove.ng-hide-remove-active {
line-height:20px;
opacity:1;
padding:10px;
border:1px solid black;
background:white;
}
.check-element {
padding:10px;
border:1px solid black;
background:white;
}
</file>
<file name="scenario.js">
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1);
expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1);
});
</file>
</example>
*/
var ngHideDirective = ['$animate', function($animate) {
return function(scope, element, attr) {
scope.$watch(attr.ngHide, function ngHideWatchAction(value){
$animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
});
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngStyle
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myStyle={color:'red'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="scenario.js">
it('should check ng-style', function() {
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ng.directive:ngSwitch
* @restrict EA
*
* @description
* The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression.
* Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location
* as specified in the template.
*
* The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
* from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element
* matches the value obtained from the evaluated expression. In other words, you define a container element
* (where you place the directive), place an expression on the **on="..." attribute**
* (or the **ng-switch="..." attribute**), define any inner elements inside of the directive and place
* a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
* expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
* attribute is displayed.
*
* @animations
* enter - happens after the ngSwtich contents change and the matched child element is placed inside the container
* leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
*
* @usage
* <ANY ng-switch="expression">
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* <ANY ng-switch-default>...</ANY>
* </ANY>
*
* @scope
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* @paramDescription
* On child elements add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed. If the same match appears multiple times, all the
* elements will be displayed.
* * `ngSwitchDefault`: the default case when no other case match. If there
* are multiple default cases, all of them will be displayed when no other
* case match.
*
*
* @example
<example animations="true">
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div class="animate-switch-container"
ng-switch on="selection">
<div ng-switch-when="settings">Settings Div</div>
<div ng-switch-when="home">Home Span</div>
<div ng-switch-default>default</div>
</div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}
</file>
<file name="animations.css">
.animate-switch-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.animate-switch-container > div {
padding:10px;
}
.animate-switch-container > .ng-enter,
.animate-switch-container > .ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
-o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}
.animate-switch-container > .ng-enter {
top:-50px;
}
.animate-switch-container > .ng-enter.ng-enter-active {
top:0;
}
.animate-switch-container > .ng-leave {
top:0;
}
.animate-switch-container > .ng-leave.ng-leave-active {
top:50px;
}
</file>
<file name="scenario.js">
it('should start in settings', function() {
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select('selection').option('home');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
});
it('should select default', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
});
</file>
</example>
*/
var ngSwitchDirective = ['$animate', function($animate) {
return {
restrict: 'EA',
require: 'ngSwitch',
// asks for $scope to fool the BC controller module
controller: ['$scope', function ngSwitchController() {
this.cases = {};
}],
link: function(scope, element, attr, ngSwitchController) {
var watchExpr = attr.ngSwitch || attr.on,
selectedTranscludes,
selectedElements,
selectedScopes = [];
scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
for (var i= 0, ii=selectedScopes.length; i<ii; i++) {
selectedScopes[i].$destroy();
$animate.leave(selectedElements[i]);
}
selectedElements = [];
selectedScopes = [];
if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
scope.$eval(attr.change);
forEach(selectedTranscludes, function(selectedTransclude) {
var selectedScope = scope.$new();
selectedScopes.push(selectedScope);
selectedTransclude.transclude(selectedScope, function(caseElement) {
var anchor = selectedTransclude.element;
selectedElements.push(caseElement);
$animate.enter(caseElement, anchor.parent(), anchor);
});
});
}
});
}
}
}];
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 500,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: transclude, element: element });
};
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 500,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['?'] = (ctrl.cases['?'] || []);
ctrl.cases['?'].push({ transclude: transclude, element: element });
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
*
* @description
* Insert the transcluded DOM here.
*
* @element ANY
*
* @example
<doc:example module="transclude">
<doc:source>
<script>
function Ctrl($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: { title:'@' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
</script>
<div ng-controller="Ctrl">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</doc:source>
<doc:scenario>
it('should have transcluded', function() {
input('title').enter('TITLE');
input('text').enter('TEXT');
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
});
</doc:scenario>
</doc:example>
*
*/
var ngTranscludeDirective = ngDirective({
controller: ['$transclude', '$element', '$scope', function($transclude, $element, $scope) {
// use evalAsync so that we don't process transclusion before directives on the parent element even when the
// transclusion replaces the current element. (we can't use priority here because that applies only to compile fns
// and not controllers
$scope.$evalAsync(function() {
$transclude(function(clone) {
$element.append(clone);
});
});
}]
});
/**
* @ngdoc directive
* @name ng.directive:script
*
* @description
* Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
* template can be used by `ngInclude`, `ngView` or directive templates.
*
* @restrict E
* @param {'text/ng-template'} type must be set to `'text/ng-template'`
*
* @example
<doc:example>
<doc:source>
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</doc:source>
<doc:scenario>
it('should load template defined inside script tag', function() {
element('#tpl-link').click();
expect(element('#tpl-content').text()).toMatch(/Content of the template/);
});
</doc:scenario>
</doc:example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
// IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for a `<select>` element using an array or an object obtained by evaluating the
* `ngOptions` expression.
*
* When an item in the `<select>` menu is selected, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
* of {@link ng.directive:ngRepeat ngRepeat} when you want the
* `select` model to be bound to a non-string value. This is because an option element can currently
* be bound to string values only.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required The control is considered valid only if value is entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
* * `trackexpr`: Used when working with an array of objects. The result of this expression will be
* used to identify the objects in the array. The `trackexpr` will most likely refer to the
* `value` variable (e.g. `value.propertyName`).
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // red
}
</script>
<div ng-controller="MyCntrl">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng-options', function() {
expect(binding('{selected_color:color}')).toMatch('red');
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
var ngOptionsDirective = valueFn({ terminal: true });
var selectDirective = ['$compile', '$parse', function($compile, $parse) {
//0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000007777000000000000000000088888
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/,
nullModelCtrl = {$setViewValue: noop};
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = {},
ngModelCtrl = nullModelCtrl,
nullOption,
unknownOption;
self.databound = $attrs.ngModel;
self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
ngModelCtrl = ngModelCtrl_;
nullOption = nullOption_;
unknownOption = unknownOption_;
}
self.addOption = function(value) {
optionsMap[value] = true;
if (ngModelCtrl.$viewValue == value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
};
self.removeOption = function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue == value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
}
self.hasOption = function(value) {
return optionsMap.hasOwnProperty(value);
}
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
}],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl = ctrls[0],
ngModelCtrl = ctrls[1],
multiple = attr.multiple,
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate =jqLite(document.createElement('optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
if (children[i].value == '') {
emptyOption = nullOption = children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator = function(value) {
ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
return value;
};
ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);
attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}
if (optionsExp) Options(scope, element, ngModelCtrl);
else if (multiple) Multiple(scope, element, ngModelCtrl);
else Single(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.on('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function Multiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render = function() {
var items = new HashMap(ctrl.$viewValue);
forEach(selectElement.find('option'), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
scope.$watch(function selectMultipleWatch() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView = copy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.on('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.find('option'), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function Options(scope, selectElement, ctrl) {
var match;
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw minErr('ngOptions')('iexp',
"Expected expression in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_' but got '{0}'. Element: {1}",
optionsExp, startingTag(selectElement));
}
var displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]),
track = match[8],
trackFn = track ? $parse(match[8]) : null,
// This is an array of array of existing option groups in DOM. We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.html('') because otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.html('');
selectElement.on('change', function() {
scope.$apply(function() {
var optionGroup,
collection = valuesFn(scope) || [],
locals = {},
key, value, optionElement, index, groupIndex, length, groupLength;
if (multiple) {
value = [];
for (groupIndex = 0, groupLength = optionGroupsCache.length;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[groupIndex];
for(index = 1, length = optionGroup.length; index < length; index++) {
if ((optionElement = optionGroup[index].element)[0].selected) {
key = optionElement.val();
if (keyName) locals[keyName] = key;
if (trackFn) {
for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) {
locals[valueName] = collection[trackIndex];
if (trackFn(scope, locals) == key) break;
}
} else {
locals[valueName] = collection[key];
}
value.push(valueFn(scope, locals));
}
}
}
} else {
key = selectElement.val();
if (key == '?') {
value = undefined;
} else if (key == ''){
value = null;
} else {
if (trackFn) {
for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) {
locals[valueName] = collection[trackIndex];
if (trackFn(scope, locals) == key) {
value = valueFn(scope, locals);
break;
}
}
} else {
locals[valueName] = collection[key];
if (keyName) locals[keyName] = key;
value = valueFn(scope, locals);
}
}
}
ctrl.$setViewValue(value);
});
});
ctrl.$render = render;
// TODO(vojta): can't we optimize this ?
scope.$watch(render);
function render() {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue = ctrl.$modelValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
groupLength, length,
groupIndex, index,
locals = {},
selected,
selectedSet = false, // nothing is selected yet
lastElement,
element,
label;
if (multiple) {
if (trackFn && isArray(modelValue)) {
selectedSet = new HashMap([]);
for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
locals[valueName] = modelValue[trackIndex];
selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
}
} else {
selectedSet = new HashMap(modelValue);
}
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
optionGroupName = groupByFn(scope, locals) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected = selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) != undefined;
} else {
if (trackFn) {
var modelCast = {};
modelCast[valueName] = modelValue;
selected = trackFn(scope, modelCast) === trackFn(scope, locals);
} else {
selected = modelValue === valueFn(scope, locals);
}
selectedSet = selectedSet || selected; // see if at least one item is selected
}
label = displayFn(scope, locals); // what will be seen by the user
label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values
optionGroup.push({
id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index), // either the index into array or key from object
label: label,
selected: selected // determine if we should be selected
});
}
if (!multiple) {
if (nullOption || modelValue === null) {
// insert null option if we have a placeholder, or the model is null
optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
} else if (!selectedSet) {
// option could not be found, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
};
existingOptions = [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the beginning
for(index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index+1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label = option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
// lastElement.prop('selected') provided by jQuery has side-effects
if (lastElement[0].selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
}
} else {
// grow elements
// if it's a null option
if (option.id === '' && nullOption) {
// put back the pre-compiled element
element = nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
}
}
}
}
}];
var optionDirective = ['$interpolate', function($interpolate) {
var nullSelectCtrl = {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function (scope, element, attr) {
var selectCtrlName = '$selectController',
parent = element.parent(),
selectCtrl = parent.data(selectCtrlName) ||
parent.parent().data(selectCtrlName); // in case we are in optgroup
if (selectCtrl && selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden this messes up the repeater.
// We don't want the view to drive the initialization of the model anyway.
element.prop('selected', false);
} else {
selectCtrl = nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
attr.$set('value', newVal);
if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
selectCtrl.addOption(newVal);
});
} else {
selectCtrl.addOption(attr.value);
}
element.on('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
}
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: true
});
//try to bind to jquery now so that one can write angular.element().read()
//but we will rebind on bootstrap again.
bindJQuery();
publishExternalAPI(angular);
jqLite(document).ready(function() {
angularInit(document, bootstrap);
});
})(window, document);
angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}</style>'); |
/**
* Created by stefabal on 02.08.15.
*/
/* Services */
/*
http://docs.angularjs.org/api/ngResource.$resource
Default ngResources are defined as
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
*/
var restServices = angular.module('myApp.services', ['ngResource']);
restServices.factory('UserService', function($resource){
var data = $resource('http://localhost:3000/users/:user', {user: '@user'},{
query: {
method: 'GET',
params:{},
isArray: true
},
save: {
method: 'POST',
params:{},
isArray: false
}
});
return data;
});
restServices.factory('authFactory', ['$rootScope', '$http', function ($rootScope, $http) {
var authFactory = {
authData: undefined
};
authFactory.login = function (user) {
return $http.post('http://localhost/api/auth/', user);
};
return authFactory;
}]);
//http://movieapp-sitepointdemos.rhcloud.com/api/movies
|
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var marked = require('marked');
var moment = require('moment');
var cheerio = require('cheerio');
var sequelize = require('./sequelize.js');
var git = require('./git.js');
var utility = require('./../content/utility.js');
var basedir = path.join(git.repository, 'content/');
// ---------------
// Importing
// ---------------
function generateCleanID(title, date)
{
var id = date.format('MM-DD-YYYY');
id = id + '-' + title.toLowerCase();
id = id.replace(/[^a-zA-Z0-9\-]/g, '-');
return id;
}
function generatePreview(text)
{
var dom = cheerio.load(text);
var paragraph = dom('p').first();
return paragraph.html();
}
function importPost(post, postsLeft)
{
if(typeof post.title === 'undefined')
{
console.error('Post doesn\'t have a title!');
importPosts(postsLeft);
return;
}
if(typeof post.date === 'undefined')
{
console.error('Post doesn\'t have a date!');
importPosts(postsLeft);
return;
}
var date;
var text;
var file = path.join(basedir, 'articles/' + post.file);
var title = post.title;
var tags = (typeof post.tags !== 'undefined') ? post.tags : [];
var chainer = new Sequelize.Utils.QueryChainer();
try
{
date = moment(post.date, 'DD.MM.YYYY HH:mm:ss Z');
text = marked(fs.readFileSync(file, 'utf-8'));
}
catch(e)
{
console.error('Failed to parse date/file: ' + e);
importPosts(postsLeft);
return;
}
var postID = generateCleanID(title, date);
var preview = generatePreview(text);
for(var i=0; i<tags.length; i++)
{
var tag = tags[i].toLowerCase();
(function(tag) {
chainer.add(sequelize.Tag.findOrCreate({ title: tag }));
})(tag);
}
chainer.run().success(function(results) {
sequelize.Post.findOrCreate({ puuid: postID }).success(function(entry) {
entry.updateAttributes({
title: title,
date: date.toDate(),
text: text,
preview: preview
});
entry.setTags(results);
importPosts(postsLeft);
}).error(function(error) {
console.error(error);
importPosts(postsLeft);
});
}).error(function(error) {
console.error(error);
importPosts(postsLeft);
});
}
function importPosts(posts)
{
if(posts.length == 0)
return;
var post = posts.pop();
importPost(post, posts);
}
function cleanTag(tag)
{
try
{
return { title: utility.capitalize(tag.values.title), url: '/blog/tag/' + tag.values.title };
}
catch(e)
{
return { title: e, url: '#' };
}
}
function cleanTags(tags)
{
var cleaned = new Array();
for(var j = 0; j < tags.length; j ++)
{
var tag = tags[j];
cleaned.push(cleanTag(tag));
}
cleaned.sort(function(a, b) {
if(a.title < b.title)
return -1;
if(a.title > b.title)
return 1;
return 0;
});
return cleaned;
}
function processPosts(posts, preview, callback)
{
var cleanPosts = new Array();
var chainer = new Sequelize.Utils.QueryChainer();
for(var i = 0; i < posts.length; i ++)
{
var post = posts[i];
var date = moment(post.values.date).fromNow();
var html = preview ? post.values.preview : post.values.text;
var cleanPost = { title: post.values.title, html: html, date: date, url: '/blog/' + post.values.puuid };
cleanPosts.push(cleanPost);
chainer.add(post.getTags());
}
chainer.run().success(function(result) {
for(var i = 0; i < cleanPosts.length; i ++)
{
var post = cleanPosts[i];
var tags = result[i];
post.tags = cleanTags(tags);
}
callback(cleanPosts);
});
}
function importData()
{
console.log('Importing data');
var articlesPath = path.join(basedir, 'articles/!content.json');
var articles = JSON.parse(fs.readFileSync(articlesPath, 'utf-8'));
importPosts(articles);
}
function importCommits(commits, callback)
{
var chainer = new Sequelize.Utils.QueryChainer();
for(var i = 0; i < commits.length; i ++)
{
var commit = commits[i];
chainer.add(sequelize.Commit.create({ hash: commit }));
}
chainer.runSerially().success(function() {
if(typeof callback !== 'undefined')
callback();
});
}
function cleanImport(callback)
{
var chainer = new Sequelize.Utils.QueryChainer;
chainer.add(sequelize.sequelize.drop());
chainer.add(sequelize.sequelize.sync());
chainer.runSerially().success(function() {
importData();
git.commits(undefined, function(commits) {
importCommits(commits, callback);
});
});
}
function importFromRepository(callback)
{
console.log('Importing blog data');
sequelize.Commit.find({ order: 'ROWID DESC' }).success(function(commit) {
if(commit == null)
{
cleanImport(callback);
return;
}
git.commits(commit.values.hash, function(commits) {
if(commits.length > 0)
{
importData();
importCommits(commits, callback);
}
else if(typeof callback !== 'undefined')
{
callback();
}
});
});
}
// ---------------
// Fetching
// ---------------
function getPage(page, callback)
{
console.log('Getting page "' + page + '"');
var limit = 8;
var start = page * limit;
sequelize.Post.findAndCountAll({ order: 'date DESC', offset: start, limit: limit }).success(function(result) {
var count = result.count;
var posts = result.rows;
if(posts.length == 0)
{
var data = {};
data.infos = new Array(utility.generateError('Oh dear!', 'It appears like this page doesn\'t exist!'));
callback(data);
return;
}
var pages = Math.ceil(count / limit);
processPosts(posts, true, function(cleanPosts) {
var data = {};
data.posts = cleanPosts;
data.page = page;
data.pages = pages;
callback(data);
});
});
}
function getPost(post, callback)
{
console.log('Getting post "' + post + '"');
var data = {};
sequelize.Post.find({ where: { puuid: post }}).success(function(post) {
if(post == null)
{
data.infos = new Array(utility.generateError('Oh dear!', 'Couldn\'t find the post you were looking for!'));
callback(data);
return;
}
processPosts([post], false, function(cleanPosts) {
var data = { post: cleanPosts[0] };
callback(data);
})
});
}
function getTag(name, callback)
{
console.log('Getting tag "' + name + '"');
sequelize.Tag.find({ where: {title: name.toLowerCase() }}).success(function(tag) {
if(tag == null)
{
var data = {};
data.infos = new Array(utility.generateError('Oh dear!', 'There is not a single post with that tag!'));
callback(data);
return;
}
tag.getPosts({ order: 'date DESC' }).success(function(posts) {
var data = {};
if(posts == null || posts.length == 0)
{
data.infos = new Array(utility.generateError('Oh dear!', 'There is not a single post with that tag!'));
callback(data);
return;
}
processPosts(posts, true, function(cleanPosts) {
data.posts = cleanPosts;
callback(data);
});
});
});
}
module.exports = {
import: importFromRepository,
getPage: getPage,
getPost: getPost,
getTag: getTag
}
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var _getUserAssets = require('./modules/getUserAssets.js');
var _exerciseData = require('./modules/exerciseData.js');
var _sort = require('./modules/sort.js');
var _helperFunctions = require('./modules/helperFunctions.js');
var thisPath = window.location.pathname;
if ((0, _helperFunctions.isProfilePage)(thisPath)) {
// populate with initial user data
(0, _getUserAssets.getUserAssets)('https://makegains.herokuapp.com/user/exercises', null).then(function (data) {
(0, _getUserAssets.displayResponse)(data.data, data.type);
});
(0, _getUserAssets.getUserAssets)('https://makegains.herokuapp.com/user/programs', null).then(function (data) {
(0, _getUserAssets.displayResponse)(data.data, data.type);
});
(0, _getUserAssets.getUserAssets)('https://makegains.herokuapp.com/user/workouts', null).then(function (data) {
(0, _getUserAssets.displayResponse)(data.data, data.type);
});
// set event listeners to sort categories
(0, _sort.setSortingListeners)('exercise');
}
if ((0, _helperFunctions.isExerciseDetailPage)(thisPath)) {
// display a chart with exercise data over time
(0, _exerciseData.displayExerciseHistory)();
}
if ((0, _helperFunctions.isWorkoutLogPage)(thisPath)) {
// set event listeners for sorting
(0, _sort.setExerciseSelectListeners)();
}
},{"./modules/exerciseData.js":2,"./modules/getUserAssets.js":3,"./modules/helperFunctions.js":4,"./modules/sort.js":6}],2:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.displayExerciseHistory = undefined;
var _httpRequest = require('./httpRequest.js');
function displayExerciseHistory() {
// set placeholders
var data = void 0;
// create url for http request
var pageUrl = window.location.href;
var tempArray = pageUrl.split('/');
var exerciseId = tempArray.pop();
tempArray.push('api', exerciseId);
var apiUrl = tempArray.join('/');
// GET the data for this particular exercise
(0, _httpRequest.get)(apiUrl).then(function (response) {
data = JSON.parse(response);
displayTrend(data);
}, function (error) {
data = 'An error has occured!';
});
}
// Functions which can be called to display the data in a specific way
// Each function will format data and then pass it to a method to display it
/* Parses every oneRepMax entry for a single exercise
and pulls out the highest one for each exercise session */
function displayTrend(data) {
var programs = data.exerciseHistory;
var oneRepMaxArray = programs.map(function (programSession) {
return programSession.dataHistory.map(function (datePerformance) {
return datePerformance.oneRepMax;
}).sort().pop();
});
var dateArray = programs.map(function (programSession) {
var dateify = new Date(programSession.date);
var formattedDate = dateify.toLocaleDateString();
return formattedDate;
});
var datasetLabel = data.name;
var dataPointLabels = dateArray;
createLineChart(datasetLabel, dataPointLabels, oneRepMaxArray);
}
// creates a Chart with provided data
function createLineChart(theExercise, dateCompletedArray, strengthIndexArray) {
// define context and create chart
var c = document.getElementById('results');
var context = c.getContext('2d');
var results = new Chart(context, {
type: 'line',
data: {
labels: dateCompletedArray,
datasets: [{
label: theExercise,
fill: false,
lineTension: 0,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'round',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 6,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
data: strengthIndexArray,
spanGaps: true
}]
},
options: {
legend: {
display: false
}
}
});
}
exports.displayExerciseHistory = displayExerciseHistory;
},{"./httpRequest.js":5}],3:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.displayResponse = exports.getUserAssets = undefined;
var _httpRequest = require('./httpRequest.js');
// makes an ajax request for a user's exercises, programs, or workouts
// then displays it on the DOM in the appropriate location
function getUserAssets(url, delimeter) {
return new Promise(function (resolve, reject) {
var path = void 0;
if (delimeter !== null) {
path = url + '/' + delimeter;
} else {
path = url;
}
// define type of request
var tempArray = url.split('/');
var reqType = tempArray.pop();
// flow of logic
(0, _httpRequest.get)(path).then(function (response) {
var data = JSON.parse(response);
handleSpecificResponseType(data, reqType).then(function (identifiedData) {
resolve(identifiedData);
}, function (err) {
console.log('Error in function "handleSpecficResponseType()"');
});
}, function (err) {
console.log('Error retrieving data in "getUserAssets()"');
});
});
}
// determines whether the response was an exercise or a program or a workout
// then assigns a type to it for further processing
function handleSpecificResponseType(json, reqType) {
return new Promise(function (resolve, reject) {
// check if data exists by sampling json data
var sample = json[0];
// initialize empty response object
var response = {};
// call function to display data based on type
switch (reqType) {
case 'exercises':
response.type = 'exercises';
break;
case 'workouts':
response.type = 'workouts';
break;
case 'programs':
response.type = 'programs';
break;
}
// determined whether data is existant
if (sample === undefined) {
response.data = undefined;
} else {
response.data = json;
}
resolve(response);
});
}
// writes the reponse to the DOM based on what type of data is received
function displayResponse(response, typeOfData) {
// Hide the loading animation
var loadingFields = document.getElementsByClassName('loading');
for (var i = 0; i < loadingFields.length; i++) {
loadingFields[i].classList.add('hidden');
}
// initialize HTML which is a part of every DOM addition
var appendTo = void 0;
var ul = document.createElement('ul');
ul.classList.add('list-group', 'buffer-top');
// create HTML for every json object, concatenate
if (typeOfData == 'exercises' && response !== undefined) {
appendTo = document.getElementById('exercises');
ul.id = 'exercise-list';
ul.innerHTML = displayExercise(response);
} else if (typeOfData == 'workouts' && response !== undefined) {
appendTo = document.getElementById('workouts');
ul.id = 'workout-list';
ul.innerHTML = displayWorkout(response);
} else if (typeOfData == 'programs' && response !== undefined) {
appendTo = document.getElementById('programs');
ul.id = 'program-list';
ul.innerHTML = displayProgram(response);
// displays the HTML for when no data is present
} else if (typeOfData == 'exercises' && response === undefined) {
appendTo = document.getElementById('exercises');
ul.id = 'exercise-list';
ul.innerHTML = displayNodataExercise();
} else if (typeOfData == 'workouts' && response === undefined) {
appendTo = document.getElementById('workouts');
ul.id = 'workout-list';
ul.innerHTML = displayNodataWorkout();
} else if (typeOfData == 'programs' && response === undefined) {
appendTo = document.getElementById('programs');
ul.id = 'program-list';
ul.innerHTML = displayNodataProgram();
// Something bad happened
} else {
alert(":(");
}
// Apply result to the DOM
appendTo.appendChild(ul);
}
// functions to perform display operations based on datatype
function displayExercise(response) {
return response.map(function (exercise) {
return '<li class="list-group-item">\n <a href="/exercise/detail/' + exercise._id + '">' + exercise.name + '</a>\n <form method="post" action="/exercise/delete/' + exercise._id + '">\n <button class="btn btn-danger" type="submit">Delete</button>\n </form>\n <form method="get" action="/exercise/edit/' + exercise._id + '">\n <button class="btn btn-warning right-buffer" type="submit">Edit</button>\n </form>\n </li>';
}).join('');
}
function displayWorkout(response) {
return response.map(function (workout) {
var localDate = new Date(workout.date).toLocaleString();
return '<li class="list-group-item">\n <a href="/workout/detail/' + workout._id + '">' + localDate + '</a>\n <form method="post" action="/workout/delete/' + workout._id + '">\n <button class="btn btn-danger" type="submit">Delete</button>\n </form>\n </li>';
}).join('');
}
function displayProgram(response) {
return response.map(function (program) {
return '<li class="list-group-item">\n <a href="/program/detail/' + program._id + '">' + program.name + '</a>\n <!--\n <form method="get" action="/program/edit/' + program._id + '">\n <button class="btn btn-warning" type="submit">Edit</button>\n </form>\n <form method="post" action="/program/delete/' + program._id + '">\n <button class="btn btn-danger" type="submit">Delete</button>\n </form>\n -->\n </li>';
}).join('');
}
function displayNodataExercise() {
return '<li class="list-group-item text-center">\n Add exercises to your account so you can add them to programs, log them in your workouts, and track your progress!\n </li>';
}
function displayNodataWorkout() {
return '<li class="list-group-item text-center">\n You don\'t have any workouts logged yet! Add exercises so you can include them in logged workouts. Workouts can be free-form or follow a pre-defined program. Track your workouts so can start recording progress!\n </li>';
}
function displayNodataProgram() {
return '<li class="list-group-item text-center">\n Have a few workouts that are "set-in-stone"? Input a your workout program so you can use it as a template while logging sets!\n </li>';
}
exports.getUserAssets = getUserAssets;
exports.displayResponse = displayResponse;
},{"./httpRequest.js":5}],4:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
// checks if the URL is the user's profile page
// 'thisPath' = the requested url path following the protocol and hostname
function isProfilePage(thisPath) {
var userProfileLocation = '/user';
var bool = undefined;
thisPath === userProfileLocation ? bool = true : bool = false;
return bool;
}
// checks if the URL is the the page to display an exercise's history
// 'thisPath' = the requested url path following the protocol and hostname
function isExerciseDetailPage(thisPath) {
var exerciseDetailLocation = '/exercise/detail';
var bool = undefined;
// remove the exerciseID from the path requested
var pathArray = thisPath.split('/');
pathArray.pop();
var path = pathArray.join('/');
path === exerciseDetailLocation ? bool = true : bool = false;
return bool;
}
// checks if the URL is the the page to log a workout
// 'thisPath' = the requested url path following the protocol and hostname
function isWorkoutLogPage(thisPath) {
var workoutLogLocation = '/workout/log';
var bool = undefined;
thisPath === workoutLogLocation ? bool = true : bool = false;
return bool;
}
exports.isProfilePage = isProfilePage;
exports.isExerciseDetailPage = isExerciseDetailPage;
exports.isWorkoutLogPage = isWorkoutLogPage;
},{}],5:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// define function to make an http request using a promise
function get(url) {
// contain XMLHttpRequest within a promise
return new Promise(function (resolve, reject) {
// data for the request
var request = new XMLHttpRequest();
request.open('GET', url);
// promise is fulfilled with either the data or an error
request.onload = function () {
if (request.status == 200 && request.readyState == 4) {
resolve(request.response);
} else {
reject(Error(request.statusText));
}
};
// error handling for request
request.onerror = function () {
reject(Error("Unable to get data"));
};
// send the request
request.send();
});
}
exports.get = get;
},{}],6:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setExerciseSelectListeners = exports.setSortingListeners = undefined;
var _getUserAssets = require('./getUserAssets.js');
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function setSortingListeners(category) {
var sortingButtons = document.getElementsByClassName(category + '-category');
var APIurl = 'https://makegains.herokuapp.com/user/' + category + 's';
var categoryFieldId = category + '-list';
var currentDisplay = document.getElementById('exercise-category-type');
Array.prototype.filter.call(sortingButtons, function (sortingButton) {
sortingButton.addEventListener('click', function () {
var sortBy = sortingButton.innerHTML;
currentDisplay.innerHTML = sortBy;
if (sortBy === 'All') {
(0, _getUserAssets.getUserAssets)(APIurl, null).then(function (data) {
clearField(categoryFieldId, function () {
(0, _getUserAssets.displayResponse)(data.data, data.type);
});
});
} else {
(0, _getUserAssets.getUserAssets)(APIurl, sortBy).then(function (data) {
clearField(categoryFieldId, function () {
(0, _getUserAssets.displayResponse)(data.data, data.type);
});
});
}
});
});
}
function clearField(idOfField, cb) {
var field = document.getElementById(idOfField);
field.remove();
cb();
}
function setExerciseSelectListeners() {
var sortingButtons = document.getElementsByClassName('exercise-category');
var exerciseSelections = document.getElementsByTagName('option');
var selectionArray = [].concat(_toConsumableArray(exerciseSelections));
var currentDisplay = document.getElementById('exercise-category-type');
Array.prototype.filter.call(sortingButtons, function (sortingButton) {
sortingButton.addEventListener('click', function () {
var sortBy = sortingButton.innerHTML;
currentDisplay.innerHTML = sortBy;
selectionArray.forEach(function (selection) {
if (sortBy === 'All') {
selection.classList.remove('hidden');
} else if (selection.dataset.category === sortBy) {
selection.classList.remove('hidden');
} else {
selection.classList.add('hidden');
}
});
});
});
}
exports.setSortingListeners = setSortingListeners;
exports.setExerciseSelectListeners = setExerciseSelectListeners;
},{"./getUserAssets.js":3}]},{},[1]);
|
/*!
* Native JavaScript for Bootstrap - Modal v4.1.0alpha5 (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2022 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
/**
* A global namespace for `Escape` key.
* @type {string} e.which = 27 equivalent
*/
const keyEscape = 'Escape';
/**
* A global namespace for aria-hidden.
* @type {string}
*/
const ariaHidden = 'aria-hidden';
/**
* A global namespace for aria-modal.
* @type {string}
*/
const ariaModal = 'aria-modal';
/**
* A global namespace for `resize` event.
* @type {string}
*/
const resizeEvent = 'resize';
/**
* A global namespace for `click` event.
* @type {string}
*/
const mouseclickEvent = 'click';
/**
* A global namespace for `keydown` event.
* @type {string}
*/
const keydownEvent = 'keydown';
/**
* Shortcut for `HTMLElement.setAttribute()` method.
* @param {HTMLElement | Element} element target element
* @param {string} attribute attribute name
* @param {string} value attribute value
*/
const setAttribute = (element, attribute, value) => element.setAttribute(attribute, value);
/**
* Shortcut for `HTMLElement.removeAttribute()` method.
* @param {HTMLElement | Element} element target element
* @param {string} attribute attribute name
*/
const removeAttribute = (element, attribute) => element.removeAttribute(attribute);
/**
* A global namespace for 'transitionDuration' string.
* @type {string}
*/
const transitionDuration = 'transitionDuration';
/**
* A global namespace for:
* * `transitionProperty` string for Firefox,
* * `transition` property for all other browsers.
*
* @type {string}
*/
const transitionProperty = 'transitionProperty';
/**
* Shortcut for `window.getComputedStyle(element).propertyName`
* static method.
*
* * If `element` parameter is not an `HTMLElement`, `getComputedStyle`
* throws a `ReferenceError`.
*
* @param {HTMLElement | Element} element target
* @param {string} property the css property
* @return {string} the css property value
*/
function getElementStyle(element, property) {
const computedStyle = getComputedStyle(element);
// @ts-ignore -- must use camelcase strings,
// or non-camelcase strings with `getPropertyValue`
return property in computedStyle ? computedStyle[property] : '';
}
/**
* Utility to get the computed `transitionDuration`
* from Element in miliseconds.
*
* @param {HTMLElement | Element} element target
* @return {number} the value in miliseconds
*/
function getElementTransitionDuration(element) {
const propertyValue = getElementStyle(element, transitionProperty);
const durationValue = getElementStyle(element, transitionDuration);
const durationScale = durationValue.includes('ms') ? 1 : 1000;
const duration = propertyValue && propertyValue !== 'none'
? parseFloat(durationValue) * durationScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
/**
* Returns the `Window` object of a target node.
* @see https://github.com/floating-ui/floating-ui
*
* @param {(Node | HTMLElement | Element | Window)=} node target node
* @returns {globalThis}
*/
function getWindow(node) {
if (node == null) {
return window;
}
if (!(node instanceof Window)) {
const { ownerDocument } = node;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
// @ts-ignore
return node;
}
/**
* Returns the `document` or the `#document` element.
* @see https://github.com/floating-ui/floating-ui
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {Document}
*/
function getDocument(node) {
if (node instanceof HTMLElement) return node.ownerDocument;
if (node instanceof Window) return node.document;
return window.document;
}
/**
* Returns the `document.body` or the `<body>` element.
*
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {HTMLElement | HTMLBodyElement}
*/
function getDocumentBody(node) {
return getDocument(node).body;
}
/**
* Returns the `document.documentElement` or the `<html>` element.
*
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {HTMLElement | HTMLHtmlElement}
*/
function getDocumentElement(node) {
return getDocument(node).documentElement;
}
/**
* A global array of possible `ParentNode`.
*/
const parentNodes = [Document, Element, HTMLElement];
/**
* A global array with `Element` | `HTMLElement`.
*/
const elementNodes = [Element, HTMLElement];
/**
* Utility to check if target is typeof `HTMLElement`, `Element`, `Node`
* or find one that matches a selector.
*
* @param {HTMLElement | Element | string} selector the input selector or target element
* @param {(HTMLElement | Element | Document)=} parent optional node to look into
* @return {(HTMLElement | Element)?} the `HTMLElement` or `querySelector` result
*/
function querySelector(selector, parent) {
const lookUp = parentNodes.some((x) => parent instanceof x)
? parent : getDocument();
// @ts-ignore
return elementNodes.some((x) => selector instanceof x)
// @ts-ignore
? selector : lookUp.querySelector(selector);
}
/**
* A shortcut for `(document|Element).querySelectorAll`.
*
* @param {string} selector the input selector
* @param {(HTMLElement | Element | Document | Node)=} parent optional node to look into
* @return {NodeListOf<HTMLElement | Element>} the query result
*/
function querySelectorAll(selector, parent) {
const lookUp = parent && parentNodes
.some((x) => parent instanceof x) ? parent : getDocument();
// @ts-ignore -- `ShadowRoot` is also a node
return lookUp.querySelectorAll(selector);
}
/**
* Shortcut for `HTMLElement.closest` method which also works
* with children of `ShadowRoot`. The order of the parameters
* is intentional since they're both required.
*
* @see https://stackoverflow.com/q/54520554/803358
*
* @param {HTMLElement | Element} element Element to look into
* @param {string} selector the selector name
* @return {(HTMLElement | Element)?} the query result
*/
function closest(element, selector) {
return element ? (element.closest(selector)
// @ts-ignore -- break out of `ShadowRoot`
|| closest(element.getRootNode().host, selector)) : null;
}
/**
* Add class to `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to add
*/
function addClass(element, classNAME) {
element.classList.add(classNAME);
}
/**
* Check class in `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to check
* @return {boolean}
*/
function hasClass(element, classNAME) {
return element.classList.contains(classNAME);
}
/**
* Remove class from `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to remove
*/
function removeClass(element, classNAME) {
element.classList.remove(classNAME);
}
/**
* Checks if a page is Right To Left.
* @param {(HTMLElement | Element)=} node the target
* @returns {boolean} the query result
*/
const isRTL = (node) => getDocumentElement(node).dir === 'rtl';
/** @type {Map<string, Map<HTMLElement | Element, Record<string, any>>>} */
const componentData = new Map();
/**
* An interface for web components background data.
* @see https://github.com/thednp/bootstrap.native/blob/master/src/components/base-component.js
*/
const Data = {
/**
* Sets web components data.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
* @param {Record<string, any>} instance the component instance
*/
set: (target, component, instance) => {
const element = querySelector(target);
if (!element) return;
if (!componentData.has(component)) {
componentData.set(component, new Map());
}
const instanceMap = componentData.get(component);
// @ts-ignore - not undefined, but defined right above
instanceMap.set(element, instance);
},
/**
* Returns all instances for specified component.
* @param {string} component the component's name or a unique key
* @returns {Map<HTMLElement | Element, Record<string, any>>?} all the component instances
*/
getAllFor: (component) => {
const instanceMap = componentData.get(component);
return instanceMap || null;
},
/**
* Returns the instance associated with the target.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
* @returns {Record<string, any>?} the instance
*/
get: (target, component) => {
const element = querySelector(target);
const allForC = Data.getAllFor(component);
const instance = element && allForC && allForC.get(element);
return instance || null;
},
/**
* Removes web components data.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
*/
remove: (target, component) => {
const element = querySelector(target);
const instanceMap = componentData.get(component);
if (!instanceMap || !element) return;
instanceMap.delete(element);
if (instanceMap.size === 0) {
componentData.delete(component);
}
},
};
/**
* An alias for `Data.get()`.
* @type {SHORTER.getInstance<any>}
*/
const getInstance = (target, component) => Data.get(target, component);
/** @type {Map<HTMLElement | Element, any>} */
const TimeCache = new Map();
/**
* An interface for one or more `TimerHandler`s per `Element`.
* @see https://github.com/thednp/navbar.js/
*/
const Timer = {
/**
* Sets a new timeout timer for an element, or element -> key association.
* @param {HTMLElement | Element | string} target target element
* @param {ReturnType<TimerHandler>} callback the callback
* @param {number} delay the execution delay
* @param {string=} key a unique
*/
set: (target, callback, delay, key) => {
const element = querySelector(target);
if (!element) return;
if (key && key.length) {
if (!TimeCache.has(element)) {
TimeCache.set(element, new Map());
}
const keyTimers = TimeCache.get(element);
keyTimers.set(key, setTimeout(callback, delay));
} else {
TimeCache.set(element, setTimeout(callback, delay));
}
},
/**
* Returns the timer associated with the target.
* @param {HTMLElement | Element | string} target target element
* @param {string=} key a unique
* @returns {number?} the timer
*/
get: (target, key) => {
const element = querySelector(target);
if (!element) return null;
const keyTimers = TimeCache.get(element);
if (key && key.length && keyTimers && keyTimers.get) {
return keyTimers.get(key) || null;
}
return keyTimers || null;
},
/**
* Clears the element's timer.
* @param {HTMLElement | Element | string} target target element
* @param {string=} key a unique key
*/
clear: (target, key) => {
const element = querySelector(target);
if (!element) return;
if (key && key.length) {
const keyTimers = TimeCache.get(element);
if (keyTimers && keyTimers.get) {
clearTimeout(keyTimers.get(key));
keyTimers.delete(key);
if (keyTimers.size === 0) {
TimeCache.delete(element);
}
}
} else {
clearTimeout(TimeCache.get(element));
TimeCache.delete(element);
}
},
};
/**
* Utility to focus an `HTMLElement` target.
*
* @param {HTMLElement | Element} element is the target
*/
// @ts-ignore -- `Element`s resulted from querySelector can focus too
const focus = (element) => element.focus();
/**
* Shortcut for `Object.assign()` static method.
* @param {Record<string, any>} obj a target object
* @param {Record<string, any>} source a source object
*/
const ObjectAssign = (obj, source) => Object.assign(obj, source);
/**
* Shortcut for the `Element.dispatchEvent(Event)` method.
*
* @param {HTMLElement | Element} element is the target
* @param {Event} event is the `Event` object
*/
const dispatchEvent = (element, event) => element.dispatchEvent(event);
/**
* A global namespace for most scroll event listeners.
* @type {Partial<AddEventListenerOptions>}
*/
const passiveHandler = { passive: true };
/**
* A global namespace for 'transitionend' string.
* @type {string}
*/
const transitionEndEvent = 'transitionend';
/**
* A global namespace for 'transitionDelay' string.
* @type {string}
*/
const transitionDelay = 'transitionDelay';
/**
* Utility to get the computed `transitionDelay`
* from Element in miliseconds.
*
* @param {HTMLElement | Element} element target
* @return {number} the value in miliseconds
*/
function getElementTransitionDelay(element) {
const propertyValue = getElementStyle(element, transitionProperty);
const delayValue = getElementStyle(element, transitionDelay);
const delayScale = delayValue.includes('ms') ? 1 : 1000;
const duration = propertyValue && propertyValue !== 'none'
? parseFloat(delayValue) * delayScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
/**
* Utility to make sure callbacks are consistently
* called when transition ends.
*
* @param {HTMLElement | Element} element target
* @param {EventListener} handler `transitionend` callback
*/
function emulateTransitionEnd(element, handler) {
let called = 0;
const endEvent = new Event(transitionEndEvent);
const duration = getElementTransitionDuration(element);
const delay = getElementTransitionDelay(element);
if (duration) {
/**
* Wrap the handler in on -> off callback
* @type {EventListenerObject['handleEvent']} e Event object
*/
const transitionEndWrapper = (e) => {
if (e.target === element) {
handler.apply(element, [e]);
element.removeEventListener(transitionEndEvent, transitionEndWrapper);
called = 1;
}
};
element.addEventListener(transitionEndEvent, transitionEndWrapper);
setTimeout(() => {
if (!called) element.dispatchEvent(endEvent);
}, duration + delay + 17);
} else {
handler.apply(element, [endEvent]);
}
}
/**
* Returns a namespaced `CustomEvent` specific to each component.
* @param {string} EventType Event.type
* @param {Record<string, any>=} config Event.options | Event.properties
* @returns {SHORTER.OriginalEvent} a new namespaced event
*/
function OriginalEvent(EventType, config) {
const OriginalCustomEvent = new CustomEvent(EventType, {
cancelable: true, bubbles: true,
});
if (config instanceof Object) {
ObjectAssign(OriginalCustomEvent, config);
}
return OriginalCustomEvent;
}
/** @type {Record<string, any>} */
const EventRegistry = {};
/**
* The global event listener.
*
* @this {Element | HTMLElement | Window | Document}
* @param {Event} e
* @returns {void}
*/
function globalListener(e) {
const that = this;
const { type } = e;
const oneEvMap = EventRegistry[type] ? [...EventRegistry[type]] : [];
oneEvMap.forEach((elementsMap) => {
const [element, listenersMap] = elementsMap;
[...listenersMap].forEach((listenerMap) => {
if (element === that) {
const [listener, options] = listenerMap;
listener.apply(element, [e]);
if (options && options.once) {
removeListener(element, type, listener, options);
}
}
});
});
}
/**
* Register a new listener with its options and attach the `globalListener`
* to the target if this is the first listener.
*
* @param {Element | HTMLElement | Window | Document} element
* @param {string} eventType
* @param {EventListenerObject['handleEvent']} listener
* @param {AddEventListenerOptions=} options
*/
const addListener = (element, eventType, listener, options) => {
// get element listeners first
if (!EventRegistry[eventType]) {
EventRegistry[eventType] = new Map();
}
const oneEventMap = EventRegistry[eventType];
if (!oneEventMap.has(element)) {
oneEventMap.set(element, new Map());
}
const oneElementMap = oneEventMap.get(element);
// get listeners size
const { size } = oneElementMap;
// register listener with its options
if (oneElementMap) {
oneElementMap.set(listener, options);
}
// add listener last
if (!size) {
element.addEventListener(eventType, globalListener, options);
}
};
/**
* Remove a listener from registry and detach the `globalListener`
* if no listeners are found in the registry.
*
* @param {Element | HTMLElement | Window | Document} element
* @param {string} eventType
* @param {EventListenerObject['handleEvent']} listener
* @param {AddEventListenerOptions=} options
*/
const removeListener = (element, eventType, listener, options) => {
// get listener first
const oneEventMap = EventRegistry[eventType];
const oneElementMap = oneEventMap && oneEventMap.get(element);
const savedOptions = oneElementMap && oneElementMap.get(listener);
// also recover initial options
const { options: eventOptions } = savedOptions !== undefined
? savedOptions
: { options };
// unsubscribe second, remove from registry
if (oneElementMap && oneElementMap.has(listener)) oneElementMap.delete(listener);
if (oneEventMap && (!oneElementMap || !oneElementMap.size)) oneEventMap.delete(element);
if (!oneEventMap || !oneEventMap.size) delete EventRegistry[eventType];
// remove listener last
if (!oneElementMap || !oneElementMap.size) {
element.removeEventListener(eventType, globalListener, eventOptions);
}
};
/**
* Global namespace for most components `toggle` option.
*/
const dataBsToggle = 'data-bs-toggle';
/**
* Global namespace for most components `dismiss` option.
*/
const dataBsDismiss = 'data-bs-dismiss';
/**
* Global namespace for most components `fade` class.
*/
const fadeClass = 'fade';
/**
* Global namespace for most components `show` class.
*/
const showClass = 'show';
/** @type {string} */
const modalString = 'modal';
/** @type {string} */
const modalComponent = 'Modal';
/**
* Check if target is a `ShadowRoot`.
*
* @param {any} element target
* @returns {boolean} the query result
*/
const isShadowRoot = (element) => {
const OwnElement = getWindow(element).ShadowRoot;
return element instanceof OwnElement || element instanceof ShadowRoot;
};
/**
* Returns the `parentNode` also going through `ShadowRoot`.
* @see https://github.com/floating-ui/floating-ui
*
* @param {Node | HTMLElement | Element} node the target node
* @returns {Node | HTMLElement | Element} the apropriate parent node
*/
function getParentNode(node) {
if (node.nodeName === 'HTML') {
return node;
}
// this is a quicker (but less type safe) way to save quite some bytes from the bundle
return (
// @ts-ignore
node.assignedSlot // step into the shadow DOM of the parent of a slotted node
|| node.parentNode // @ts-ignore DOM Element detected
|| (isShadowRoot(node) ? node.host : null) // ShadowRoot detected
|| getDocumentElement(node) // fallback
);
}
/**
* Check if a target element is a `<table>`, `<td>` or `<th>`.
* @param {any} element the target element
* @returns {boolean} the query result
*/
const isTableElement = (element) => ['TABLE', 'TD', 'TH'].includes(element.tagName);
/**
* Checks if an element is an `HTMLElement`.
*
* @param {any} element the target object
* @returns {boolean} the query result
*/
const isHTMLElement = (element) => element instanceof HTMLElement;
/**
* Returns an `HTMLElement` to be used as default value for *options.container*
* for `Tooltip` / `Popover` components.
*
* When `getOffset` is *true*, it returns the `offsetParent` for tooltip/popover
* offsets computation similar to **floating-ui**.
* @see https://github.com/floating-ui/floating-ui
*
* @param {HTMLElement | Element} element the target
* @param {boolean=} getOffset when *true* it will return an `offsetParent`
* @returns {HTMLElement | HTMLBodyElement | Window | globalThis} the query result
*/
function getElementContainer(element, getOffset) {
const majorBlockTags = ['HTML', 'BODY'];
if (getOffset) {
/** @type {any} */
let { offsetParent } = element;
const win = getWindow(element);
// const { innerWidth } = getDocumentElement(element);
while (offsetParent && (isTableElement(offsetParent)
|| (isHTMLElement(offsetParent)
// we must count for both fixed & sticky
&& !['sticky', 'fixed'].includes(getElementStyle(offsetParent, 'position'))))) {
offsetParent = offsetParent.offsetParent;
}
if (!offsetParent || (offsetParent
&& (majorBlockTags.includes(offsetParent.tagName)
|| getElementStyle(offsetParent, 'position') === 'static'))) {
offsetParent = win;
}
return offsetParent;
}
/** @type {(HTMLElement)[]} */
const containers = [];
/** @type {any} */
let { parentNode } = element;
while (parentNode && !majorBlockTags.includes(parentNode.nodeName)) {
parentNode = getParentNode(parentNode);
if (!(isShadowRoot(parentNode) || !!parentNode.shadowRoot
|| isTableElement(parentNode))) {
containers.push(parentNode);
}
}
return containers.find((c, i) => {
if (getElementStyle(c, 'position') !== 'relative'
&& containers.slice(i + 1).every((r) => getElementStyle(r, 'position') === 'static')) {
return c;
}
return null;
}) || getDocumentBody(element);
}
/**
* Shortcut for `HTMLElement.getAttribute()` method.
* @param {HTMLElement | Element} element target element
* @param {string} attribute attribute name
*/
const getAttribute = (element, attribute) => element.getAttribute(attribute);
/**
* Global namespace for most components `target` option.
*/
const dataBsTarget = 'data-bs-target';
/**
* Global namespace for most components `parent` option.
*/
const dataBsParent = 'data-bs-parent';
/**
* Global namespace for most components `container` option.
*/
const dataBsContainer = 'data-bs-container';
/**
* Returns the `Element` that THIS one targets
* via `data-bs-target`, `href`, `data-bs-parent` or `data-bs-container`.
*
* @param {HTMLElement | Element} element the target element
* @returns {(HTMLElement | Element)?} the query result
*/
function getTargetElement(element) {
const targetAttr = [dataBsTarget, dataBsParent, dataBsContainer, 'href'];
const doc = getDocument(element);
return targetAttr.map((att) => {
const attValue = getAttribute(element, att);
if (attValue) {
return att === dataBsParent ? closest(element, attValue) : querySelector(attValue, doc);
}
return null;
}).filter((x) => x)[0];
}
/**
* Shortcut for `HTMLElement.getElementsByClassName` method. Some `Node` elements
* like `ShadowRoot` do not support `getElementsByClassName`.
*
* @param {string} selector the class name
* @param {(HTMLElement | Element | Document)=} parent optional Element to look into
* @return {HTMLCollectionOf<HTMLElement | Element>} the 'HTMLCollection'
*/
function getElementsByClassName(selector, parent) {
const lookUp = parent && parentNodes.some((x) => parent instanceof x)
? parent : getDocument();
return lookUp.getElementsByClassName(selector);
}
/**
* Shortcut for multiple uses of `HTMLElement.style.propertyName` method.
* @param {HTMLElement | Element} element target element
* @param {Partial<CSSStyleDeclaration>} styles attribute value
*/
// @ts-ignore
const setElementStyle = (element, styles) => { ObjectAssign(element.style, styles); };
/**
* Global namespace for components `fixed-top` class.
*/
const fixedTopClass = 'fixed-top';
/**
* Global namespace for components `fixed-bottom` class.
*/
const fixedBottomClass = 'fixed-bottom';
/**
* Global namespace for components `sticky-top` class.
*/
const stickyTopClass = 'sticky-top';
/**
* Global namespace for components `position-sticky` class.
*/
const positionStickyClass = 'position-sticky';
/** @param {(HTMLElement | Element | Document)=} parent */
const getFixedItems = (parent) => [
...getElementsByClassName(fixedTopClass, parent),
...getElementsByClassName(fixedBottomClass, parent),
...getElementsByClassName(stickyTopClass, parent),
...getElementsByClassName(positionStickyClass, parent),
...getElementsByClassName('is-fixed', parent),
];
/**
* Removes *padding* and *overflow* from the `<body>`
* and all spacing from fixed items.
* @param {(HTMLElement | Element)=} element the target modal/offcanvas
*/
function resetScrollbar(element) {
const bd = getDocumentBody(element);
setElementStyle(bd, {
paddingRight: '',
overflow: '',
});
const fixedItems = getFixedItems(bd);
if (fixedItems.length) {
fixedItems.forEach((fixed) => {
setElementStyle(fixed, {
paddingRight: '',
marginRight: '',
});
});
}
}
/**
* Returns the scrollbar width if the body does overflow
* the window.
* @param {(HTMLElement | Element)=} element
* @returns {number} the value
*/
function measureScrollbar(element) {
const { clientWidth } = getDocumentElement(element);
const { innerWidth } = getWindow(element);
return Math.abs(innerWidth - clientWidth);
}
/**
* Sets the `<body>` and fixed items style when modal / offcanvas
* is shown to the user.
*
* @param {HTMLElement | Element} element the target modal/offcanvas
* @param {boolean=} overflow body does overflow or not
*/
function setScrollbar(element, overflow) {
const bd = getDocumentBody(element);
const bodyPad = parseInt(getElementStyle(bd, 'paddingRight'), 10);
const isOpen = getElementStyle(bd, 'overflow') === 'hidden';
const sbWidth = isOpen && bodyPad ? 0 : measureScrollbar(element);
const fixedItems = getFixedItems(bd);
if (overflow) {
setElementStyle(bd, {
overflow: 'hidden',
paddingRight: `${bodyPad + sbWidth}px`,
});
if (fixedItems.length) {
fixedItems.forEach((fixed) => {
const itemPadValue = getElementStyle(fixed, 'paddingRight');
// @ts-ignore
fixed.style.paddingRight = `${parseInt(itemPadValue, 10) + sbWidth}px`;
if ([stickyTopClass, positionStickyClass].some((c) => hasClass(fixed, c))) {
const itemMValue = getElementStyle(fixed, 'marginRight');
// @ts-ignore
fixed.style.marginRight = `${parseInt(itemMValue, 10) - sbWidth}px`;
}
});
}
}
}
/**
* Utility to force re-paint of an `HTMLElement` target.
*
* @param {HTMLElement | Element} element is the target
* @return {number} the `Element.offsetHeight` value
*/
// @ts-ignore
const reflow = (element) => element.offsetHeight;
/** @type {string} */
const offcanvasString = 'offcanvas';
const backdropString = 'backdrop';
const modalBackdropClass = `${modalString}-${backdropString}`;
const offcanvasBackdropClass = `${offcanvasString}-${backdropString}`;
const modalActiveSelector = `.${modalString}.${showClass}`;
const offcanvasActiveSelector = `.${offcanvasString}.${showClass}`;
// any document would suffice
const overlay = getDocument().createElement('div');
/**
* Returns the current active modal / offcancas element.
* @param {(HTMLElement | Element)=} element the context element
* @returns {(HTMLElement | Element)?} the requested element
*/
function getCurrentOpen(element) {
return querySelector(`${modalActiveSelector},${offcanvasActiveSelector}`, getDocument(element));
}
/**
* Toogles from a Modal overlay to an Offcanvas, or vice-versa.
* @param {boolean=} isModal
*/
function toggleOverlayType(isModal) {
const targetClass = isModal ? modalBackdropClass : offcanvasBackdropClass;
[modalBackdropClass, offcanvasBackdropClass].forEach((c) => {
removeClass(overlay, c);
});
addClass(overlay, targetClass);
}
/**
* Append the overlay to DOM.
* @param {HTMLElement | Element} container
* @param {boolean} hasFade
* @param {boolean=} isModal
*/
function appendOverlay(container, hasFade, isModal) {
toggleOverlayType(isModal);
container.append(overlay);
if (hasFade) addClass(overlay, fadeClass);
}
/**
* Shows the overlay to the user.
*/
function showOverlay() {
addClass(overlay, showClass);
reflow(overlay);
}
/**
* Hides the overlay from the user.
*/
function hideOverlay() {
removeClass(overlay, showClass);
}
/**
* Removes the overlay from DOM.
* @param {(HTMLElement | Element)=} element
*/
function removeOverlay(element) {
if (!getCurrentOpen(element)) {
removeClass(overlay, fadeClass);
overlay.remove();
resetScrollbar(element);
}
}
/**
* @param {HTMLElement | Element} element target
* @returns {boolean}
*/
function isVisible(element) {
return element && getElementStyle(element, 'visibility') !== 'hidden'
// @ts-ignore
&& element.offsetParent !== null;
}
/**
* The raw value or a given component option.
*
* @typedef {string | HTMLElement | Function | number | boolean | null} niceValue
*/
/**
* Utility to normalize component options
*
* @param {any} value the input value
* @return {niceValue} the normalized value
*/
function normalizeValue(value) {
if (value === 'true') { // boolean
return true;
}
if (value === 'false') { // boolean
return false;
}
if (!Number.isNaN(+value)) { // number
return +value;
}
if (value === '' || value === 'null') { // null
return null;
}
// string / function / HTMLElement / object
return value;
}
/**
* Shortcut for `Object.keys()` static method.
* @param {Record<string, any>} obj a target object
* @returns {string[]}
*/
const ObjectKeys = (obj) => Object.keys(obj);
/**
* Shortcut for `String.toLowerCase()`.
*
* @param {string} source input string
* @returns {string} lowercase output string
*/
const toLowerCase = (source) => source.toLowerCase();
/**
* Utility to normalize component options.
*
* @param {HTMLElement | Element} element target
* @param {Record<string, any>} defaultOps component default options
* @param {Record<string, any>} inputOps component instance options
* @param {string=} ns component namespace
* @return {Record<string, any>} normalized component options object
*/
function normalizeOptions(element, defaultOps, inputOps, ns) {
// @ts-ignore -- our targets are always `HTMLElement`
const data = { ...element.dataset };
/** @type {Record<string, any>} */
const normalOps = {};
/** @type {Record<string, any>} */
const dataOps = {};
const title = 'title';
ObjectKeys(data).forEach((k) => {
const key = ns && k.includes(ns)
? k.replace(ns, '').replace(/[A-Z]/, (match) => toLowerCase(match))
: k;
dataOps[key] = normalizeValue(data[k]);
});
ObjectKeys(inputOps).forEach((k) => {
inputOps[k] = normalizeValue(inputOps[k]);
});
ObjectKeys(defaultOps).forEach((k) => {
if (k in inputOps) {
normalOps[k] = inputOps[k];
} else if (k in dataOps) {
normalOps[k] = dataOps[k];
} else {
normalOps[k] = k === title
? getAttribute(element, title)
: defaultOps[k];
}
});
return normalOps;
}
var version = "4.1.0alpha5";
const Version = version;
/* Native JavaScript for Bootstrap 5 | Base Component
----------------------------------------------------- */
/** Returns a new `BaseComponent` instance. */
class BaseComponent {
/**
* @param {HTMLElement | Element | string} target `Element` or selector string
* @param {BSN.ComponentOptions=} config component instance options
*/
constructor(target, config) {
const self = this;
const element = querySelector(target);
if (!element) {
throw Error(`${self.name} Error: "${target}" is not a valid selector.`);
}
/** @static @type {BSN.ComponentOptions} */
self.options = {};
const prevInstance = Data.get(element, self.name);
if (prevInstance) prevInstance.dispose();
/** @type {HTMLElement | Element} */
self.element = element;
if (self.defaults && Object.keys(self.defaults).length) {
self.options = normalizeOptions(element, self.defaults, (config || {}), 'bs');
}
Data.set(element, self.name, self);
}
/* eslint-disable */
/** @static */
get version() { return Version; }
/* eslint-enable */
/** @static */
get name() { return this.constructor.name; }
/** @static */
// @ts-ignore
get defaults() { return this.constructor.defaults; }
/**
* Removes component from target element;
*/
dispose() {
const self = this;
Data.remove(self.element, self.name);
// @ts-ignore
ObjectKeys(self).forEach((prop) => { self[prop] = null; });
}
}
/* Native JavaScript for Bootstrap 5 | Modal
-------------------------------------------- */
// MODAL PRIVATE GC
// ================
const modalSelector = `.${modalString}`;
const modalToggleSelector = `[${dataBsToggle}="${modalString}"]`;
const modalDismissSelector = `[${dataBsDismiss}="${modalString}"]`;
const modalStaticClass = `${modalString}-static`;
const modalDefaults = {
backdrop: true, // boolean|string
keyboard: true, // boolean
};
/**
* Static method which returns an existing `Modal` instance associated
* to a target `Element`.
*
* @type {BSN.GetInstance<Modal>}
*/
const getModalInstance = (element) => getInstance(element, modalComponent);
/**
* A `Modal` initialization callback.
* @type {BSN.InitCallback<Modal>}
*/
const modalInitCallback = (element) => new Modal(element);
// MODAL CUSTOM EVENTS
// ===================
const showModalEvent = OriginalEvent(`show.bs.${modalString}`);
const shownModalEvent = OriginalEvent(`shown.bs.${modalString}`);
const hideModalEvent = OriginalEvent(`hide.bs.${modalString}`);
const hiddenModalEvent = OriginalEvent(`hidden.bs.${modalString}`);
// MODAL PRIVATE METHODS
// =====================
/**
* Applies special style for the `<body>` and fixed elements
* when a modal instance is shown to the user.
*
* @param {Modal} self the `Modal` instance
*/
function setModalScrollbar(self) {
const { element } = self;
const scrollbarWidth = measureScrollbar(element);
const { clientHeight, scrollHeight } = getDocumentElement(element);
const { clientHeight: modalHeight, scrollHeight: modalScrollHeight } = element;
const modalOverflow = modalHeight !== modalScrollHeight;
if (!modalOverflow && scrollbarWidth) {
const pad = isRTL(element) ? 'paddingLeft' : 'paddingRight';
// @ts-ignore
element.style[pad] = `${scrollbarWidth}px`;
}
setScrollbar(element, (modalOverflow || clientHeight !== scrollHeight));
}
/**
* Toggles on/off the listeners of events that close the modal.
*
* @param {Modal} self the `Modal` instance
* @param {boolean=} add when `true`, event listeners are added
*/
function toggleModalDismiss(self, add) {
const action = add ? addListener : removeListener;
const { element } = self;
action(element, mouseclickEvent, modalDismissHandler);
// @ts-ignore
action(getWindow(element), resizeEvent, self.update, passiveHandler);
action(getDocument(element), keydownEvent, modalKeyHandler);
}
/**
* Toggles on/off the `click` event listener of the `Modal` instance.
* @param {Modal} self the `Modal` instance
* @param {boolean=} add when `true`, event listener is added
*/
function toggleModalHandler(self, add) {
const action = add ? addListener : removeListener;
const { triggers } = self;
if (triggers.length) {
triggers.forEach((btn) => action(btn, mouseclickEvent, modalClickHandler));
}
}
/**
* Executes after a modal is hidden to the user.
* @param {Modal} self the `Modal` instance
*/
function afterModalHide(self) {
const { triggers, element } = self;
removeOverlay(element);
// @ts-ignore
element.style.paddingRight = '';
if (triggers.length) {
const visibleTrigger = triggers.find((x) => isVisible(x));
if (visibleTrigger) focus(visibleTrigger);
}
}
/**
* Executes after a modal is shown to the user.
* @param {Modal} self the `Modal` instance
*/
function afterModalShow(self) {
const { element, relatedTarget } = self;
focus(element);
toggleModalDismiss(self, true);
shownModalEvent.relatedTarget = relatedTarget;
dispatchEvent(element, shownModalEvent);
}
/**
* Executes before a modal is shown to the user.
* @param {Modal} self the `Modal` instance
*/
function beforeModalShow(self) {
const { element, hasFade } = self;
// @ts-ignore
element.style.display = 'block';
setModalScrollbar(self);
if (!getCurrentOpen(element)) {
getDocumentBody(element).style.overflow = 'hidden';
}
addClass(element, showClass);
removeAttribute(element, ariaHidden);
setAttribute(element, ariaModal, 'true');
if (hasFade) emulateTransitionEnd(element, () => afterModalShow(self));
else afterModalShow(self);
}
/**
* Executes before a modal is hidden to the user.
* @param {Modal} self the `Modal` instance
* @param {boolean=} force when `true` skip animation
*/
function beforeModalHide(self, force) {
const {
element, options, relatedTarget, hasFade,
} = self;
// @ts-ignore
element.style.display = '';
// force can also be the transitionEvent object, we wanna make sure it's not
// call is not forced and overlay is visible
if (options.backdrop && !force && hasFade && hasClass(overlay, showClass)
&& !getCurrentOpen(element)) { // AND no modal is visible
hideOverlay();
emulateTransitionEnd(overlay, () => afterModalHide(self));
} else {
afterModalHide(self);
}
toggleModalDismiss(self);
hiddenModalEvent.relatedTarget = relatedTarget;
dispatchEvent(element, hiddenModalEvent);
}
// MODAL EVENT HANDLERS
// ====================
/**
* Handles the `click` event listener for modal.
* @param {MouseEvent} e the `Event` object
* @this {HTMLElement | Element}
*/
function modalClickHandler(e) {
const { target } = e;
const trigger = target && closest(this, modalToggleSelector);
const element = trigger && getTargetElement(trigger);
const self = element && getModalInstance(element);
if (!self) return;
if (trigger && trigger.tagName === 'A') e.preventDefault();
self.relatedTarget = trigger;
self.toggle();
}
/**
* Handles the `keydown` event listener for modal
* to hide the modal when user type the `ESC` key.
*
* @param {KeyboardEvent} e the `Event` object
*/
function modalKeyHandler({ code }) {
const element = querySelector(modalActiveSelector);
const self = element && getModalInstance(element);
if (!self) return;
const { options } = self;
if (options.keyboard && code === keyEscape // the keyboard option is enabled and the key is 27
&& hasClass(element, showClass)) { // the modal is not visible
self.relatedTarget = null;
self.hide();
}
}
/**
* Handles the `click` event listeners that hide the modal.
*
* @this {HTMLElement | Element}
* @param {MouseEvent} e the `Event` object
*/
function modalDismissHandler(e) {
const element = this;
const self = getModalInstance(element);
// this timer is needed
if (!self || Timer.get(element)) return;
const { options, isStatic, modalDialog } = self;
const { backdrop } = options;
const { target } = e;
// @ts-ignore
const selectedText = getDocument(element).getSelection().toString().length;
// @ts-ignore
const targetInsideDialog = modalDialog.contains(target);
// @ts-ignore
const dismiss = target && closest(target, modalDismissSelector);
if (isStatic && !targetInsideDialog) {
Timer.set(element, () => {
addClass(element, modalStaticClass);
emulateTransitionEnd(modalDialog, () => staticTransitionEnd(self));
}, 17);
} else if (dismiss || (!selectedText && !isStatic && !targetInsideDialog && backdrop)) {
self.relatedTarget = dismiss || null;
self.hide();
e.preventDefault();
}
}
/**
* Handles the `transitionend` event listeners for `Modal`.
*
* @param {Modal} self the `Modal` instance
*/
function staticTransitionEnd(self) {
const { element, modalDialog } = self;
const duration = getElementTransitionDuration(modalDialog) + 17;
removeClass(element, modalStaticClass);
// user must wait for zoom out transition
Timer.set(element, () => Timer.clear(element), duration);
}
// MODAL DEFINITION
// ================
/** Returns a new `Modal` instance. */
class Modal extends BaseComponent {
/**
* @param {HTMLElement | Element | string} target usually the `.modal` element
* @param {BSN.Options.Modal=} config instance options
*/
constructor(target, config) {
super(target, config);
// bind
const self = this;
// the modal
const { element } = self;
// the modal-dialog
/** @type {(HTMLElement | Element)} */
// @ts-ignore
self.modalDialog = querySelector(`.${modalString}-dialog`, element);
// modal can have multiple triggering elements
/** @type {(HTMLElement | Element)[]} */
self.triggers = [...querySelectorAll(modalToggleSelector)]
.filter((btn) => getTargetElement(btn) === element);
// additional internals
/** @type {boolean} */
self.isStatic = self.options.backdrop === 'static';
/** @type {boolean} */
self.hasFade = hasClass(element, fadeClass);
/** @type {(HTMLElement | Element)?} */
self.relatedTarget = null;
/** @type {HTMLBodyElement | HTMLElement | Element} */
// @ts-ignore
self.container = getElementContainer(element);
// attach event listeners
toggleModalHandler(self, true);
// bind
self.update = self.update.bind(self);
}
/* eslint-disable */
/**
* Returns component name string.
* @readonly @static
*/
get name() { return modalComponent; }
/**
* Returns component default options.
* @readonly @static
*/
get defaults() { return modalDefaults; }
/* eslint-enable */
// MODAL PUBLIC METHODS
// ====================
/** Toggles the visibility of the modal. */
toggle() {
const self = this;
if (hasClass(self.element, showClass)) self.hide();
else self.show();
}
/** Shows the modal to the user. */
show() {
const self = this;
const {
element, options, hasFade, relatedTarget, container,
} = self;
const { backdrop } = options;
let overlayDelay = 0;
if (hasClass(element, showClass)) return;
showModalEvent.relatedTarget = relatedTarget || null;
dispatchEvent(element, showModalEvent);
if (showModalEvent.defaultPrevented) return;
// we elegantly hide any opened modal/offcanvas
const currentOpen = getCurrentOpen(element);
if (currentOpen && currentOpen !== element) {
const this1 = getModalInstance(currentOpen);
const that1 = this1 || getInstance(currentOpen, 'Offcanvas');
that1.hide();
}
if (backdrop) {
if (!currentOpen && !hasClass(overlay, showClass)) {
appendOverlay(container, hasFade, true);
} else {
toggleOverlayType(true);
}
overlayDelay = getElementTransitionDuration(overlay);
if (!hasClass(overlay, showClass)) showOverlay();
setTimeout(() => beforeModalShow(self), overlayDelay);
} else {
beforeModalShow(self);
if (currentOpen && hasClass(overlay, showClass)) {
hideOverlay();
}
}
}
/**
* Hide the modal from the user.
* @param {boolean=} force when `true` it will skip animation
*/
hide(force) {
const self = this;
const {
element, hasFade, relatedTarget,
} = self;
if (!hasClass(element, showClass)) return;
hideModalEvent.relatedTarget = relatedTarget || null;
dispatchEvent(element, hideModalEvent);
if (hideModalEvent.defaultPrevented) return;
removeClass(element, showClass);
setAttribute(element, ariaHidden, 'true');
removeAttribute(element, ariaModal);
if (hasFade && force !== false) {
emulateTransitionEnd(element, () => beforeModalHide(self));
} else {
beforeModalHide(self, force);
}
}
/** Updates the modal layout. */
update() {
const self = this;
if (hasClass(self.element, showClass)) setModalScrollbar(self);
}
/** Removes the `Modal` component from target element. */
dispose() {
const self = this;
self.hide(true); // forced call
toggleModalHandler(self);
super.dispose();
}
}
ObjectAssign(Modal, {
selector: modalSelector,
init: modalInitCallback,
getInstance: getModalInstance,
});
export { Modal as default };
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
typeof define === 'function' && define.amd ? define(['jquery'], factory) :
(global = global || self, factory(global.jQuery));
}(this, (function ($) { 'use strict';
$ = $ && Object.prototype.hasOwnProperty.call($, 'default') ? $['default'] : $;
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global_1 =
// eslint-disable-next-line no-undef
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
check(typeof self == 'object' && self) ||
check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
// eslint-disable-next-line no-new-func
Function('return this')();
var fails = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
// Thank's IE8 for his funny defineProperty
var descriptors = !fails(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
var f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : nativePropertyIsEnumerable;
var objectPropertyIsEnumerable = {
f: f
};
var createPropertyDescriptor = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var toString = {}.toString;
var classofRaw = function (it) {
return toString.call(it).slice(8, -1);
};
var split = ''.split;
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);
} : Object;
// `RequireObjectCoercible` abstract operation
// https://tc39.github.io/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
// toObject with fallback for non-array-like ES3 strings
var toIndexedObject = function (it) {
return indexedObject(requireObjectCoercible(it));
};
var isObject = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
// `ToPrimitive` abstract operation
// https://tc39.github.io/ecma262/#sec-toprimitive
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
var toPrimitive = function (input, PREFERRED_STRING) {
if (!isObject(input)) return input;
var fn, val;
if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
throw TypeError("Can't convert object to primitive value");
};
var hasOwnProperty = {}.hasOwnProperty;
var has = function (it, key) {
return hasOwnProperty.call(it, key);
};
var document = global_1.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document) && isObject(document.createElement);
var documentCreateElement = function (it) {
return EXISTS ? document.createElement(it) : {};
};
// Thank's IE8 for his funny defineProperty
var ie8DomDefine = !descriptors && !fails(function () {
return Object.defineProperty(documentCreateElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPrimitive(P, true);
if (ie8DomDefine) try {
return nativeGetOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]);
};
var objectGetOwnPropertyDescriptor = {
f: f$1
};
var anObject = function (it) {
if (!isObject(it)) {
throw TypeError(String(it) + ' is not an object');
} return it;
};
var nativeDefineProperty = Object.defineProperty;
// `Object.defineProperty` method
// https://tc39.github.io/ecma262/#sec-object.defineproperty
var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (ie8DomDefine) try {
return nativeDefineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
var objectDefineProperty = {
f: f$2
};
var createNonEnumerableProperty = descriptors ? function (object, key, value) {
return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
var setGlobal = function (key, value) {
try {
createNonEnumerableProperty(global_1, key, value);
} catch (error) {
global_1[key] = value;
} return value;
};
var SHARED = '__core-js_shared__';
var store = global_1[SHARED] || setGlobal(SHARED, {});
var sharedStore = store;
var functionToString = Function.toString;
// this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper
if (typeof sharedStore.inspectSource != 'function') {
sharedStore.inspectSource = function (it) {
return functionToString.call(it);
};
}
var inspectSource = sharedStore.inspectSource;
var WeakMap = global_1.WeakMap;
var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));
var shared = createCommonjsModule(function (module) {
(module.exports = function (key, value) {
return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.6.0',
mode: 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
});
var id = 0;
var postfix = Math.random();
var uid = function (key) {
return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
};
var keys = shared('keys');
var sharedKey = function (key) {
return keys[key] || (keys[key] = uid(key));
};
var hiddenKeys = {};
var WeakMap$1 = global_1.WeakMap;
var set, get, has$1;
var enforce = function (it) {
return has$1(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (nativeWeakMap) {
var store$1 = new WeakMap$1();
var wmget = store$1.get;
var wmhas = store$1.has;
var wmset = store$1.set;
set = function (it, metadata) {
wmset.call(store$1, it, metadata);
return metadata;
};
get = function (it) {
return wmget.call(store$1, it) || {};
};
has$1 = function (it) {
return wmhas.call(store$1, it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
createNonEnumerableProperty(it, STATE, metadata);
return metadata;
};
get = function (it) {
return has(it, STATE) ? it[STATE] : {};
};
has$1 = function (it) {
return has(it, STATE);
};
}
var internalState = {
set: set,
get: get,
has: has$1,
enforce: enforce,
getterFor: getterFor
};
var redefine = createCommonjsModule(function (module) {
var getInternalState = internalState.get;
var enforceInternalState = internalState.enforce;
var TEMPLATE = String(String).split('String');
(module.exports = function (O, key, value, options) {
var unsafe = options ? !!options.unsafe : false;
var simple = options ? !!options.enumerable : false;
var noTargetGet = options ? !!options.noTargetGet : false;
if (typeof value == 'function') {
if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);
enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
}
if (O === global_1) {
if (simple) O[key] = value;
else setGlobal(key, value);
return;
} else if (!unsafe) {
delete O[key];
} else if (!noTargetGet && O[key]) {
simple = true;
}
if (simple) O[key] = value;
else createNonEnumerableProperty(O, key, value);
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, 'toString', function toString() {
return typeof this == 'function' && getInternalState(this).source || inspectSource(this);
});
});
var path = global_1;
var aFunction = function (variable) {
return typeof variable == 'function' ? variable : undefined;
};
var getBuiltIn = function (namespace, method) {
return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace])
: path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method];
};
var ceil = Math.ceil;
var floor = Math.floor;
// `ToInteger` abstract operation
// https://tc39.github.io/ecma262/#sec-tointeger
var toInteger = function (argument) {
return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
};
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.github.io/ecma262/#sec-tolength
var toLength = function (argument) {
return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
var max = Math.max;
var min$1 = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
var toAbsoluteIndex = function (index, length) {
var integer = toInteger(index);
return integer < 0 ? max(integer + length, 0) : min$1(integer, length);
};
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
var arrayIncludes = {
// `Array.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
var indexOf = arrayIncludes.indexOf;
var objectKeysInternal = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~indexOf(result, key) || result.push(key);
}
return result;
};
// IE8- don't enum bug keys
var enumBugKeys = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return objectKeysInternal(O, hiddenKeys$1);
};
var objectGetOwnPropertyNames = {
f: f$3
};
var f$4 = Object.getOwnPropertySymbols;
var objectGetOwnPropertySymbols = {
f: f$4
};
// all object keys, includes non-enumerable and symbols
var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = objectGetOwnPropertyNames.f(anObject(it));
var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
};
var copyConstructorProperties = function (target, source) {
var keys = ownKeys(source);
var defineProperty = objectDefineProperty.f;
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
};
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: typeof detection == 'function' ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
var isForced_1 = isForced;
var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
*/
var _export = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global_1;
} else if (STATIC) {
target = global_1[TARGET] || setGlobal(TARGET, {});
} else {
target = (global_1[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor$1(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty === typeof targetProperty) continue;
copyConstructorProperties(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty(sourceProperty, 'sham', true);
}
// extend global
redefine(target, key, sourceProperty, options);
}
};
// `IsArray` abstract operation
// https://tc39.github.io/ecma262/#sec-isarray
var isArray = Array.isArray || function isArray(arg) {
return classofRaw(arg) == 'Array';
};
// `ToObject` abstract operation
// https://tc39.github.io/ecma262/#sec-toobject
var toObject = function (argument) {
return Object(requireObjectCoercible(argument));
};
var createProperty = function (object, key, value) {
var propertyKey = toPrimitive(key);
if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () {
// Chrome 38 Symbol has incorrect toString conversion
// eslint-disable-next-line no-undef
return !String(Symbol());
});
var useSymbolAsUid = nativeSymbol
// eslint-disable-next-line no-undef
&& !Symbol.sham
// eslint-disable-next-line no-undef
&& typeof Symbol() == 'symbol';
var WellKnownSymbolsStore = shared('wks');
var Symbol$1 = global_1.Symbol;
var createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : uid;
var wellKnownSymbol = function (name) {
if (!has(WellKnownSymbolsStore, name)) {
if (nativeSymbol && has(Symbol$1, name)) WellKnownSymbolsStore[name] = Symbol$1[name];
else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name);
} return WellKnownSymbolsStore[name];
};
var SPECIES = wellKnownSymbol('species');
// `ArraySpeciesCreate` abstract operation
// https://tc39.github.io/ecma262/#sec-arrayspeciescreate
var arraySpeciesCreate = function (originalArray, length) {
var C;
if (isArray(originalArray)) {
C = originalArray.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
else if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
};
var userAgent = getBuiltIn('navigator', 'userAgent') || '';
var process = global_1.process;
var versions = process && process.versions;
var v8 = versions && versions.v8;
var match, version;
if (v8) {
match = v8.split('.');
version = match[0] + match[1];
} else if (userAgent) {
match = userAgent.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = userAgent.match(/Chrome\/(\d+)/);
if (match) version = match[1];
}
}
var v8Version = version && +version;
var SPECIES$1 = wellKnownSymbol('species');
var arrayMethodHasSpeciesSupport = function (METHOD_NAME) {
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/677
return v8Version >= 51 || !fails(function () {
var array = [];
var constructor = array.constructor = {};
constructor[SPECIES$1] = function () {
return { foo: 1 };
};
return array[METHOD_NAME](Boolean).foo !== 1;
});
};
var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/679
var IS_CONCAT_SPREADABLE_SUPPORT = v8Version >= 51 || !fails(function () {
var array = [];
array[IS_CONCAT_SPREADABLE] = false;
return array.concat()[0] !== array;
});
var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
var isConcatSpreadable = function (O) {
if (!isObject(O)) return false;
var spreadable = O[IS_CONCAT_SPREADABLE];
return spreadable !== undefined ? !!spreadable : isArray(O);
};
var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
// `Array.prototype.concat` method
// https://tc39.github.io/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
_export({ target: 'Array', proto: true, forced: FORCED }, {
concat: function concat(arg) { // eslint-disable-line no-unused-vars
var O = toObject(this);
var A = arraySpeciesCreate(O, 0);
var n = 0;
var i, k, length, len, E;
for (i = -1, length = arguments.length; i < length; i++) {
E = i === -1 ? O : arguments[i];
if (isConcatSpreadable(E)) {
len = toLength(E.length);
if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
} else {
if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
createProperty(A, n++, E);
}
}
A.length = n;
return A;
}
});
/**
* Bootstrap Table Spanish (Argentina) translation
* Author: Felix Vera (felix.vera@gmail.com)
* Edited by: DarkThinking (https://github.com/DarkThinking)
*/
$.fn.bootstrapTable.locales['es-AR'] = {
formatCopyRows: function formatCopyRows() {
return 'Copiar Filas';
},
formatPrint: function formatPrint() {
return 'Imprimir';
},
formatLoadingMessage: function formatLoadingMessage() {
return 'Cargando, espere por favor';
},
formatRecordsPerPage: function formatRecordsPerPage(pageNumber) {
return "".concat(pageNumber, " registros por p\xE1gina");
},
formatShowingRows: function formatShowingRows(pageFrom, pageTo, totalRows, totalNotFiltered) {
if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) {
return "Mostrando desde ".concat(pageFrom, " a ").concat(pageTo, " de ").concat(totalRows, " filas (filtrado de ").concat(totalNotFiltered, " columnas totales)");
}
return "Mostrando desde ".concat(pageFrom, " a ").concat(pageTo, " de ").concat(totalRows, " filas");
},
formatSRPaginationPreText: function formatSRPaginationPreText() {
return 'página anterior';
},
formatSRPaginationPageText: function formatSRPaginationPageText(page) {
return "a la p\xE1gina ".concat(page);
},
formatSRPaginationNextText: function formatSRPaginationNextText() {
return 'siguiente página';
},
formatDetailPagination: function formatDetailPagination(totalRows) {
return "Mostrando ".concat(totalRows, " columnas");
},
formatClearSearch: function formatClearSearch() {
return 'Limpiar búsqueda';
},
formatSearch: function formatSearch() {
return 'Buscar';
},
formatNoMatches: function formatNoMatches() {
return 'No se encontraron registros';
},
formatPaginationSwitch: function formatPaginationSwitch() {
return 'Ocultar/Mostrar paginación';
},
formatPaginationSwitchDown: function formatPaginationSwitchDown() {
return 'Mostrar paginación';
},
formatPaginationSwitchUp: function formatPaginationSwitchUp() {
return 'Ocultar paginación';
},
formatRefresh: function formatRefresh() {
return 'Recargar';
},
formatToggle: function formatToggle() {
return 'Cambiar';
},
formatToggleOn: function formatToggleOn() {
return 'Mostrar vista de carta';
},
formatToggleOff: function formatToggleOff() {
return 'Ocultar vista de carta';
},
formatColumns: function formatColumns() {
return 'Columnas';
},
formatColumnsToggleAll: function formatColumnsToggleAll() {
return 'Cambiar todo';
},
formatFullscreen: function formatFullscreen() {
return 'Pantalla completa';
},
formatAllRows: function formatAllRows() {
return 'Todo';
},
formatAutoRefresh: function formatAutoRefresh() {
return 'Auto Recargar';
},
formatExport: function formatExport() {
return 'Exportar datos';
},
formatJumpTo: function formatJumpTo() {
return 'Ir';
},
formatAdvancedSearch: function formatAdvancedSearch() {
return 'Búsqueda avanzada';
},
formatAdvancedCloseButton: function formatAdvancedCloseButton() {
return 'Cerrar';
},
formatFilterControlSwitch: function formatFilterControlSwitch() {
return 'Ocultar/Mostrar controles';
},
formatFilterControlSwitchHide: function formatFilterControlSwitchHide() {
return 'Ocultar controles';
},
formatFilterControlSwitchShow: function formatFilterControlSwitchShow() {
return 'Mostrar controles';
}
};
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['es-AR']);
})));
|
/**
* Tom Select v1.2.1
* Licensed under the Apache License, Version 2.0 (the "License");
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../tom-select.ts')) :
typeof define === 'function' && define.amd ? define(['../../tom-select.ts'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TomSelect));
}(this, (function (TomSelect) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var TomSelect__default = /*#__PURE__*/_interopDefaultLegacy(TomSelect);
var defaults = {
options: [],
optgroups: [],
plugins: [],
delimiter: ',',
splitOn: null,
// regexp or string for splitting up values from a paste command
persist: true,
diacritics: true,
create: null,
createOnBlur: false,
createFilter: null,
highlight: true,
openOnFocus: true,
shouldOpen: null,
maxOptions: 50,
maxItems: null,
hideSelected: null,
duplicates: false,
addPrecedence: false,
selectOnTab: false,
preload: null,
allowEmptyOption: false,
closeAfterSelect: false,
scrollDuration: 60,
loadThrottle: 300,
loadingClass: 'loading',
dataAttr: null,
//'data-data',
optgroupField: 'optgroup',
valueField: 'value',
labelField: 'text',
disabledField: 'disabled',
optgroupLabelField: 'label',
optgroupValueField: 'value',
lockOptgroupOrder: false,
sortField: '$order',
searchField: ['text'],
searchConjunction: 'and',
mode: null,
wrapperClass: 'ts-control',
inputClass: 'ts-input',
dropdownClass: 'ts-dropdown',
dropdownContentClass: 'ts-dropdown-content',
itemClass: 'item',
optionClass: 'option',
dropdownParent: null,
controlInput: null,
copyClassesToDropdown: true,
shouldLoad: function (query) {
return query.length > 0;
},
/*
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() { ... }
onOptionGroupAdd : null, // function(id, data) { ... }
onOptionGroupRemove : null, // function(id) { ... }
onOptionGroupClear : 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
*/
}
};
/**
* Converts a scalar to its best string representation
* for hash keys and HTML attribute values.
*
* Transformations:
* 'str' -> 'str'
* null -> ''
* undefined -> ''
* true -> '1'
* false -> '0'
* 0 -> '0'
* 1 -> '1'
*
*/
function hash_key(value) {
if (typeof value === 'undefined' || value === null) return null;
if (typeof value === 'boolean') return value ? '1' : '0';
return value + '';
}
/**
* Prevent default
*
*/
function addEvent(target, type, callback, options) {
target.addEventListener(type, callback, options);
}
function getSettings(input, settings_user) {
var settings = Object.assign({}, defaults, settings_user);
var attr_data = settings.dataAttr;
var field_label = settings.labelField;
var field_value = settings.valueField;
var field_disabled = settings.disabledField;
var field_optgroup = settings.optgroupField;
var field_optgroup_label = settings.optgroupLabelField;
var field_optgroup_value = settings.optgroupValueField;
var tag_name = input.tagName.toLowerCase();
var placeholder = input.getAttribute('placeholder') || input.getAttribute('data-placeholder');
if (!placeholder && !settings.allowEmptyOption) {
let option = input.querySelector('option[value=""]');
if (option) {
placeholder = option.textContent;
}
}
var settings_element = {
placeholder: placeholder,
options: [],
optgroups: [],
items: [],
maxItems: null
};
/**
* Initialize from a <select> element.
*
*/
var init_select = () => {
var tagName;
var options = settings_element.options;
var optionsMap = {};
var group_count = 1;
var readData = el => {
var data = Object.assign({}, el.dataset); // get plain object from DOMStringMap
var json = attr_data && data[attr_data];
if (typeof json === 'string' && json.length) {
data = Object.assign(data, JSON.parse(json));
}
return data;
};
var addOption = (option, group) => {
var value = hash_key(option.value);
if (!value && !settings.allowEmptyOption) return; // if the option already exists, it's probably been
// duplicated in another optgroup. in this case, push
// the current group to the "optgroup" property on the
// existing option so that it's rendered in both places.
if (optionsMap.hasOwnProperty(value)) {
if (group) {
var arr = optionsMap[value][field_optgroup];
if (!arr) {
optionsMap[value][field_optgroup] = group;
} else if (!Array.isArray(arr)) {
optionsMap[value][field_optgroup] = [arr, group];
} else {
arr.push(group);
}
}
return;
}
var option_data = readData(option);
option_data[field_label] = option_data[field_label] || option.textContent;
option_data[field_value] = option_data[field_value] || value;
option_data[field_disabled] = option_data[field_disabled] || option.disabled;
option_data[field_optgroup] = option_data[field_optgroup] || group;
optionsMap[value] = option_data;
options.push(option_data);
if (option.selected) {
settings_element.items.push(value);
}
};
var addGroup = optgroup => {
var id, optgroup_data;
optgroup_data = readData(optgroup);
optgroup_data[field_optgroup_label] = optgroup_data[field_optgroup_label] || optgroup.getAttribute('label') || '';
optgroup_data[field_optgroup_value] = optgroup_data[field_optgroup_value] || group_count++;
optgroup_data[field_disabled] = optgroup_data[field_disabled] || optgroup.disabled;
settings_element.optgroups.push(optgroup_data);
id = optgroup_data[field_optgroup_value];
for (const option of optgroup.children) {
addOption(option, id);
}
};
settings_element.maxItems = input.hasAttribute('multiple') ? null : 1;
for (const child of input.children) {
tagName = child.tagName.toLowerCase();
if (tagName === 'optgroup') {
addGroup(child);
} else if (tagName === 'option') {
addOption(child);
}
}
};
/**
* Initialize from a <input type="text"> element.
*
*/
var init_textbox = () => {
var values, option;
var data_raw = input.getAttribute(attr_data);
if (!data_raw) {
var value = input.value.trim() || '';
if (!settings.allowEmptyOption && !value.length) return;
values = value.split(settings.delimiter);
for (const _value of values) {
option = {};
option[field_label] = _value;
option[field_value] = _value;
settings_element.options.push(option);
}
settings_element.items = values;
} else {
settings_element.options = JSON.parse(data_raw);
for (const opt of settings_element.options) {
settings_element.items.push(opt[field_value]);
}
}
};
if (tag_name === 'select') {
init_select();
} else {
init_textbox();
}
return Object.assign({}, defaults, settings_element, settings_user);
}
/**
* Plugin: "change_listener" (Tom Select)
* Copyright (c) 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.
*
*/
TomSelect__default['default'].define('change_listener', function (options) {
var self = this;
var changed = false;
addEvent(self.input, 'change', () => {
// prevent infinite loops
if (changed) {
changed = false;
return;
}
changed = true;
var settings = getSettings(self.input, {});
self.setupOptions(settings.options, settings.optgroups);
self.setValue(settings.items);
});
});
})));
//# sourceMappingURL=change_listener.js.map
|
/**
* Tom Select v1.7.3
* Licensed under the Apache License, Version 2.0 (the "License");
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TomSelect=t()}(this,(function(){"use strict"
function e(e,t){e.split(/\s+/).forEach((e=>{t(e)}))}class t{constructor(){this._events={}}on(t,i){e(t,(e=>{this._events[e]=this._events[e]||[],this._events[e].push(i)}))}off(t,i){var s=arguments.length
0!==s?e(t,(e=>{if(1===s)return delete this._events[e]
e in this._events!=!1&&this._events[e].splice(this._events[e].indexOf(i),1)})):this._events={}}trigger(t,...i){var s=this
e(t,(e=>{if(e in s._events!=!1)for(let t of s._events[e])t.apply(s,i)}))}}var i=[[67,67],[160,160],[192,438],[452,652],[961,961],[1019,1019],[1083,1083],[1281,1289],[1984,1984],[5095,5095],[7429,7441],[7545,7549],[7680,7935],[8580,8580],[9398,9449],[11360,11391],[42792,42793],[42802,42851],[42873,42897],[42912,42922],[64256,64260],[65313,65338],[65345,65370]]
function s(e){return e.normalize("NFD").replace(/[\u0300-\u036F]/g,"").normalize("NFKD").toLowerCase()}var n=null
function o(e){null===n&&(n=function(){var e={"l·":"l","ʼn":"n","æ":"ae","ø":"o","aʾ":"a","dž":"dz"},t={}
return i.forEach((i=>{for(let s=i[0];s<=i[1];s++){let i=String.fromCharCode(s),n=i.normalize("NFD").replace(/[\u0300-\u036F]/g,"").normalize("NFKD")
n!=i&&(n=n.toLowerCase(),n in e&&(n=e[n]),n in t||(t[n]=n+n.toUpperCase()),t[n]+=i)}})),t}())
for(let t in n)n.hasOwnProperty(t)&&(e=e.replace(new RegExp(t,"g"),"["+n[t]+"]"))
return e}function r(e,t){if(e)return e[t]}function l(e,t){if(e){for(var i=t.split(".");i.length&&(e=e[i.shift()]););return e}}function a(e,t,i){var s,n
return e?-1===(n=(e+="").search(t.regex))?0:(s=t.string.length/e.length,0===n&&(s+=.5),s*i):0}function c(e){return(e+"").replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}function d(e,t){var i=e[t]
i&&!Array.isArray(i)&&(e[t]=[i])}function p(e,t){if(Array.isArray(e))e.forEach(t)
else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)}function u(e,t){return"number"==typeof e&&"number"==typeof t?e>t?1:e<t?-1:0:(e=s(e+"").toLowerCase())>(t=s(t+"").toLowerCase())?1:t>e?-1:0}class h{constructor(e,t){this.items=void 0,this.settings=void 0,this.items=e,this.settings=t||{diacritics:!0}}tokenize(e,t,i){if(!e||!e.length)return[]
const s=[],n=e.split(/\s+/)
var r
return i&&(r=new RegExp("^("+Object.keys(i).map(c).join("|")+"):(.*)$")),n.forEach((e=>{let i,n=null,l=null
r&&(i=e.match(r))&&(n=i[1],e=i[2]),e.length>0&&(l=c(e),this.settings.diacritics&&(l=o(l)),t&&(l="\\b"+l),l=new RegExp(l,"i")),s.push({string:e,regex:l,field:n})})),s}getScoreFunction(e,t){var i=this.prepareSearch(e,t)
return this._getScoreFunction(i)}_getScoreFunction(e){const t=e.tokens,i=t.length
if(!i)return function(){return 0}
const s=e.options.fields,n=e.weights,o=s.length,r=e.getAttrFn
if(!o)return function(){return 1}
const l=1===o?function(e,t){const i=s[0].field
return a(r(t,i),e,n[i])}:function(e,t){var i=0
if(e.field){const s=r(t,e.field)
!e.regex&&s?i+=1/o:i+=a(s,e,1)}else p(n,((s,n)=>{i+=a(r(t,n),e,s)}))
return i/o}
return 1===i?function(e){return l(t[0],e)}:"and"===e.options.conjunction?function(e){for(var s,n=0,o=0;n<i;n++){if((s=l(t[n],e))<=0)return 0
o+=s}return o/i}:function(e){var s=0
return p(t,(t=>{s+=l(t,e)})),s/i}}getSortFunction(e,t){var i=this.prepareSearch(e,t)
return this._getSortFunction(i)}_getSortFunction(e){var t,i,s,n,o,r
const l=this,a=e.options,c=!e.query&&a.sort_empty||a.sort,d=[],p=[],h=function(t,i){return"$score"===t?i.score:e.getAttrFn(l.items[i.id],t)}
if(c)for(t=0,i=c.length;t<i;t++)(e.query||"$score"!==c[t].field)&&d.push(c[t])
if(e.query){for(r=!0,t=0,i=d.length;t<i;t++)if("$score"===d[t].field){r=!1
break}r&&d.unshift({field:"$score",direction:"desc"})}else for(t=0,i=d.length;t<i;t++)if("$score"===d[t].field){d.splice(t,1)
break}for(t=0,i=d.length;t<i;t++)p.push("desc"===d[t].direction?-1:1)
return(n=d.length)?1===n?(s=d[0].field,o=p[0],function(e,t){return o*u(h(s,e),h(s,t))}):function(e,t){var i,s,o
for(i=0;i<n;i++)if(o=d[i].field,s=p[i]*u(h(o,e),h(o,t)))return s
return 0}:null}prepareSearch(e,t){const i={}
var n=Object.assign({},t)
if(d(n,"sort"),d(n,"sort_empty"),n.fields){if(d(n,"fields"),Array.isArray(n.fields)&&"object"!=typeof n.fields[0]){var o=[]
n.fields.forEach((e=>{o.push({field:e})})),n.fields=o}n.fields.forEach((e=>{i[e.field]="weight"in e?e.weight:1}))}return{options:n,query:e=s(e+"").toLowerCase().trim(),tokens:this.tokenize(e,n.respect_word_boundaries,i),total:0,items:[],weights:i,getAttrFn:n.nesting?l:r}}search(e,t){var i,s,n,o,r=this
return s=this.prepareSearch(e,t),t=s.options,e=s.query,o=t.score||r._getScoreFunction(s),e.length?p(r.items,((e,n)=>{i=o(e),(!1===t.filter||i>0)&&s.items.push({score:i,id:n})})):p(r.items,((e,t)=>{s.items.push({score:1,id:t})})),(n=r._getSortFunction(s))&&s.items.sort(n),s.total=s.items.length,"number"==typeof t.limit&&(s.items=s.items.slice(0,t.limit)),s}}function g(e,t){if(null!==t){if("string"==typeof t){if(!t.length)return
t=new RegExp(t,"i")}!function e(i){var s=0
if(3===i.nodeType){var n=i.data.search(t)
if(n>=0&&i.data.length>0){var o=i.data.match(t),r=document.createElement("span")
r.className="highlight"
var l=i.splitText(n)
l.splitText(o[0].length)
var a=l.cloneNode(!0)
r.appendChild(a),l.parentNode.replaceChild(r,l),s=1}}else if(1===i.nodeType&&i.childNodes&&!/(script|style)/i.test(i.tagName)&&("highlight"!==i.className||"SPAN"!==i.tagName))for(var c=0;c<i.childNodes.length;++c)c+=e(i.childNodes[c])
return s}(e)}}const f="undefined"!=typeof navigator&&/Mac/.test(navigator.userAgent)?"metaKey":"ctrlKey"
var v={options:[],optgroups:[],plugins:[],delimiter:",",splitOn:null,persist:!0,diacritics:!0,create:null,createOnBlur:!1,createFilter:null,highlight:!0,openOnFocus:!0,shouldOpen:null,maxOptions:50,maxItems:null,hideSelected:null,duplicates:!1,addPrecedence:!1,selectOnTab:!1,preload:null,allowEmptyOption:!1,closeAfterSelect:!1,loadThrottle:300,loadingClass:"loading",dataAttr:null,optgroupField:"optgroup",valueField:"value",labelField:"text",disabledField:"disabled",optgroupLabelField:"label",optgroupValueField:"value",lockOptgroupOrder:!1,sortField:"$order",searchField:["text"],searchConjunction:"and",mode:null,wrapperClass:"ts-control",inputClass:"ts-input",dropdownClass:"ts-dropdown",dropdownContentClass:"ts-dropdown-content",itemClass:"item",optionClass:"option",dropdownParent:null,controlInput:null,copyClassesToDropdown:!0,placeholder:null,hidePlaceholder:null,shouldLoad:function(e){return e.length>0},render:{}}
function m(e){return null==e?null:y(e)}function y(e){return"boolean"==typeof e?e?"1":"0":e+""}function O(e){return(e+"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function b(e,t,i){var s,n=e.trigger,o={}
for(s in e.trigger=function(){var i=arguments[0]
if(-1===t.indexOf(i))return n.apply(e,arguments)
o[i]=arguments},i.apply(e,[]),e.trigger=n,o)n.apply(e,o[s])}function w(e,t=!1){e&&(e.preventDefault(),t&&e.stopPropagation())}function I(e,t,i,s){e.addEventListener(t,i,s)}function C(e,t){return!!t&&(!!t[e]&&1===(t.altKey?1:0)+(t.ctrlKey?1:0)+(t.shiftKey?1:0)+(t.metaKey?1:0))}function _(e,t){const i=e.getAttribute("id")
return i||(e.setAttribute("id",t),t)}function A(e){if(e.jquery)return e[0]
if(e instanceof HTMLElement)return e
if(e.indexOf("<")>-1){let t=document.createElement("div")
return t.innerHTML=e.trim(),t.firstChild}return document.querySelector(e)}function S(e,t){var i=document.createEvent("HTMLEvents")
i.initEvent(t,!0,!1),e.dispatchEvent(i)}function F(e,t){Object.assign(e.style,t)}function x(e,...t){var i=L(t);(e=P(e)).map((e=>{i.map((t=>{e.classList.add(t)}))}))}function k(e,...t){var i=L(t);(e=P(e)).map((e=>{i.map((t=>{e.classList.remove(t)}))}))}function L(e){var t=[]
for(let i of e)"string"==typeof i&&(i=i.trim().split(/[\11\12\14\15\40]/)),Array.isArray(i)&&(t=t.concat(i))
return t.filter(Boolean)}function P(e){return Array.isArray(e)||(e=[e]),e}function E(e,t,i){if(!i||i.contains(e))for(;e&&e.matches;){if(e.matches(t))return e
e=e.parentNode}}function T(e,t=0){return t>0?e[e.length-1]:e[0]}function q(e,t){if(!e)return-1
t=t||e.nodeName
for(var i=0;e=e.previousElementSibling;)e.matches(t)&&i++
return i}function V(e,t){for(const i in t){let s=t[i]
null==s?e.removeAttribute(i):e.setAttribute(i,s)}}function j(e,t){e.parentNode&&e.parentNode.replaceChild(t,e)}var D=0
class N extends(function(e){return e.plugins={},class extends e{constructor(...e){super(...e),this.plugins={names:[],settings:{},requested:{},loaded:{}}}static define(t,i){e.plugins[t]={name:t,fn:i}}initializePlugins(e){var t,i,s
const n=this,o=[]
if(Array.isArray(e))for(t=0,i=e.length;t<i;t++)"string"==typeof e[t]?o.push(e[t]):(n.plugins.settings[e[t].name]=e[t].options,o.push(e[t].name))
else if(e)for(s in e)e.hasOwnProperty(s)&&(n.plugins.settings[s]=e[s],o.push(s))
for(;o.length;)n.require(o.shift())}loadPlugin(t){var i=this,s=i.plugins,n=e.plugins[t]
if(!e.plugins.hasOwnProperty(t))throw new Error('Unable to find "'+t+'" plugin')
s.requested[t]=!0,s.loaded[t]=n.fn.apply(i,[i.plugins.settings[t]||{}]),s.names.push(t)}require(e){var t=this,i=t.plugins
if(!t.plugins.loaded.hasOwnProperty(e)){if(i.requested[e])throw new Error('Plugin has circular dependency ("'+e+'")')
t.loadPlugin(e)}return i.loaded[e]}}}(t)){constructor(e,t){var i
super(),this.control_input=void 0,this.wrapper=void 0,this.dropdown=void 0,this.control=void 0,this.dropdown_content=void 0,this.order=0,this.settings=void 0,this.input=void 0,this.tabIndex=void 0,this.is_select_tag=void 0,this.rtl=void 0,this.inputId=void 0,this._destroy=void 0,this.sifter=void 0,this.tab_key=!1,this.isOpen=!1,this.isDisabled=!1,this.isRequired=void 0,this.isInvalid=!1,this.isLocked=!1,this.isFocused=!1,this.isInputHidden=!1,this.isSetup=!1,this.ignoreFocus=!1,this.hasOptions=!1,this.currentResults=null,this.lastValue="",this.caretPos=0,this.loading=0,this.loadedSearches={},this.activeOption=null,this.activeItems=[],this.optgroups={},this.options={},this.userOptions={},this.items=[],this.renderCache={item:{},option:{}},D++
var s=A(e)
if(s.tomselect)throw new Error("Tom Select already initialized on this element")
s.tomselect=this,i=(window.getComputedStyle&&window.getComputedStyle(s,null)).getPropertyValue("direction"),this.settings=function(e,t){var i=Object.assign({},v,t),s=i.dataAttr,n=i.labelField,o=i.valueField,r=i.disabledField,l=i.optgroupField,a=i.optgroupLabelField,c=i.optgroupValueField,d=e.tagName.toLowerCase(),p=e.getAttribute("placeholder")||e.getAttribute("data-placeholder")
if(!p&&!i.allowEmptyOption){let t=e.querySelector('option[value=""]')
t&&(p=t.textContent)}var u={placeholder:p,options:[],optgroups:[],items:[],maxItems:null}
return"select"===d?(()=>{var t,d=u.options,p={},h=1,g=e=>{var t=Object.assign({},e.dataset),i=s&&t[s]
return"string"==typeof i&&i.length&&(t=Object.assign(t,JSON.parse(i))),t},f=(e,t)=>{var s=m(e.value)
if(null!=s&&(s||i.allowEmptyOption))if(p.hasOwnProperty(s)){if(t){var a=p[s][l]
a?Array.isArray(a)?a.push(t):p[s][l]=[a,t]:p[s][l]=t}}else{var c=g(e)
c[n]=c[n]||e.textContent,c[o]=c[o]||s,c[r]=c[r]||e.disabled,c[l]=c[l]||t,c.$option=e,p[s]=c,d.push(c),e.selected&&u.items.push(s)}},v=e=>{var t,i;(i=g(e))[a]=i[a]||e.getAttribute("label")||"",i[c]=i[c]||h++,i[r]=i[r]||e.disabled,u.optgroups.push(i),t=i[c]
for(const i of e.children)f(i,t)}
u.maxItems=e.hasAttribute("multiple")?null:1
for(const i of e.children)"optgroup"===(t=i.tagName.toLowerCase())?v(i):"option"===t&&f(i)})():(()=>{var t,r,l=e.getAttribute(s)
if(l){u.options=JSON.parse(l)
for(const e of u.options)u.items.push(e[o])}else{var a=e.value.trim()||""
if(!i.allowEmptyOption&&!a.length)return
t=a.split(i.delimiter)
for(const e of t)(r={})[n]=e,r[o]=e,u.options.push(r)
u.items=t}})(),Object.assign({},v,u,t)}(s,t),this.input=s,this.tabIndex=s.tabIndex||0,this.is_select_tag="select"===s.tagName.toLowerCase(),this.rtl=/rtl/i.test(i),this.inputId=_(s,"tomselect-"+D),this.isRequired=s.required,this.sifter=new h(this.options,{diacritics:this.settings.diacritics}),this.setupOptions(this.settings.options,this.settings.optgroups),delete this.settings.optgroups,delete this.settings.options,this.settings.mode=this.settings.mode||(1===this.settings.maxItems?"single":"multi"),"boolean"!=typeof this.settings.hideSelected&&(this.settings.hideSelected="multi"===this.settings.mode),"boolean"!=typeof this.settings.hidePlaceholder&&(this.settings.hidePlaceholder="multi"!==this.settings.mode)
var n=this.settings.createFilter
"function"!=typeof n&&("string"==typeof n&&(n=new RegExp(n)),n instanceof RegExp?this.settings.createFilter=e=>n.test(e):this.settings.createFilter=()=>!0),this.initializePlugins(this.settings.plugins),this.setupCallbacks(),this.setupTemplates(),this.setup()}setup(){var e,t,i,s,n,o,r,l,a,d=this,p=d.settings,u=d.input
const h={passive:!0},g=d.inputId+"-ts-dropdown"
if(o=d.settings.mode,r=u.getAttribute("class")||"",x(e=A("<div>"),p.wrapperClass,r,o),x(t=A('<div class="items">'),p.inputClass),e.append(t),x(s=d._render("dropdown"),p.dropdownClass,o),x(n=A(`<div role="listbox" id="${g}" tabindex="-1">`),p.dropdownContentClass),s.append(n),A(p.dropdownParent||e).appendChild(s),p.controlInput)i=A(p.controlInput)
else{i=A('<input type="text" autocomplete="off" size="1" />')
for(const e of["autocorrect","autocapitalize","autocomplete"])u.getAttribute(e)&&V(i,{[e]:u.getAttribute(e)})}p.controlInput||(i.tabIndex=u.disabled?-1:d.tabIndex,t.appendChild(i)),V(i,{role:"combobox",haspopup:"listbox","aria-expanded":"false","aria-controls":g}),a=_(i,d.inputId+"-tomselected")
let f="label[for='"+function(e){return e.replace(/['"\\]/g,"\\$&")}(d.inputId)+"']",v=document.querySelector(f)
if(v){V(v,{for:a}),V(n,{"aria-labelledby":_(v,d.inputId+"-ts-label")})}var m,y,O
d.settings.copyClassesToDropdown&&x(s,r),e.style.width=u.style.width,d.plugins.names.length&&(l="plugin-"+d.plugins.names.join(" plugin-"),x([e,s],l)),(null===p.maxItems||p.maxItems>1)&&d.is_select_tag&&V(u,{multiple:"multiple"}),d.settings.placeholder&&V(i,{placeholder:p.placeholder}),!d.settings.splitOn&&d.settings.delimiter&&(d.settings.splitOn=new RegExp("\\s*"+c(d.settings.delimiter)+"+\\s*")),this.settings.load&&this.settings.loadThrottle&&(this.settings.load=(m=this.settings.load,y=this.settings.loadThrottle,function(e,t){var i=this
O&&(i.loading=Math.max(i.loading-1,0)),clearTimeout(O),O=setTimeout((function(){i.loadedSearches[e]=!0,m.call(i,e,t)}),y)})),d.control=t,d.control_input=i,d.wrapper=e,d.dropdown=s,d.dropdown_content=n,d.control_input.type=u.type,I(s,"click",(e=>{const t=E(e.target,"[data-selectable]")
t&&(d.onOptionSelect(e,t),w(e,!0))})),I(t,"click",(e=>{var s=E(e.target,"."+d.settings.itemClass,t)
s&&d.onItemSelect(e,s)?w(e,!0):""==i.value&&(d.onClick(),w(e,!0))})),I(i,"mousedown",(e=>{""!==i.value&&e.stopPropagation()})),I(i,"keydown",(e=>d.onKeyDown(e))),I(i,"keyup",(e=>d.onKeyUp(e))),I(i,"keypress",(e=>d.onKeyPress(e))),I(i,"resize",(()=>d.positionDropdown()),h),I(i,"blur",d.onBlur),I(i,"focus",(e=>d.onFocus(e))),I(i,"paste",(e=>d.onPaste(e)))
const b=t=>{if(!e.contains(t.target)&&!s.contains(t.target))return d.isFocused&&d.blur(),void d.inputState()
w(t,!0)}
var C=()=>{d.isOpen&&d.positionDropdown()}
I(document,"mousedown",b),I(window,"sroll",C,h),I(window,"resize",C,h),d._destroy=()=>{document.removeEventListener("mousedown",b),window.removeEventListener("sroll",C),window.removeEventListener("resize",C)},this.revertSettings={innerHTML:u.innerHTML,tabIndex:u.tabIndex},u.tabIndex=-1,V(u,{hidden:"hidden"}),u.insertAdjacentElement("afterend",d.wrapper),d.setValue(p.items),p.items=[],I(u,"invalid",(e=>{w(e),d.isInvalid||(d.isInvalid=!0,d.refreshState())})),d.updateOriginalInput(),d.refreshItems(),d.close(!1),d.inputState(),d.isSetup=!0,u.disabled&&d.disable(),d.on("change",this.onChange),x(u,"tomselected"),d.trigger("initialize"),!0===p.preload&&d.load("")}setupOptions(e=[],t=[]){for(const t of e)this.registerOption(t)
for(const e of t)this.registerOptionGroup(e)}setupTemplates(){var e=this,t=e.settings.labelField,i=e.settings.optgroupLabelField,s={optgroup:e=>{let t=document.createElement("div")
return t.className="optgroup",t.appendChild(e.options),t},optgroup_header:(e,t)=>'<div class="optgroup-header">'+t(e[i])+"</div>",option:(e,i)=>"<div>"+i(e[t])+"</div>",item:(e,i)=>"<div>"+i(e[t])+"</div>",option_create:(e,t)=>'<div class="create">Add <strong>'+t(e.input)+"</strong>…</div>",no_results:()=>'<div class="no-results">No results found</div>',loading:()=>'<div class="spinner"></div>',not_loading:()=>{},dropdown:()=>"<div></div>"}
e.settings.render=Object.assign({},s,e.settings.render)}setupCallbacks(){var e,t,i={initialize:"onInitialize",change:"onChange",item_add:"onItemAdd",item_remove:"onItemRemove",clear:"onClear",option_add:"onOptionAdd",option_remove:"onOptionRemove",option_clear:"onOptionClear",optgroup_add:"onOptionGroupAdd",optgroup_remove:"onOptionGroupRemove",optgroup_clear:"onOptionGroupClear",dropdown_open:"onDropdownOpen",dropdown_close:"onDropdownClose",type:"onType",load:"onLoad",focus:"onFocus",blur:"onBlur"}
for(e in i)(t=this.settings[i[e]])&&this.on(e,t)}onClick(){var e=this
if(e.activeItems.length>0)return e.clearActiveItems(),void e.focus()
e.isFocused&&e.isOpen?e.blur():e.focus()}onMouseDown(){}onChange(){S(this.input,"input"),S(this.input,"change")}onPaste(e){var t=this
t.isFull()||t.isInputHidden||t.isLocked?w(e):t.settings.splitOn&&setTimeout((()=>{var e=t.inputValue()
if(e.match(t.settings.splitOn)){var i=e.trim().split(t.settings.splitOn)
for(const e of i)t.createItem(e)}}),0)}onKeyPress(e){var t=this
if(!t.isLocked){var i=String.fromCharCode(e.keyCode||e.which)
return t.settings.create&&"multi"===t.settings.mode&&i===t.settings.delimiter?(t.createItem(),void w(e)):void 0}w(e)}onKeyDown(e){var t=this
if(t.isLocked)9!==e.keyCode&&w(e)
else{switch(e.keyCode){case 65:if(C(f,e))return void t.selectAll()
break
case 27:return t.isOpen&&(w(e,!0),t.close()),void t.clearActiveItems()
case 40:if(!t.isOpen&&t.hasOptions)t.open()
else if(t.activeOption){let e=t.getAdjacent(t.activeOption,1)
e&&t.setActiveOption(e)}return void w(e)
case 38:if(t.activeOption){let e=t.getAdjacent(t.activeOption,-1)
e&&t.setActiveOption(e)}return void w(e)
case 13:return void(t.isOpen&&t.activeOption?(t.onOptionSelect(e,t.activeOption),w(e)):t.settings.create&&t.createItem()&&w(e))
case 37:return void t.advanceSelection(-1,e)
case 39:return void t.advanceSelection(1,e)
case 9:return void(t.settings.selectOnTab&&(t.isOpen&&t.activeOption&&(t.tab_key=!0,t.onOptionSelect(e,t.activeOption),w(e),t.tab_key=!1),t.settings.create&&t.createItem()&&w(e)))
case 8:case 46:return void t.deleteSelection(e)}t.isInputHidden&&!C(f,e)&&w(e)}}onKeyUp(e){var t=this
if(t.isLocked)w(e)
else{var i=t.inputValue()
t.lastValue!==i&&(t.lastValue=i,t.settings.shouldLoad.call(t,i)&&t.load(i),t.refreshOptions(),t.trigger("type",i))}}onFocus(e){var t=this,i=t.isFocused
if(t.isDisabled)return t.blur(),void w(e)
t.ignoreFocus||(t.isFocused=!0,"focus"===t.settings.preload&&t.load(""),i||t.trigger("focus"),t.activeItems.length||(t.showInput(),t.refreshOptions(!!t.settings.openOnFocus)),t.refreshState())}onBlur(){var e=this
if(e.isFocused){e.isFocused=!1,e.ignoreFocus=!1
var t=()=>{e.close(),e.setActiveItem(),e.setCaret(e.items.length),e.trigger("blur")}
e.settings.create&&e.settings.createOnBlur?e.createItem(null,!1,t):t()}}onOptionSelect(e,t){var i,s=this
t&&(t.parentElement&&t.parentElement.matches("[data-disabled]")||(t.classList.contains("create")?s.createItem(null,!0,(()=>{s.settings.closeAfterSelect&&s.close()})):void 0!==(i=t.dataset.value)&&(s.lastQuery=null,s.addItem(i),s.settings.closeAfterSelect&&s.close(),!s.settings.hideSelected&&e.type&&/click/.test(e.type)&&s.setActiveOption(t))))}onItemSelect(e,t){var i=this
return!i.isLocked&&"multi"===i.settings.mode&&(w(e),i.setActiveItem(t,e),!0)}canLoad(e){return!!this.settings.load&&!this.loadedSearches.hasOwnProperty(e)}load(e){const t=this
if(!t.canLoad(e))return
x(t.wrapper,t.settings.loadingClass),t.loading++
const i=t.loadCallback.bind(t,e)
t.settings.load.call(t,e,i)}loadCallback(e,t,i){const s=this
s.loading=Math.max(s.loading-1,0),s.lastQuery=null,s.clearActiveOption(),s.setupOptions(t,i),s.refreshOptions(s.isFocused&&!s.isInputHidden),s.loading||k(s.wrapper,s.settings.loadingClass),s.trigger("load",t,i)}setTextboxValue(e=""){var t=this.control_input
t.value!==e&&(t.value=e,S(t,"update"),this.lastValue=e)}getValue(){return this.is_select_tag&&this.input.hasAttribute("multiple")?this.items:this.items.join(this.settings.delimiter)}setValue(e,t){b(this,t?[]:["change"],(()=>{this.clear(t),this.addItems(e,t)}))}setMaxItems(e){0===e&&(e=null),this.settings.maxItems=e,this.refreshState()}setActiveItem(e,t){var i,s,n,o,r,l,a=this
if("single"!==a.settings.mode){if(!e)return a.clearActiveItems(),void(a.isFocused&&a.showInput())
if("click"===(i=t&&t.type.toLowerCase())&&C("shiftKey",t)&&a.activeItems.length){for(l=a.getLastActive(),(n=Array.prototype.indexOf.call(a.control.children,l))>(o=Array.prototype.indexOf.call(a.control.children,e))&&(r=n,n=o,o=r),s=n;s<=o;s++)e=a.control.children[s],-1===a.activeItems.indexOf(e)&&a.setActiveItemClass(e)
w(t)}else"click"===i&&C(f,t)||"keydown"===i&&C("shiftKey",t)?e.classList.contains("active")?a.removeActiveItem(e):a.setActiveItemClass(e):(a.clearActiveItems(),a.setActiveItemClass(e))
a.hideInput(),a.isFocused||a.focus()}}setActiveItemClass(e){var t=this.control.querySelector(".last-active")
t&&k(t,"last-active"),x(e,"active last-active"),-1==this.activeItems.indexOf(e)&&this.activeItems.push(e)}removeActiveItem(e){var t=this.activeItems.indexOf(e)
this.activeItems.splice(t,1),k(e,"active")}clearActiveItems(){k(this.activeItems,"active"),this.activeItems=[]}setActiveOption(e){e!==this.activeOption&&(this.clearActiveOption(),e&&(this.activeOption=e,V(this.control_input,{"aria-activedescendant":e.getAttribute("id")}),V(e,{"aria-selected":"true"}),x(e,"active"),this.scrollToOption(e)))}scrollToOption(e,t){if(!e)return
const i=this.dropdown_content,s=i.clientHeight,n=i.scrollTop||0,o=e.offsetHeight,r=e.getBoundingClientRect().top-i.getBoundingClientRect().top+n
r+o>s+n?this.scroll(r-s+o,t):r<n&&this.scroll(r,t)}scroll(e,t){const i=this.dropdown_content
t&&(i.style.scrollBehavior=t),i.scrollTop=e,i.style.scrollBehavior=""}clearActiveOption(){this.activeOption&&(k(this.activeOption,"active"),V(this.activeOption,{"aria-selected":null})),this.activeOption=null,V(this.control_input,{"aria-activedescendant":null})}selectAll(){"single"!==this.settings.mode&&(this.activeItems=this.controlChildren(),this.activeItems.length&&(x(this.activeItems,"active"),this.hideInput(),this.close()),this.focus())}inputState(){var e=this
e.settings.controlInput||(e.activeItems.length>0||!e.isFocused&&this.settings.hidePlaceholder&&e.items.length>0?(e.setTextboxValue(),e.isInputHidden=!0,x(e.wrapper,"input-hidden")):(e.isInputHidden=!1,k(e.wrapper,"input-hidden")))}hideInput(){this.inputState()}showInput(){this.inputState()}inputValue(){return this.control_input.value.trim()}focus(){var e=this
e.isDisabled||(e.ignoreFocus=!0,e.control_input.focus(),setTimeout((()=>{e.ignoreFocus=!1,e.onFocus()}),0))}blur(){this.control_input.blur(),this.onBlur()}getScoreFunction(e){return this.sifter.getScoreFunction(e,this.getSearchOptions())}getSearchOptions(){var e=this.settings,t=e.sortField
return"string"==typeof e.sortField&&(t=[{field:e.sortField}]),{fields:e.searchField,conjunction:e.searchConjunction,sort:t,nesting:e.nesting}}search(e){var t,i,s,n=this,o=this.getSearchOptions()
if(n.settings.score&&"function"!=typeof(s=n.settings.score.call(n,e)))throw new Error('Tom Select "score" setting must be a function that returns a function')
if(e!==n.lastQuery?(n.lastQuery=e,i=n.sifter.search(e,Object.assign(o,{score:s})),n.currentResults=i):i=Object.assign({},n.currentResults),n.settings.hideSelected)for(t=i.items.length-1;t>=0;t--){let e=m(i.items[t].id)
e&&-1!==n.items.indexOf(e)&&i.items.splice(t,1)}return i}refreshOptions(e=!0){var t,i,s,n,o,r,l,a,c,d,p
const u={},h=[]
var f,v=this,m=v.inputValue(),O=v.search(m),b=v.activeOption,w=v.settings.shouldOpen||!1,I=v.dropdown_content
for(b&&(c=b.dataset.value,d=b.closest("[data-group]")),n=O.items.length,"number"==typeof v.settings.maxOptions&&(n=Math.min(n,v.settings.maxOptions)),n>0&&(w=!0),t=0;t<n;t++){let e=v.options[O.items[t].id],n=y(e[v.settings.valueField]),l=v.getOption(n)
for(l||(l=v._render("option",e)),v.settings.hideSelected||l.classList.toggle("selected",v.items.includes(n)),o=e[v.settings.optgroupField]||"",i=0,s=(r=Array.isArray(o)?o:[o])&&r.length;i<s;i++)o=r[i],v.optgroups.hasOwnProperty(o)||(o=""),u.hasOwnProperty(o)||(u[o]=document.createDocumentFragment(),h.push(o)),i>0&&(l=l.cloneNode(!0),V(l,{id:e.$id+"-clone-"+i,"aria-selected":null}),l.classList.add("ts-cloned"),k(l,"active")),c==n&&d&&d.dataset.group===o&&(b=l),u[o].appendChild(l)}for(o of(this.settings.lockOptgroupOrder&&h.sort(((e,t)=>(v.optgroups[e]&&v.optgroups[e].$order||0)-(v.optgroups[t]&&v.optgroups[t].$order||0))),l=document.createDocumentFragment(),h))if(v.optgroups.hasOwnProperty(o)&&u[o].children.length){let e=document.createDocumentFragment(),t=v.render("optgroup_header",v.optgroups[o])
t&&e.append(t),e.append(u[o])
let i=v.render("optgroup",{group:v.optgroups[o],options:e})
l.append(i)}else l.append(u[o])
if(I.innerHTML="",I.append(l),v.settings.highlight&&(f=I.querySelectorAll("span.highlight"),Array.prototype.forEach.call(f,(function(e){var t=e.parentNode
t.replaceChild(e.firstChild,e),t.normalize()})),O.query.length&&O.tokens.length))for(const e of O.tokens)g(I,e.regex)
var C=e=>{let t=v.render(e,{input:m})
return t&&(w=!0,I.insertBefore(t,I.firstChild)),t}
if(v.settings.shouldLoad.call(v,m)?v.loading?C("loading"):0===O.items.length&&C("no_results"):C("not_loading"),(a=v.canCreate(m))&&(p=C("option_create")),v.hasOptions=O.items.length>0||a,w){if(O.items.length>0){if(!I.contains(b)&&"single"===v.settings.mode&&v.items.length&&(b=v.getOption(v.items[0])),!I.contains(b)){let e=0
p&&!v.settings.addPrecedence&&(e=1),b=v.selectable()[e]}}else b=p
e&&!v.isOpen&&(v.open(),v.scrollToOption(b,"auto")),v.setActiveOption(b)}else v.clearActiveOption(),e&&v.isOpen&&v.close(!1)}selectable(){return this.dropdown_content.querySelectorAll("[data-selectable]")}addOption(e){var t,i=this
if(Array.isArray(e))for(const t of e)i.addOption(t)
else(t=i.registerOption(e))&&(i.userOptions[t]=!0,i.lastQuery=null,i.trigger("option_add",t,e))}registerOption(e){var t=m(e[this.settings.valueField])
return null!==t&&!this.options.hasOwnProperty(t)&&(e.$order=e.$order||++this.order,e.$id=this.inputId+"-opt-"+e.$order,this.options[t]=e,t)}registerOptionGroup(e){var t=m(e[this.settings.optgroupValueField])
return null!==t&&(e.$order=e.$order||++this.order,this.optgroups[t]=e,t)}addOptionGroup(e,t){var i
t[this.settings.optgroupValueField]=e,(i=this.registerOptionGroup(t))&&this.trigger("optgroup_add",i,t)}removeOptionGroup(e){this.optgroups.hasOwnProperty(e)&&(delete this.optgroups[e],this.clearCache(),this.trigger("optgroup_remove",e))}clearOptionGroups(){this.optgroups={},this.clearCache(),this.trigger("optgroup_clear")}updateOption(e,t){const i=this
var s,n
const o=m(e)
if(null===o)return
const r=m(t[i.settings.valueField]),l=i.getOption(o),a=i.getItem(o)
if(i.options.hasOwnProperty(o)){if("string"!=typeof r)throw new Error("Value must be set in option data")
if(t.$order=t.$order||i.options[o].$order,delete i.options[o],i.uncacheValue(r),i.uncacheValue(o,!1),i.options[r]=t,l){if(i.dropdown_content.contains(l)){const e=i._render("option",t)
j(l,e),i.activeOption===l&&i.setActiveOption(e)}l.remove()}a&&(-1!==(n=i.items.indexOf(o))&&i.items.splice(n,1,r),s=i._render("item",t),a.classList.contains("active")&&x(s,"active"),j(a,s)),i.lastQuery=null}}removeOption(e,t){const i=this
e=y(e),i.uncacheValue(e),delete i.userOptions[e],delete i.options[e],i.lastQuery=null,i.trigger("option_remove",e),i.removeItem(e,t)}clearOptions(){this.loadedSearches={},this.userOptions={},this.clearCache()
var e={}
for(let t in this.options)this.options.hasOwnProperty(t)&&this.items.indexOf(t)>=0&&(e[t]=this.options[t])
this.options=this.sifter.items=e,this.lastQuery=null,this.trigger("option_clear")}uncacheValue(e,t=!0){const i=this,s=i.renderCache.item,n=i.renderCache.option
if(s&&delete s[e],n&&delete n[e],t){const t=i.getOption(e)
t&&t.remove()}}getOption(e){var t=m(e)
return t?this.rendered("option",t):null}getAdjacent(e,t,i="option"){var s
if(!e)return null
s="item"==i?this.controlChildren():this.dropdown_content.querySelectorAll("[data-selectable]")
for(let i=0;i<s.length;i++)if(s[i]==e)return t>0?s[i+1]:s[i-1]
return null}getItem(e){var t,i=m(e)
return i?this.control.querySelector(`[data-value="${t=i,t.replace(/[\\"']/g,"\\$&")}"]`):null}addItems(e,t){var i=this
i.buffer=document.createDocumentFragment()
for(const e of i.control.children)i.buffer.appendChild(e)
var s=Array.isArray(e)?e:[e]
for(let e=0,n=(s=s.filter((e=>-1===i.items.indexOf(e)))).length;e<n;e++)i.isPending=e<n-1,i.addItem(s[e],t)
var n=i.control
n.insertBefore(i.buffer,n.firstChild),i.buffer=null}addItem(e,t){b(this,t?[]:["change"],(()=>{var i,s
const n=this,o=n.settings.mode,r=m(e)
if((!r||-1===n.items.indexOf(r)||("single"===o&&n.close(),"single"!==o&&n.settings.duplicates))&&r&&n.options.hasOwnProperty(r)&&("single"===o&&n.clear(t),"multi"!==o||!n.isFull())){if(i=n._render("item",n.options[r]),n.control.contains(i)&&(i=i.cloneNode(!0)),s=n.isFull(),n.items.splice(n.caretPos,0,r),n.insertAtCaret(i),n.isSetup){let e=n.selectable()
if(!n.isPending&&n.settings.hideSelected){let e=n.getOption(r),t=n.getAdjacent(e,1)
t&&n.setActiveOption(t)}n.isPending||n.refreshOptions(n.isFocused&&"single"!==o),!e.length||n.isFull()?n.close():n.isPending||n.positionDropdown(),n.trigger("item_add",r,i),n.isPending||n.updateOriginalInput({silent:t})}(!n.isPending||!s&&n.isFull())&&n.refreshState()}}))}removeItem(e,t){var i,s
const n=this,o=m(e)
if(!o)return
const r=n.getItem(o)
r&&-1!==(i=n.items.indexOf(o))&&(r.remove(),r.classList.contains("active")&&(s=n.activeItems.indexOf(r),n.activeItems.splice(s,1),k(r,"active")),n.items.splice(i,1),n.lastQuery=null,!n.settings.persist&&n.userOptions.hasOwnProperty(o)&&n.removeOption(o,t),i<n.caretPos&&n.setCaret(n.caretPos-1),n.updateOriginalInput({silent:t}),n.refreshState(),n.positionDropdown(),n.trigger("item_remove",o,r))}createItem(e=null,t=!0,i=(()=>{})){var s,n=this,o=n.caretPos
if(e=e||n.inputValue(),!n.canCreate(e))return i(),!1
n.lock()
var r=!1,l=e=>{if(n.unlock(),!e||"object"!=typeof e)return i()
var s=m(e[n.settings.valueField])
if("string"!=typeof s)return i()
n.setTextboxValue(),n.addOption(e),n.setCaret(o),n.addItem(s),n.refreshOptions(t&&"single"!==n.settings.mode),i(e),r=!0}
return s="function"==typeof n.settings.create?n.settings.create.call(this,e,l):{[n.settings.labelField]:e,[n.settings.valueField]:e},r||l(s),!0}refreshItems(){var e=this
e.lastQuery=null,e.isSetup&&e.addItems(e.items),e.updateOriginalInput(),e.refreshState()}refreshState(){var e=this
e.refreshValidityState()
var t=e.isFull(),i=e.isLocked
e.wrapper.classList.toggle("rtl",e.rtl)
var s,n=e.control.classList
n.toggle("focus",e.isFocused),n.toggle("disabled",e.isDisabled),n.toggle("required",e.isRequired),n.toggle("invalid",e.isInvalid),n.toggle("locked",i),n.toggle("full",t),n.toggle("not-full",!t),n.toggle("input-active",e.isFocused&&!e.isInputHidden),n.toggle("dropdown-active",e.isOpen),n.toggle("has-options",(s=e.options,0===Object.keys(s).length)),n.toggle("has-items",e.items.length>0)}refreshValidityState(){var e=this
if(e.input.checkValidity){this.isRequired&&(e.input.required=!0)
var t=!e.input.checkValidity()
e.isInvalid=t,e.control_input.required=t,this.isRequired&&(e.input.required=!t)}}isFull(){return null!==this.settings.maxItems&&this.items.length>=this.settings.maxItems}updateOriginalInput(e={}){const t=this
var i,s,n,o
if(t.is_select_tag){function r(e,i,s){return e||(e=A('<option value="'+O(i)+'">'+O(s)+"</option>")),e.selected=!0,V(e,{selected:"true"}),t.input.prepend(e),e}for(t.input.querySelectorAll("option[selected]").forEach((e=>{const i=e;-1==t.items.indexOf(i.value)&&(V(i,{selected:null}),i.selected=!1)})),i=t.items.length-1;i>=0;i--)s=t.items[i],o=(n=t.options[s])[t.settings.labelField]||"",n.$option=r(n.$option,s,o)
0!=t.items.length||"single"!=t.settings.mode||t.isRequired||r(t.input.querySelector('option[value=""]'),"","")}else t.input.value=t.getValue()
t.isSetup&&(e.silent||t.trigger("change",t.getValue()))}open(){var e=this
e.isLocked||e.isOpen||"multi"===e.settings.mode&&e.isFull()||(e.isOpen=!0,V(e.control_input,{"aria-expanded":"true"}),e.refreshState(),F(e.dropdown,{visibility:"hidden",display:"block"}),e.positionDropdown(),F(e.dropdown,{visibility:"visible",display:"block"}),e.focus(),e.trigger("dropdown_open",e.dropdown))}close(e=!0){var t=this,i=t.isOpen
e&&(t.setTextboxValue(),"single"===t.settings.mode&&t.items.length&&(t.hideInput(),t.tab_key||t.blur())),t.isOpen=!1,V(t.control_input,{"aria-expanded":"false"}),F(t.dropdown,{display:"none"}),t.settings.hideSelected&&t.clearActiveOption(),t.refreshState(),i&&t.trigger("dropdown_close",t.dropdown)}positionDropdown(){if("body"===this.settings.dropdownParent){var e=this.control,t=e.getBoundingClientRect(),i=e.offsetHeight+t.top+window.scrollY,s=t.left+window.scrollX
F(this.dropdown,{width:t.width+"px",top:i+"px",left:s+"px"})}}clear(e){var t=this
if(t.items.length){var i=t.controlChildren()
for(const e of i)e.remove()
t.items=[],t.lastQuery=null,t.setCaret(0),t.clearActiveItems(),t.updateOriginalInput({silent:e}),t.refreshState(),t.showInput(),t.trigger("clear")}}insertAtCaret(e){var t=this,i=Math.min(t.caretPos,t.items.length),s=t.buffer||t.control
0===i?s.insertBefore(e,s.firstChild):s.insertBefore(e,s.children[i]),t.setCaret(i+1)}deleteSelection(e){var t,i,s,n,o,r=this
if(t=e&&8===e.keyCode?-1:1,i={start:(o=r.control_input).selectionStart||0,length:(o.selectionEnd||0)-(o.selectionStart||0)},s=[],r.activeItems.length){n=q(T(r.activeItems,t)),t>0&&n++
for(const e of r.activeItems)s.push(e.dataset.value)}else(r.isFocused||"single"===r.settings.mode)&&r.items.length&&(t<0&&0===i.start&&0===i.length?s.push(r.items[r.caretPos-1]):t>0&&i.start===r.inputValue().length&&s.push(r.items[r.caretPos]))
if(!s.length||"function"==typeof r.settings.onDelete&&!1===r.settings.onDelete.call(r,s,e))return!1
for(w(e,!0),void 0!==n&&r.setCaret(n);s.length;)r.removeItem(s.pop())
return r.showInput(),r.positionDropdown(),r.refreshOptions(!1),!0}advanceSelection(e,t){var i,s,n,o=this
o.rtl&&(e*=-1),o.inputValue().length||(C(f,t)||C("shiftKey",t)?(n=(s=o.getLastActive(e))?s.classList.contains("active")?o.getAdjacent(s,e,"item"):s:e>0?o.control_input.nextElementSibling:o.control_input.previousElementSibling)&&(n.classList.contains("active")&&o.removeActiveItem(s),o.setActiveItemClass(n)):o.isFocused&&!o.activeItems.length?o.setCaret(o.caretPos+e):(s=o.getLastActive(e))&&(i=q(s),o.setCaret(e>0?i+1:i),o.setActiveItem()))}getLastActive(e){let t=this.control.querySelector(".last-active")
if(t)return t
var i=this.control.querySelectorAll(".active")
return i?T(i,e):void 0}setCaret(e){var t=this
"single"===t.settings.mode||t.settings.controlInput?e=t.items.length:(e=Math.max(0,Math.min(t.items.length,e)))==t.caretPos||t.isPending||t.controlChildren().forEach(((i,s)=>{s<e?t.control_input.insertAdjacentElement("beforebegin",i):t.control.appendChild(i)})),t.caretPos=e}controlChildren(){return Array.from(this.control.getElementsByClassName(this.settings.itemClass))}lock(){this.close(),this.isLocked=!0,this.refreshState()}unlock(){this.isLocked=!1,this.refreshState()}disable(){var e=this
e.input.disabled=!0,e.control_input.disabled=!0,e.control_input.tabIndex=-1,e.isDisabled=!0,e.lock()}enable(){var e=this
e.input.disabled=!1,e.control_input.disabled=!1,e.control_input.tabIndex=e.tabIndex,e.isDisabled=!1,e.unlock()}destroy(){var e=this,t=e.revertSettings
e.trigger("destroy"),e.off(),e.wrapper.remove(),e.dropdown.remove(),e.input.innerHTML=t.innerHTML,e.input.tabIndex=t.tabIndex,k(e.input,"tomselected"),V(e.input,{hidden:null}),e.input.required=this.isRequired,e._destroy(),delete e.input.tomselect}render(e,t){return"function"!=typeof this.settings.render[e]?null:this._render(e,t)}_render(e,t){var i,s
const n=this
return("option"===e||"item"===e)&&(i=y(t[n.settings.valueField]),s=n.rendered(e,i))?s:(s=n.settings.render[e].call(this,t,O))?(s=A(s),"option"===e||"option_create"===e?t[n.settings.disabledField]?V(s,{"aria-disabled":"true"}):V(s,{"data-selectable":""}):"optgroup"===e&&(V(s,{"data-group":t.group[n.settings.optgroupValueField]}),t.group[n.settings.disabledField]&&V(s,{"data-disabled":""})),"option"!==e&&"item"!==e||(V(s,{"data-value":i}),"item"===e?x(s,n.settings.itemClass):(x(s,n.settings.optionClass),V(s,{role:"option",id:t.$id})),n.renderCache[e][i]=s),s):s}rendered(e,t){return this.renderCache[e].hasOwnProperty(t)?this.renderCache[e][t]:null}clearCache(e){var t=this
for(let e in t.options){const i=t.getOption(e)
i&&i.remove()}void 0===e?t.renderCache={item:{},option:{}}:t.renderCache[e]={}}canCreate(e){return this.settings.create&&e.length>0&&this.settings.createFilter.call(this,e)}hook(e,t,i){var s=this,n=s[t]
s[t]=function(){var t,o
return"after"===e&&(t=n.apply(s,arguments)),o=i.apply(s,arguments),"instead"===e?o:("before"===e&&(t=n.apply(s,arguments)),t)}}}return N.define("dropdown_input",(function(){var e=this,t=e.settings.controlInput||'<input type="text" autocomplete="off" class="dropdown-input" />'
t=A(t),e.settings.placeholder&&V(t,{placeholder:e.settings.placeholder}),e.settings.controlInput=t,e.settings.shouldOpen=!0,e.hook("after","setup",(()=>{V(e.wrapper,{tabindex:e.input.disabled?"-1":""+e.tabIndex}),I(e.wrapper,"keypress",(t=>{if(!e.control.contains(t.target)&&!e.dropdown.contains(t.target))switch(t.keyCode){case 13:return void e.onClick()}}))
let i=A('<div class="dropdown-input-wrap">')
i.appendChild(t),e.dropdown.insertBefore(i,e.dropdown.firstChild)}))})),N.define("no_backspace_delete",(function(){var e=this,t=e.deleteSelection
this.hook("instead","deleteSelection",(function(){return!!e.activeItems.length&&t.apply(e,arguments)}))})),N.define("remove_button",(function(e){e=Object.assign({label:"×",title:"Remove",className:"remove",append:!0},e)
var t=this
if(e.append){var i='<a href="javascript:void(0)" class="'+e.className+'" tabindex="-1" title="'+O(e.title)+'">'+e.label+"</a>"
t.hook("after","setupTemplates",(()=>{var e=t.settings.render.item
t.settings.render.item=function(){var s=A(e.apply(t,arguments)),n=A(i)
return s.appendChild(n),I(n,"mousedown",(e=>{w(e,!0)})),I(n,"click",(e=>{if(w(e,!0),!t.isLocked){var i=s.dataset.value
t.removeItem(i),t.refreshOptions(!1)}})),s}}))}})),N.define("restore_on_backspace",(function(e){var t=this
e.text=e.text||function(e){return e[t.settings.labelField]},t.on("item_remove",(function(i){if(""===t.control_input.value.trim()){var s=t.options[i]
s&&t.setTextboxValue(e.text.call(t,s))}}))})),N}))
var tomSelect=function(e,t){return new TomSelect(e,t)}
//# sourceMappingURL=tom-select.popular.min.js.map
|
import { l as log } from './index-44c0fa28.js';
class Leaf {
constructor(trie) {
this.children = [];
this.parent = trie;
}
delete(value) {
const index = this.children.indexOf(value);
if (index === -1)
return false;
this.children = this.children.slice(0, index).concat(this.children.slice(index + 1));
if (this.children.length === 0) {
this.parent.delete(this);
}
return true;
}
add(value) {
this.children.push(value);
return this;
}
}
class RadixTrie {
constructor(trie) {
this.parent = null;
this.children = {};
this.parent = trie || null;
}
get(edge) {
return this.children[edge];
}
insert(edges) {
let currentNode = this;
for (let i = 0; i < edges.length; i += 1) {
const edge = edges[i];
let nextNode = currentNode.get(edge);
if (i === edges.length - 1) {
if (nextNode instanceof RadixTrie) {
currentNode.delete(nextNode);
nextNode = null;
}
if (!nextNode) {
nextNode = new Leaf(currentNode);
currentNode.children[edge] = nextNode;
}
return nextNode;
}
else {
if (nextNode instanceof Leaf)
nextNode = null;
if (!nextNode) {
nextNode = new RadixTrie(currentNode);
currentNode.children[edge] = nextNode;
}
}
currentNode = nextNode;
}
return currentNode;
}
delete(node) {
for (const edge in this.children) {
const currentNode = this.children[edge];
if (currentNode === node) {
const success = delete this.children[edge];
if (Object.keys(this.children).length === 0 && this.parent) {
this.parent.delete(this);
}
return success;
}
}
return false;
}
}
function isFormField(element) {
if (!(element instanceof HTMLElement)) {
return false;
}
const name = element.nodeName.toLowerCase();
const type = (element.getAttribute('type') || '').toLowerCase();
return (name === 'select' ||
name === 'textarea' ||
(name === 'input' && type !== 'submit' && type !== 'reset' && type !== 'checkbox' && type !== 'radio') ||
element.isContentEditable);
}
function fireDeterminedAction(el) {
if (isFormField(el)) {
el.focus();
}
else {
el.click();
}
}
function expandHotkeyToEdges(hotkey) {
return hotkey.split(',').map(edge => edge.split(' '));
}
function hotkey(event) {
return `${event.ctrlKey ? 'Control+' : ''}${event.altKey ? 'Alt+' : ''}${event.metaKey ? 'Meta+' : ''}${event.shiftKey && event.key.toUpperCase() !== event.key ? 'Shift+' : ''}${event.key}`;
}
const hotkeyRadixTrie = new RadixTrie();
const elementsLeaves = new WeakMap();
let currentTriePosition = hotkeyRadixTrie;
let resetTriePositionTimer = null;
function resetTriePosition() {
resetTriePositionTimer = null;
currentTriePosition = hotkeyRadixTrie;
}
function keyDownHandler(event) {
if (event.defaultPrevented)
return;
if (event.target instanceof Node && isFormField(event.target))
return;
if (resetTriePositionTimer != null) {
window.clearTimeout(resetTriePositionTimer);
}
resetTriePositionTimer = window.setTimeout(resetTriePosition, 1500);
const newTriePosition = currentTriePosition.get(hotkey(event));
if (!newTriePosition) {
resetTriePosition();
return;
}
currentTriePosition = newTriePosition;
if (newTriePosition instanceof Leaf) {
fireDeterminedAction(newTriePosition.children[newTriePosition.children.length - 1]);
event.preventDefault();
resetTriePosition();
return;
}
}
function install(element, hotkey) {
if (Object.keys(hotkeyRadixTrie.children).length === 0) {
document.addEventListener('keydown', keyDownHandler);
}
const hotkeys = expandHotkeyToEdges(hotkey || element.getAttribute('data-hotkey') || '');
const leaves = hotkeys.map(h => hotkeyRadixTrie.insert(h).add(element));
elementsLeaves.set(element, leaves);
}
function uninstall(element) {
const leaves = elementsLeaves.get(element);
if (leaves && leaves.length) {
for (const leaf of leaves) {
leaf && leaf.delete(element);
}
}
if (Object.keys(hotkeyRadixTrie.children).length === 0) {
document.removeEventListener('keydown', keyDownHandler);
}
}
function HotKeyBehavior(host, options) {
let installed = false;
return {
connected() {
setTimeout(() => {
const el = host.nuRef || host;
el.dataset.hotkey = (options || '').trim();
install(el);
log('hotkey installed', el, el.dataset.hotkey);
installed = true;
}, 300);
},
disconnected() {
if (installed) {
uninstall(host);
log('hotkey uninstalled', host, options);
installed = false;
}
},
};
}
export default HotKeyBehavior;
|
/*!
* Name : Just Another Parallax [Jarallax]
* Version : 1.12.2
* Author : nK <https://nkdev.info>
* GitHub : https://github.com/nk-o/jarallax
*/
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 10);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */,
/* 1 */,
/* 2 */
/***/ (function(module, exports) {
module.exports = function (callback) {
if (document.readyState === 'complete' || document.readyState === 'interactive') {
// Already ready or interactive, execute callback
callback.call();
} else if (document.attachEvent) {
// Old browsers
document.attachEvent('onreadystatechange', function () {
if (document.readyState === 'interactive') callback.call();
});
} else if (document.addEventListener) {
// Modern browsers
document.addEventListener('DOMContentLoaded', callback);
}
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof global !== "undefined") {
win = global;
} else if (typeof self !== "undefined") {
win = self;
} else {
win = {};
}
module.exports = win;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(4)))
/***/ }),
/* 4 */
/***/ (function(module, exports) {
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var g; // This works in non-strict mode
g = function () {
return this;
}();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === "object") g = window;
} // g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 5 */,
/* 6 */,
/* 7 */,
/* 8 */,
/* 9 */,
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(11);
/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var lite_ready__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var lite_ready__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lite_ready__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var global__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var global__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(global__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _jarallax_esm__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(12);
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
// no conflict
var oldPlugin = global__WEBPACK_IMPORTED_MODULE_1__["window"].jarallax;
global__WEBPACK_IMPORTED_MODULE_1__["window"].jarallax = _jarallax_esm__WEBPACK_IMPORTED_MODULE_2__["default"];
global__WEBPACK_IMPORTED_MODULE_1__["window"].jarallax.noConflict = function () {
global__WEBPACK_IMPORTED_MODULE_1__["window"].jarallax = oldPlugin;
return this;
}; // jQuery support
if ('undefined' !== typeof global__WEBPACK_IMPORTED_MODULE_1__["jQuery"]) {
var jQueryPlugin = function jQueryPlugin() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
Array.prototype.unshift.call(args, this);
var res = _jarallax_esm__WEBPACK_IMPORTED_MODULE_2__["default"].apply(global__WEBPACK_IMPORTED_MODULE_1__["window"], args);
return 'object' !== _typeof(res) ? res : this;
};
jQueryPlugin.constructor = _jarallax_esm__WEBPACK_IMPORTED_MODULE_2__["default"].constructor; // no conflict
var oldJqPlugin = global__WEBPACK_IMPORTED_MODULE_1__["jQuery"].fn.jarallax;
global__WEBPACK_IMPORTED_MODULE_1__["jQuery"].fn.jarallax = jQueryPlugin;
global__WEBPACK_IMPORTED_MODULE_1__["jQuery"].fn.jarallax.noConflict = function () {
global__WEBPACK_IMPORTED_MODULE_1__["jQuery"].fn.jarallax = oldJqPlugin;
return this;
};
} // data-jarallax initialization
lite_ready__WEBPACK_IMPORTED_MODULE_0___default()(function () {
Object(_jarallax_esm__WEBPACK_IMPORTED_MODULE_2__["default"])(document.querySelectorAll('[data-jarallax]'));
});
/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var lite_ready__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var lite_ready__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lite_ready__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var global__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var global__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(global__WEBPACK_IMPORTED_MODULE_1__);
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var navigator = global__WEBPACK_IMPORTED_MODULE_1__["window"].navigator;
var isIE = -1 < navigator.userAgent.indexOf('MSIE ') || -1 < navigator.userAgent.indexOf('Trident/') || -1 < navigator.userAgent.indexOf('Edge/');
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
var supportTransform = function () {
var prefixes = 'transform WebkitTransform MozTransform'.split(' ');
var div = document.createElement('div');
for (var i = 0; i < prefixes.length; i += 1) {
if (div && div.style[prefixes[i]] !== undefined) {
return prefixes[i];
}
}
return false;
}();
var $deviceHelper;
/**
* The most popular mobile browsers changes height after page scroll and this generates image jumping.
* We can fix it using this workaround with vh units.
*/
function getDeviceHeight() {
if (!$deviceHelper && document.body) {
$deviceHelper = document.createElement('div');
$deviceHelper.style.cssText = 'position: fixed; top: -9999px; left: 0; height: 100vh; width: 0;';
document.body.appendChild($deviceHelper);
}
return ($deviceHelper ? $deviceHelper.clientHeight : 0) || global__WEBPACK_IMPORTED_MODULE_1__["window"].innerHeight || document.documentElement.clientHeight;
} // Window height data
var wndH;
function updateWndVars() {
if (isMobile) {
wndH = getDeviceHeight();
} else {
wndH = global__WEBPACK_IMPORTED_MODULE_1__["window"].innerHeight || document.documentElement.clientHeight;
}
}
updateWndVars();
global__WEBPACK_IMPORTED_MODULE_1__["window"].addEventListener('resize', updateWndVars);
global__WEBPACK_IMPORTED_MODULE_1__["window"].addEventListener('orientationchange', updateWndVars);
global__WEBPACK_IMPORTED_MODULE_1__["window"].addEventListener('load', updateWndVars);
lite_ready__WEBPACK_IMPORTED_MODULE_0___default()(function () {
updateWndVars({
type: 'dom-loaded'
});
}); // list with all jarallax instances
// need to render all in one scroll/resize event
var jarallaxList = []; // get all parents of the element.
function getParents(elem) {
var parents = [];
while (null !== elem.parentElement) {
elem = elem.parentElement;
if (1 === elem.nodeType) {
parents.push(elem);
}
}
return parents;
}
function updateParallax() {
if (!jarallaxList.length) {
return;
}
jarallaxList.forEach(function (data, k) {
var instance = data.instance,
oldData = data.oldData;
var clientRect = instance.$item.getBoundingClientRect();
var newData = {
width: clientRect.width,
height: clientRect.height,
top: clientRect.top,
bottom: clientRect.bottom,
wndW: global__WEBPACK_IMPORTED_MODULE_1__["window"].innerWidth,
wndH: wndH
};
var isResized = !oldData || oldData.wndW !== newData.wndW || oldData.wndH !== newData.wndH || oldData.width !== newData.width || oldData.height !== newData.height;
var isScrolled = isResized || !oldData || oldData.top !== newData.top || oldData.bottom !== newData.bottom;
jarallaxList[k].oldData = newData;
if (isResized) {
instance.onResize();
}
if (isScrolled) {
instance.onScroll();
}
});
global__WEBPACK_IMPORTED_MODULE_1__["window"].requestAnimationFrame(updateParallax);
}
var instanceID = 0; // Jarallax class
var Jarallax = /*#__PURE__*/function () {
function Jarallax(item, userOptions) {
_classCallCheck(this, Jarallax);
var self = this;
self.instanceID = instanceID;
instanceID += 1;
self.$item = item;
self.defaults = {
type: 'scroll',
// type of parallax: scroll, scale, opacity, scale-opacity, scroll-opacity
speed: 0.5,
// supported value from -1 to 2
imgSrc: null,
imgElement: '.jarallax-img',
imgSize: 'cover',
imgPosition: '50% 50%',
imgRepeat: 'no-repeat',
// supported only for background, not for <img> tag
keepImg: false,
// keep <img> tag in it's default place
elementInViewport: null,
zIndex: -100,
disableParallax: false,
disableVideo: false,
// video
videoSrc: null,
videoStartTime: 0,
videoEndTime: 0,
videoVolume: 0,
videoLoop: true,
videoPlayOnlyVisible: true,
videoLazyLoading: true,
// events
onScroll: null,
// function(calculations) {}
onInit: null,
// function() {}
onDestroy: null,
// function() {}
onCoverImage: null // function() {}
}; // prepare data-options
var dataOptions = self.$item.dataset || {};
var pureDataOptions = {};
Object.keys(dataOptions).forEach(function (key) {
var loweCaseOption = key.substr(0, 1).toLowerCase() + key.substr(1);
if (loweCaseOption && 'undefined' !== typeof self.defaults[loweCaseOption]) {
pureDataOptions[loweCaseOption] = dataOptions[key];
}
});
self.options = self.extend({}, self.defaults, pureDataOptions, userOptions);
self.pureOptions = self.extend({}, self.options); // prepare 'true' and 'false' strings to boolean
Object.keys(self.options).forEach(function (key) {
if ('true' === self.options[key]) {
self.options[key] = true;
} else if ('false' === self.options[key]) {
self.options[key] = false;
}
}); // fix speed option [-1.0, 2.0]
self.options.speed = Math.min(2, Math.max(-1, parseFloat(self.options.speed))); // prepare disableParallax callback
if ('string' === typeof self.options.disableParallax) {
self.options.disableParallax = new RegExp(self.options.disableParallax);
}
if (self.options.disableParallax instanceof RegExp) {
var disableParallaxRegexp = self.options.disableParallax;
self.options.disableParallax = function () {
return disableParallaxRegexp.test(navigator.userAgent);
};
}
if ('function' !== typeof self.options.disableParallax) {
self.options.disableParallax = function () {
return false;
};
} // prepare disableVideo callback
if ('string' === typeof self.options.disableVideo) {
self.options.disableVideo = new RegExp(self.options.disableVideo);
}
if (self.options.disableVideo instanceof RegExp) {
var disableVideoRegexp = self.options.disableVideo;
self.options.disableVideo = function () {
return disableVideoRegexp.test(navigator.userAgent);
};
}
if ('function' !== typeof self.options.disableVideo) {
self.options.disableVideo = function () {
return false;
};
} // custom element to check if parallax in viewport
var elementInVP = self.options.elementInViewport; // get first item from array
if (elementInVP && 'object' === _typeof(elementInVP) && 'undefined' !== typeof elementInVP.length) {
var _elementInVP = elementInVP;
var _elementInVP2 = _slicedToArray(_elementInVP, 1);
elementInVP = _elementInVP2[0];
} // check if dom element
if (!(elementInVP instanceof Element)) {
elementInVP = null;
}
self.options.elementInViewport = elementInVP;
self.image = {
src: self.options.imgSrc || null,
$container: null,
useImgTag: false,
// position fixed is needed for the most of browsers because absolute position have glitches
// on MacOS with smooth scroll there is a huge lags with absolute position - https://github.com/nk-o/jarallax/issues/75
// on mobile devices better scrolled with absolute position
position: /iPad|iPhone|iPod|Android/.test(navigator.userAgent) ? 'absolute' : 'fixed'
};
if (self.initImg() && self.canInitParallax()) {
self.init();
}
} // add styles to element
// eslint-disable-next-line class-methods-use-this
_createClass(Jarallax, [{
key: "css",
value: function css(el, styles) {
if ('string' === typeof styles) {
return global__WEBPACK_IMPORTED_MODULE_1__["window"].getComputedStyle(el).getPropertyValue(styles);
} // add transform property with vendor prefix
if (styles.transform && supportTransform) {
styles[supportTransform] = styles.transform;
}
Object.keys(styles).forEach(function (key) {
el.style[key] = styles[key];
});
return el;
} // Extend like jQuery.extend
// eslint-disable-next-line class-methods-use-this
}, {
key: "extend",
value: function extend(out) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
out = out || {};
Object.keys(args).forEach(function (i) {
if (!args[i]) {
return;
}
Object.keys(args[i]).forEach(function (key) {
out[key] = args[i][key];
});
});
return out;
} // get window size and scroll position. Useful for extensions
// eslint-disable-next-line class-methods-use-this
}, {
key: "getWindowData",
value: function getWindowData() {
return {
width: global__WEBPACK_IMPORTED_MODULE_1__["window"].innerWidth || document.documentElement.clientWidth,
height: wndH,
y: document.documentElement.scrollTop
};
} // Jarallax functions
}, {
key: "initImg",
value: function initImg() {
var self = this; // find image element
var $imgElement = self.options.imgElement;
if ($imgElement && 'string' === typeof $imgElement) {
$imgElement = self.$item.querySelector($imgElement);
} // check if dom element
if (!($imgElement instanceof Element)) {
if (self.options.imgSrc) {
$imgElement = new Image();
$imgElement.src = self.options.imgSrc;
} else {
$imgElement = null;
}
}
if ($imgElement) {
if (self.options.keepImg) {
self.image.$item = $imgElement.cloneNode(true);
} else {
self.image.$item = $imgElement;
self.image.$itemParent = $imgElement.parentNode;
}
self.image.useImgTag = true;
} // true if there is img tag
if (self.image.$item) {
return true;
} // get image src
if (null === self.image.src) {
self.image.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
self.image.bgImage = self.css(self.$item, 'background-image');
}
return !(!self.image.bgImage || 'none' === self.image.bgImage);
}
}, {
key: "canInitParallax",
value: function canInitParallax() {
return supportTransform && !this.options.disableParallax();
}
}, {
key: "init",
value: function init() {
var self = this;
var containerStyles = {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
overflow: 'hidden'
};
var imageStyles = {
pointerEvents: 'none',
transformStyle: 'preserve-3d',
backfaceVisibility: 'hidden',
willChange: 'transform,opacity'
};
if (!self.options.keepImg) {
// save default user styles
var curStyle = self.$item.getAttribute('style');
if (curStyle) {
self.$item.setAttribute('data-jarallax-original-styles', curStyle);
}
if (self.image.useImgTag) {
var curImgStyle = self.image.$item.getAttribute('style');
if (curImgStyle) {
self.image.$item.setAttribute('data-jarallax-original-styles', curImgStyle);
}
}
} // set relative position and z-index to the parent
if ('static' === self.css(self.$item, 'position')) {
self.css(self.$item, {
position: 'relative'
});
}
if ('auto' === self.css(self.$item, 'z-index')) {
self.css(self.$item, {
zIndex: 0
});
} // container for parallax image
self.image.$container = document.createElement('div');
self.css(self.image.$container, containerStyles);
self.css(self.image.$container, {
'z-index': self.options.zIndex
}); // fix for IE https://github.com/nk-o/jarallax/issues/110
if (isIE) {
self.css(self.image.$container, {
opacity: 0.9999
});
}
self.image.$container.setAttribute('id', "jarallax-container-".concat(self.instanceID));
self.$item.appendChild(self.image.$container); // use img tag
if (self.image.useImgTag) {
imageStyles = self.extend({
'object-fit': self.options.imgSize,
'object-position': self.options.imgPosition,
// support for plugin https://github.com/bfred-it/object-fit-images
'font-family': "object-fit: ".concat(self.options.imgSize, "; object-position: ").concat(self.options.imgPosition, ";"),
'max-width': 'none'
}, containerStyles, imageStyles); // use div with background image
} else {
self.image.$item = document.createElement('div');
if (self.image.src) {
imageStyles = self.extend({
'background-position': self.options.imgPosition,
'background-size': self.options.imgSize,
'background-repeat': self.options.imgRepeat,
'background-image': self.image.bgImage || "url(\"".concat(self.image.src, "\")")
}, containerStyles, imageStyles);
}
}
if ('opacity' === self.options.type || 'scale' === self.options.type || 'scale-opacity' === self.options.type || 1 === self.options.speed) {
self.image.position = 'absolute';
} // 1. Check if one of parents have transform style (without this check, scroll transform will be inverted if used parallax with position fixed)
// discussion - https://github.com/nk-o/jarallax/issues/9
// 2. Check if parents have overflow scroll
if ('fixed' === self.image.position) {
var $parents = getParents(self.$item).filter(function (el) {
var styles = global__WEBPACK_IMPORTED_MODULE_1__["window"].getComputedStyle(el);
var parentTransform = styles['-webkit-transform'] || styles['-moz-transform'] || styles.transform;
var overflowRegex = /(auto|scroll)/;
return parentTransform && 'none' !== parentTransform || overflowRegex.test(styles.overflow + styles['overflow-y'] + styles['overflow-x']);
});
self.image.position = $parents.length ? 'absolute' : 'fixed';
} // add position to parallax block
imageStyles.position = self.image.position; // insert parallax image
self.css(self.image.$item, imageStyles);
self.image.$container.appendChild(self.image.$item); // set initial position and size
self.onResize();
self.onScroll(true); // call onInit event
if (self.options.onInit) {
self.options.onInit.call(self);
} // remove default user background
if ('none' !== self.css(self.$item, 'background-image')) {
self.css(self.$item, {
'background-image': 'none'
});
}
self.addToParallaxList();
} // add to parallax instances list
}, {
key: "addToParallaxList",
value: function addToParallaxList() {
jarallaxList.push({
instance: this
});
if (1 === jarallaxList.length) {
global__WEBPACK_IMPORTED_MODULE_1__["window"].requestAnimationFrame(updateParallax);
}
} // remove from parallax instances list
}, {
key: "removeFromParallaxList",
value: function removeFromParallaxList() {
var self = this;
jarallaxList.forEach(function (data, key) {
if (data.instance.instanceID === self.instanceID) {
jarallaxList.splice(key, 1);
}
});
}
}, {
key: "destroy",
value: function destroy() {
var self = this;
self.removeFromParallaxList(); // return styles on container as before jarallax init
var originalStylesTag = self.$item.getAttribute('data-jarallax-original-styles');
self.$item.removeAttribute('data-jarallax-original-styles'); // null occurs if there is no style tag before jarallax init
if (!originalStylesTag) {
self.$item.removeAttribute('style');
} else {
self.$item.setAttribute('style', originalStylesTag);
}
if (self.image.useImgTag) {
// return styles on img tag as before jarallax init
var originalStylesImgTag = self.image.$item.getAttribute('data-jarallax-original-styles');
self.image.$item.removeAttribute('data-jarallax-original-styles'); // null occurs if there is no style tag before jarallax init
if (!originalStylesImgTag) {
self.image.$item.removeAttribute('style');
} else {
self.image.$item.setAttribute('style', originalStylesTag);
} // move img tag to its default position
if (self.image.$itemParent) {
self.image.$itemParent.appendChild(self.image.$item);
}
} // remove additional dom elements
if (self.$clipStyles) {
self.$clipStyles.parentNode.removeChild(self.$clipStyles);
}
if (self.image.$container) {
self.image.$container.parentNode.removeChild(self.image.$container);
} // call onDestroy event
if (self.options.onDestroy) {
self.options.onDestroy.call(self);
} // delete jarallax from item
delete self.$item.jarallax;
} // it will remove some image overlapping
// overlapping occur due to an image position fixed inside absolute position element
}, {
key: "clipContainer",
value: function clipContainer() {
// needed only when background in fixed position
if ('fixed' !== this.image.position) {
return;
}
var self = this;
var rect = self.image.$container.getBoundingClientRect();
var width = rect.width,
height = rect.height;
if (!self.$clipStyles) {
self.$clipStyles = document.createElement('style');
self.$clipStyles.setAttribute('type', 'text/css');
self.$clipStyles.setAttribute('id', "jarallax-clip-".concat(self.instanceID));
var head = document.head || document.getElementsByTagName('head')[0];
head.appendChild(self.$clipStyles);
}
var styles = "#jarallax-container-".concat(self.instanceID, " {\n clip: rect(0 ").concat(width, "px ").concat(height, "px 0);\n clip: rect(0, ").concat(width, "px, ").concat(height, "px, 0);\n }"); // add clip styles inline (this method need for support IE8 and less browsers)
if (self.$clipStyles.styleSheet) {
self.$clipStyles.styleSheet.cssText = styles;
} else {
self.$clipStyles.innerHTML = styles;
}
}
}, {
key: "coverImage",
value: function coverImage() {
var self = this;
var rect = self.image.$container.getBoundingClientRect();
var contH = rect.height;
var speed = self.options.speed;
var isScroll = 'scroll' === self.options.type || 'scroll-opacity' === self.options.type;
var scrollDist = 0;
var resultH = contH;
var resultMT = 0; // scroll parallax
if (isScroll) {
// scroll distance and height for image
if (0 > speed) {
scrollDist = speed * Math.max(contH, wndH);
if (wndH < contH) {
scrollDist -= speed * (contH - wndH);
}
} else {
scrollDist = speed * (contH + wndH);
} // size for scroll parallax
if (1 < speed) {
resultH = Math.abs(scrollDist - wndH);
} else if (0 > speed) {
resultH = scrollDist / speed + Math.abs(scrollDist);
} else {
resultH += (wndH - contH) * (1 - speed);
}
scrollDist /= 2;
} // store scroll distance
self.parallaxScrollDistance = scrollDist; // vertical center
if (isScroll) {
resultMT = (wndH - resultH) / 2;
} else {
resultMT = (contH - resultH) / 2;
} // apply result to item
self.css(self.image.$item, {
height: "".concat(resultH, "px"),
marginTop: "".concat(resultMT, "px"),
left: 'fixed' === self.image.position ? "".concat(rect.left, "px") : '0',
width: "".concat(rect.width, "px")
}); // call onCoverImage event
if (self.options.onCoverImage) {
self.options.onCoverImage.call(self);
} // return some useful data. Used in the video cover function
return {
image: {
height: resultH,
marginTop: resultMT
},
container: rect
};
}
}, {
key: "isVisible",
value: function isVisible() {
return this.isElementInViewport || false;
}
}, {
key: "onScroll",
value: function onScroll(force) {
var self = this;
var rect = self.$item.getBoundingClientRect();
var contT = rect.top;
var contH = rect.height;
var styles = {}; // check if in viewport
var viewportRect = rect;
if (self.options.elementInViewport) {
viewportRect = self.options.elementInViewport.getBoundingClientRect();
}
self.isElementInViewport = 0 <= viewportRect.bottom && 0 <= viewportRect.right && viewportRect.top <= wndH && viewportRect.left <= global__WEBPACK_IMPORTED_MODULE_1__["window"].innerWidth; // stop calculations if item is not in viewport
if (force ? false : !self.isElementInViewport) {
return;
} // calculate parallax helping variables
var beforeTop = Math.max(0, contT);
var beforeTopEnd = Math.max(0, contH + contT);
var afterTop = Math.max(0, -contT);
var beforeBottom = Math.max(0, contT + contH - wndH);
var beforeBottomEnd = Math.max(0, contH - (contT + contH - wndH));
var afterBottom = Math.max(0, -contT + wndH - contH);
var fromViewportCenter = 1 - 2 * ((wndH - contT) / (wndH + contH)); // calculate on how percent of section is visible
var visiblePercent = 1;
if (contH < wndH) {
visiblePercent = 1 - (afterTop || beforeBottom) / contH;
} else if (beforeTopEnd <= wndH) {
visiblePercent = beforeTopEnd / wndH;
} else if (beforeBottomEnd <= wndH) {
visiblePercent = beforeBottomEnd / wndH;
} // opacity
if ('opacity' === self.options.type || 'scale-opacity' === self.options.type || 'scroll-opacity' === self.options.type) {
styles.transform = 'translate3d(0,0,0)';
styles.opacity = visiblePercent;
} // scale
if ('scale' === self.options.type || 'scale-opacity' === self.options.type) {
var scale = 1;
if (0 > self.options.speed) {
scale -= self.options.speed * visiblePercent;
} else {
scale += self.options.speed * (1 - visiblePercent);
}
styles.transform = "scale(".concat(scale, ") translate3d(0,0,0)");
} // scroll
if ('scroll' === self.options.type || 'scroll-opacity' === self.options.type) {
var positionY = self.parallaxScrollDistance * fromViewportCenter; // fix if parallax block in absolute position
if ('absolute' === self.image.position) {
positionY -= contT;
}
styles.transform = "translate3d(0,".concat(positionY, "px,0)");
}
self.css(self.image.$item, styles); // call onScroll event
if (self.options.onScroll) {
self.options.onScroll.call(self, {
section: rect,
beforeTop: beforeTop,
beforeTopEnd: beforeTopEnd,
afterTop: afterTop,
beforeBottom: beforeBottom,
beforeBottomEnd: beforeBottomEnd,
afterBottom: afterBottom,
visiblePercent: visiblePercent,
fromViewportCenter: fromViewportCenter
});
}
}
}, {
key: "onResize",
value: function onResize() {
this.coverImage();
this.clipContainer();
}
}]);
return Jarallax;
}(); // global definition
var plugin = function plugin(items, options) {
// check for dom element
// thanks: http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
if ('object' === (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) ? items instanceof HTMLElement : items && 'object' === _typeof(items) && null !== items && 1 === items.nodeType && 'string' === typeof items.nodeName) {
items = [items];
}
var len = items.length;
var k = 0;
var ret;
for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
for (k; k < len; k += 1) {
if ('object' === _typeof(options) || 'undefined' === typeof options) {
if (!items[k].jarallax) {
items[k].jarallax = new Jarallax(items[k], options);
}
} else if (items[k].jarallax) {
// eslint-disable-next-line prefer-spread
ret = items[k].jarallax[options].apply(items[k].jarallax, args);
}
if ('undefined' !== typeof ret) {
return ret;
}
}
return items;
};
plugin.constructor = Jarallax;
/* harmony default export */ __webpack_exports__["default"] = (plugin);
/***/ })
/******/ ]); |
const test = require('tape')
const sinon = require('sinon')
const helpers = require('../test/helpers')
const bindFunc = helpers.bindFunc
const isFunction = require('../core/isFunction')
const unit = require('../core/_unit')
const constant = x => () => x
const identity = x => x
const swap = require('./swap')
test('swap pointfree', t => {
const m = bindFunc(swap)
const f = { swap: unit }
t.ok(isFunction(swap), 'is a function')
const err = /swap: Function required for first two arguments/
t.throws(m(undefined, unit, f), err, 'throws if first arg is undefined')
t.throws(m(null, unit, f), err, 'throws if first arg is null')
t.throws(m(0, unit, f), err, 'throws if first arg is a falsey number')
t.throws(m(1, unit, f), err, 'throws if first arg is a truthy number')
t.throws(m('', unit, f), err, 'throws if first arg is a falsey string')
t.throws(m('string', unit, f), err, 'throws if first arg is a truthy string')
t.throws(m(false, unit, f), err, 'throws if first arg is false')
t.throws(m(true, unit, f), err, 'throws if first arg is true')
t.throws(m([], unit, f), err, 'throws if first arg is an array')
t.throws(m({}, unit, f), err, 'throws if first arg is an object')
t.throws(m(unit, undefined, f), err, 'throws if second arg is undefined')
t.throws(m(unit, null, f), err, 'throws if second arg is null')
t.throws(m(unit, 0, f), err, 'throws if second arg is a falsey number')
t.throws(m(unit, 1, f), err, 'throws if second arg is a truthy number')
t.throws(m(unit, '', f), err, 'throws if second arg is a falsey string')
t.throws(m(unit, 'string', f), err, 'throws if second arg is a truthy string')
t.throws(m(unit, false, f), err, 'throws if second arg is false')
t.throws(m(unit, true, f), err, 'throws if second arg is true')
t.throws(m(unit, [], f), err, 'throws if second arg is an array')
t.throws(m(unit, {}, f), err, 'throws if second arg is an object')
const last = /swap: Async, Either, Pair or Result required for third arguments/
t.throws(m(unit, unit, undefined), last, 'throws if third arg is undefined')
t.throws(m(unit, unit, null), last, 'throws if third arg is null')
t.throws(m(unit, unit, 0), last, 'throws if third arg is a falsey number')
t.throws(m(unit, unit, 1), last, 'throws if third arg is a truthy number')
t.throws(m(unit, unit, ''), last, 'throws if third arg is a falsey string')
t.throws(m(unit, unit, 'string'), last, 'throws if third arg is a truthy string')
t.throws(m(unit, unit, false), last, 'throws if third arg is false')
t.throws(m(unit, unit, true), last, 'throws if third arg is true')
t.throws(m(unit, unit, {}), last, 'throws if third arg is an object')
t.end()
})
test('swap sum type', t => {
const x = 'result'
const m = { swap: sinon.spy(constant(x)) }
const result = swap(identity, identity, m)
t.ok(m.swap.calledWith(identity, identity), 'calls swap on sum types, passing the functions')
t.equal(result, x, 'returns the result of the call to swap')
t.end()
})
|
var Initializer = require("../initializer");
var _ = require('lodash');
Initializer.add('startup', 'stex.db', ['stex.config', 'stex.logging', 'stex.newrelic'], function(stex) {
var Knex = require('knex');
var config = stex.conf.get("db");
config.connection = _.extend(config.connection, {
stringifyObjects: true
});
stex.db = Knex.initialize(config);
stex.db.on("query", function(query) {
log.info("query", {
sql: query.sql
})
});
global.db = stex.db;
});
Initializer.add('shutdown', 'stex.db', function(stex) {
if(stex.db) {
stex.db.client.pool.destroy();
}
}); |
/**
*
* Rotate device.
*
* <example>
:rotate.js
client.rotate(114, 198, 5, 3, 220, 2);
* </example>
*
* @type appium
*
*/
module.exports = function rotate(x, y, duration, radius, rotation, touchCount) {
/*!
* make sure that callback contains chainit callback
*/
var callback = arguments[arguments.length - 1];
var data = {
x: x,
y: y,
duration: duration,
radius: radius,
rotation: rotation,
touchCount: touchCount
};
var requestOptions = {
path: '/session/:sessionId/appium/device/rotate',
method: 'POST'
};
this.requestHandler.create(requestOptions, data, callback);
}; |
'use strict';
var globalFs = require('fs');
var path = require('path');
var setTimeout = require('timers').setTimeout;
var clearTimeout = require('timers').clearTimeout;
var uuid = require('uuid');
var PROBE_INTERVAL = 25;
var CPU_TICK_MS = 10;
var IS_NULL_CHAR_REGEX = /\u0000/g;
module.exports = ProcWatcher;
function ProcWatcher(flamer, pid, options) {
var self = this;
this.type = 'proc-watcher';
this.flamer = flamer;
this.pid = pid;
this.cmdline = (options && options.cmdline) || '';
this.fs = (options && options.fs) || globalFs;
this.probeInterval = PROBE_INTERVAL;
this.minCyclesDuration = flamer.minCyclesDuration || 250;
this.minTimeSlices = Math.floor(
this.minCyclesDuration / PROBE_INTERVAL
) + 2;
this.filePath = path.join(
'/proc', String(this.pid), 'stat'
);
this.nextProbe = 0;
this.timer = null;
this.seenFirstRunning = false;
this.timeSlices = [];
this.windowReported = false;
this.destroyed = false;
this.paused = false;
this.boundOnProbe = boundOnProbe;
this.boundOnFile = boundOnFile;
function boundOnProbe() {
self.onProbe();
}
function boundOnFile(err, str) {
self.onFile(err, str);
}
}
ProcWatcher.prototype.watch = function watch() {
var now = Date.now();
this.nextProbe = now + this.probeInterval;
this.timer = setTimeout(this.boundOnProbe, this.probeInterval);
};
ProcWatcher.prototype.destroy = function destroy() {
this.destroyed = true;
this.reset();
if (this.timer) {
clearTimeout(this.timer);
}
};
ProcWatcher.prototype.pause = function pause() {
this.paused = true;
if (this.timer) {
clearTimeout(this.timer);
}
};
ProcWatcher.prototype.resume = function resume() {
this.paused = false;
this.watch();
};
ProcWatcher.prototype.onProbe = function onProbe() {
this.timer = null;
this.nextProbe = this.nextProbe + this.probeInterval;
globalFs.readFile(this.filePath, 'utf8', this.boundOnFile);
};
ProcWatcher.prototype.onFile = function onFile(err, text) {
if (err) {
this.flamer.handleError(err, this);
this.reset();
this.scheduleNextProbe();
return;
}
var segments = text.split(' ');
var procInfo = new ProcInfo(
this.pid,
segments[2], // state %c
segments[13], // utime %lu
segments[14], // stime %lu
segments[38], // processor %d
segments[42] // guest_time %lu
);
this.handleProcInfo(procInfo);
this.scheduleNextProbe();
};
ProcWatcher.prototype.handleProcInfo = function handleProcInfo(procInfo) {
if (procInfo.state !== 'R') {
this.reset();
return;
}
this.timeSlices.push(procInfo);
if (!this.windowReported && this.timeSlices.length > this.minTimeSlices) {
var windowInfo = this.getTimeWindowInfo();
if (windowInfo.cpuPercentage >= 95) {
this.windowReported = true;
if (!this.paused) {
this.flamer.onCPUHot(windowInfo);
}
}
}
};
ProcWatcher.prototype.getTimeWindowInfo = function getTimeWindowInfo() {
// Remove first & last slice as they are "partial data";
var slices = this.timeSlices;
var elapsedTime = slices[slices.length - 2].timestamp - slices[1].timestamp;
var cpuTicks = slices[slices.length - 2].ttime - slices[1].ttime;
return new TimeWindowInfo(
slices[0].pid, elapsedTime, cpuTicks, this.cmdline
);
};
ProcWatcher.prototype.reset = function reset() {
this.timeSlices.length = 0;
this.windowReported = false;
};
ProcWatcher.prototype.scheduleNextProbe = function scheduleNextProbe() {
if (this.destroyed || this.paused || this.timer) {
return;
}
var now = Date.now();
this.timer = setTimeout(this.boundOnProbe, this.nextProbe - now);
};
function ProcInfo(pid, state, utime, stime, processor, guestTime) {
this.timestamp = Date.now();
this.pid = pid;
this.state = state;
this.utime = parseInt(utime, 10);
this.stime = parseInt(stime, 10);
this.ttime = this.utime + this.stime;
this.processor = parseInt(processor, 10);
this.guestTime = parseInt(guestTime, 10);
}
function TimeWindowInfo(pid, elapsedTime, cpuTicks, cmdline) {
this.timestamp = Date.now();
this.pid = pid;
this.elapsedTime = elapsedTime;
this.cpuTicks = cpuTicks;
this.cmdline = cmdline.replace(IS_NULL_CHAR_REGEX, '');
this.uuid = uuid();
this.filePath = null;
this.cpuPercentage = Math.floor(
100 * (cpuTicks * CPU_TICK_MS) / elapsedTime
);
}
|
var clc = require('cli-color');
module.exports = {
run: function( next ){
global.desktopNotify('Starting the example module', 'Enjoy', 10);
global.log.general( clc.bold.red('Hi there!') + 'This is the custom module in action!' );
global.log.general('');
global.log.general('This is the quilk.json object found for this module:');
global.log.general(global.current_module);
global.log.general('');
global.log.general('This is all the li args passed:');
global.log.general(global.cliArgs);
global.log.general('');
global.log.general('This is the quilk.json object found for this module:');
global.log.general(global.current_module);
global.log.general('');
global.log.general('This is the developer object found:');
global.log.general( global.quilkConf.developers[ global.cliArgs.developer ] );
global.log.general('');
global.log.general(clc.bold.blue.blink('Scoll up to see all of the console output from the example module'));
//run the next module
next();
},
help : function(){
var helps = [
'This is the help function form the example custom module :)',
'Have a look at the module code.. just open /quilk_modules/example_module.js and take a look.. it is not as complex as you might think :)',
'All the functional code goes in the run function and the help for other people goes int the help function.. thats it :)',
];
var clc = require('cli-color');
global.log.general( clc.bold.underline('example_module module help - start') );
for( var key in helps ){
global.log.general( helps[key] );
}
global.log.general( clc.bold.underline('example_module module help - end') );
}
}; |
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Sector = mongoose.model('Sector');
/**
* Globals
*/
var user, sector;
/**
* Unit tests
*/
describe('Sector Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
sector = new Sector({
name: 'Sector Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return sector.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
sector.name = '';
return sector.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Sector.remove().exec();
User.remove().exec();
done();
});
}); |
/* http://prismjs.com/download.html?themes=prism-okaidia&languages=clike */
var self = (typeof window !== 'undefined') ? window : {};
/**
* Prism: Lightweight, robust, elegant syntax highlighting
* MIT license http://www.opensource.org/licenses/mit-license.php/
* @author Lea Verou http://lea.verou.me
*/
var Prism = (function(){
// Private helper vars
var lang = /\blang(?:uage)?-(?!\*)(\w+)\b/i;
var _ = self.Prism = {
util: {
type: function (o) {
return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1];
},
// Deep clone a language definition (e.g. to extend it)
clone: function (o) {
var type = _.util.type(o);
switch (type) {
case 'Object':
var clone = {};
for (var key in o) {
if (o.hasOwnProperty(key)) {
clone[key] = _.util.clone(o[key]);
}
}
return clone;
case 'Array':
return o.slice();
}
return o;
}
},
languages: {
extend: function (id, redef) {
var lang = _.util.clone(_.languages[id]);
for (var key in redef) {
lang[key] = redef[key];
}
return lang;
},
// Insert a token before another token in a language literal
insertBefore: function (inside, before, insert, root) {
root = root || _.languages;
var grammar = root[inside];
var ret = {};
for (var token in grammar) {
if (grammar.hasOwnProperty(token)) {
if (token == before) {
for (var newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
ret[newToken] = insert[newToken];
}
}
}
ret[token] = grammar[token];
}
}
return root[inside] = ret;
},
// Traverse a language definition with Depth First Search
DFS: function(o, callback) {
for (var i in o) {
callback.call(o, i, o[i]);
if (_.util.type(o) === 'Object') {
_.languages.DFS(o[i], callback);
}
}
}
},
highlightAll: function(async, callback) {
var elements = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');
for (var i=0, element; element = elements[i++];) {
_.highlightElement(element, async === true, callback);
}
},
highlightElement: function(element, async, callback) {
// Find language
var language, grammar, parent = element;
while (parent && !lang.test(parent.className)) {
parent = parent.parentNode;
}
if (parent) {
language = (parent.className.match(lang) || [,''])[1];
grammar = _.languages[language];
}
if (!grammar) {
return;
}
// Set language on the element, if not present
element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
// Set language on the parent, for styling
parent = element.parentNode;
if (/pre/i.test(parent.nodeName)) {
parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
}
var code = element.textContent;
if(!code) {
return;
}
code = code.replace(/&/g, '&').replace(/</g, '<').replace(/\u00a0/g, ' ');
var env = {
element: element,
language: language,
grammar: grammar,
code: code
};
_.hooks.run('before-highlight', env);
if (async && self.Worker) {
var worker = new Worker(_.filename);
worker.onmessage = function(evt) {
env.highlightedCode = Token.stringify(JSON.parse(evt.data), language);
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
callback && callback.call(env.element);
_.hooks.run('after-highlight', env);
};
worker.postMessage(JSON.stringify({
language: env.language,
code: env.code
}));
}
else {
env.highlightedCode = _.highlight(env.code, env.grammar, env.language)
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
callback && callback.call(element);
_.hooks.run('after-highlight', env);
}
},
highlight: function (text, grammar, language) {
return Token.stringify(_.tokenize(text, grammar), language);
},
tokenize: function(text, grammar, language) {
var Token = _.Token;
var strarr = [text];
var rest = grammar.rest;
if (rest) {
for (var token in rest) {
grammar[token] = rest[token];
}
delete grammar.rest;
}
tokenloop: for (var token in grammar) {
if(!grammar.hasOwnProperty(token) || !grammar[token]) {
continue;
}
var pattern = grammar[token],
inside = pattern.inside,
lookbehind = !!pattern.lookbehind,
lookbehindLength = 0;
pattern = pattern.pattern || pattern;
for (var i=0; i<strarr.length; i++) { // Don’t cache length as it changes during the loop
var str = strarr[i];
if (strarr.length > text.length) {
// Something went terribly wrong, ABORT, ABORT!
break tokenloop;
}
if (str instanceof Token) {
continue;
}
pattern.lastIndex = 0;
var match = pattern.exec(str);
if (match) {
if(lookbehind) {
lookbehindLength = match[1].length;
}
var from = match.index - 1 + lookbehindLength,
match = match[0].slice(lookbehindLength),
len = match.length,
to = from + len,
before = str.slice(0, from + 1),
after = str.slice(to + 1);
var args = [i, 1];
if (before) {
args.push(before);
}
var wrapped = new Token(token, inside? _.tokenize(match, inside) : match);
args.push(wrapped);
if (after) {
args.push(after);
}
Array.prototype.splice.apply(strarr, args);
}
}
}
return strarr;
},
hooks: {
all: {},
add: function (name, callback) {
var hooks = _.hooks.all;
hooks[name] = hooks[name] || [];
hooks[name].push(callback);
},
run: function (name, env) {
var callbacks = _.hooks.all[name];
if (!callbacks || !callbacks.length) {
return;
}
for (var i=0, callback; callback = callbacks[i++];) {
callback(env);
}
}
}
};
var Token = _.Token = function(type, content) {
this.type = type;
this.content = content;
};
Token.stringify = function(o, language, parent) {
if (typeof o == 'string') {
return o;
}
if (Object.prototype.toString.call(o) == '[object Array]') {
return o.map(function(element) {
return Token.stringify(element, language, o);
}).join('');
}
var env = {
type: o.type,
content: Token.stringify(o.content, language, parent),
tag: 'span',
classes: ['token', o.type],
attributes: {},
language: language,
parent: parent
};
if (env.type == 'comment') {
env.attributes['spellcheck'] = 'true';
}
_.hooks.run('wrap', env);
var attributes = '';
for (var name in env.attributes) {
attributes += name + '="' + (env.attributes[name] || '') + '"';
}
return '<' + env.tag + ' class="' + env.classes.join(' ') + '" ' + attributes + '>' + env.content + '</' + env.tag + '>';
};
if (!self.document) {
if (!self.addEventListener) {
// in Node.js
return self.Prism;
}
// In worker
self.addEventListener('message', function(evt) {
var message = JSON.parse(evt.data),
lang = message.language,
code = message.code;
self.postMessage(JSON.stringify(_.tokenize(code, _.languages[lang])));
self.close();
}, false);
return self.Prism;
}
// Get current script and highlight
var script = document.getElementsByTagName('script');
script = script[script.length - 1];
if (script) {
_.filename = script.src;
if (document.addEventListener && !script.hasAttribute('data-manual')) {
//document.addEventListener('DOMContentLoaded', _.highlightAll);
}
}
return self.Prism;
})();
if (typeof module !== 'undefined' && module.exports) {
module.exports = Prism;
};
Prism.languages.lambda = {
'comment': {
pattern: /(^|[^\\])(\/\*[\w\W]*?\*\/|(^|[^:])\/\/.*?(\r?\n|$))/g,
lookbehind: true
},
'string': /("|')(\\?.)*?\1/g,
'class-name': {
pattern: /((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/ig,
lookbehind: true,
inside: {
punctuation: /(\.|\\)/
}
},
'keyword': /\b(attack|dbl|succ|get|inc|dec|copy)\b/g,
'Icombinator': /\b(I)\b/g,
'Kcombinator': /\b(K)\b/g,
'Scombinator': /\b(S)\b/g,
'lambda': /\u03BB/g,
'function': {
pattern: /[a-z0-9_]+\(/ig,
inside: {
punctuation: /\(/
}
},
'number': /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,
'operator': /[-+]{1,2}|!|<=?|>=?|={1,3}|(&){1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,
'ignore': /&(lt|gt|amp);/gi,
'punctuation': /[{}[\];(),.:]/g
};
;
|
version https://git-lfs.github.com/spec/v1
oid sha256:f9e62fdf000383e5de776e9ff67c71b4da0e64b3e92b6093d77f05b59402b948
size 738
|
version https://git-lfs.github.com/spec/v1
oid sha256:1ec168495fcf5d3f686f6696b8fb45111dbf62d4956248fe3e1ebf6f3a257a98
size 771
|
version https://git-lfs.github.com/spec/v1
oid sha256:eecc753022aa9191fb353565afbea840bcf90f4a834d28cac48b89c987adfe0b
size 846
|
describe('console plugin', function() {
var logMessageButton = element(by.id('log-message'));
var warningMessageButton = element(by.id('simulate-warning'));
var deleteMessageButton = element(by.id('simulate-error'));
it('should not fail on log and debug messages', function() {
browser.get('/');
logMessageButton.click();
});
it('should not fail on warning message', function() {
browser.get('/');
warningMessageButton.click();
});
it('should not fail on error message', function() {
browser.get('/');
deleteMessageButton.click();
});
});
|
import _cloneRegExp from './internal/_cloneRegExp';
import _curry2 from './internal/_curry2';
import _isRegExp from './internal/_isRegExp';
import toString from './toString';
/**
* Determines whether a given string matches a given regular expression.
*
* @func
* @memberOf R
* @since v0.12.0
* @category String
* @sig RegExp -> String -> Boolean
* @param {RegExp} pattern
* @param {String} str
* @return {Boolean}
* @see R.match
* @example
*
* R.test(/^x/, 'xyz'); //=> true
* R.test(/^y/, 'xyz'); //=> false
*/
var test = _curry2(function test(pattern, str) {
if (!_isRegExp(pattern)) {
throw new TypeError('‘test’ requires a value of type RegExp as its first argument; received ' + toString(pattern));
}
return _cloneRegExp(pattern).test(str);
});
export default test;
|
var Rtern = {}; // define the Rtern namespace
(function($) {
var last_event_id = 0;
var access_id = 0;
var ajax_url = "";
var ajax_type = "json";
Rtern.init = function(url,type) {
ajax_url = url;
ajax_type = type;
setTimeout(function() {
poll(); // start the long poller
},1000);
};
Rtern.setAccessID = function(id) {
access_id = id;
};
var poll = function() {
var post_data = { evt_id: last_event_id, access_id: access_id };
$.ajax({ url: 'http://mj.localhost:8124', type: 'GET', data: post_data, dataType: 'jsonp', success: function(new_event) {
console.log(new_event);
$(document).trigger( 'rtern.'+new_event.type, new_event.evt );
poll();
} });
};
})(jQuery);
|
angular.module('mongolabResourceHttp', []).factory('$mongolabResourceHttp', ['MONGOLAB_CONFIG', '$http', function (MONGOLAB_CONFIG, $http) {
function MmongolabResourceFactory(collectionName) {
var config = angular.extend({
BASE_URL : 'https://api.mongolab.com/api/1/databases/'
}, MONGOLAB_CONFIG);
var dbUrl = config.BASE_URL + config.DB_NAME;
var collectionUrl = dbUrl + '/collections/' + collectionName;
var defaultParams = {apiKey:config.API_KEY};
var resourceRespTransform = function(data) {
return new Resource(data);
};
var resourcesArrayRespTransform = function(data) {
var result = [];
for (var i = 0; i < data.length; i++) {
result.push(new Resource(data[i]));
}
return result;
};
var promiseThen = function (httpPromise, successcb, errorcb, fransformFn) {
return httpPromise.then(function (response) {
var result = fransformFn(response.data);
(successcb || angular.noop)(result, response.status, response.headers, response.config);
return result;
}, function (response) {
(errorcb || angular.noop)(undefined, response.status, response.headers, response.config);
return undefined;
});
};
var preparyQueryParam = function(queryJson) {
return angular.isObject(queryJson)&&!angular.equals(queryJson,{}) ? {q:JSON.stringify(queryJson)} : {};
};
var Resource = function (data) {
angular.extend(this, data);
};
Resource.query = function (queryJson, options, successcb, errorcb) {
var prepareOptions = function(options) {
var optionsMapping = {sort: 's', limit: 'l', fields: 'f', skip: 'sk'};
var optionsTranslated = {};
if (options && !angular.equals(options, {})) {
angular.forEach(optionsMapping, function (targetOption, sourceOption) {
if (angular.isDefined(options[sourceOption])) {
if (angular.isObject(options[sourceOption])) {
optionsTranslated[targetOption] = JSON.stringify(options[sourceOption]);
} else {
optionsTranslated[targetOption] = options[sourceOption];
}
}
});
}
return optionsTranslated;
};
if(angular.isFunction(options)) { errorcb = successcb; successcb = options; options = {}; }
var requestParams = angular.extend({}, defaultParams, preparyQueryParam(queryJson), prepareOptions(options));
var httpPromise = $http.get(collectionUrl, {params:requestParams});
return promiseThen(httpPromise, successcb, errorcb, resourcesArrayRespTransform);
};
Resource.all = function (options, successcb, errorcb) {
if(angular.isFunction(options)) { errorcb = successcb; successcb = options; options = {}; }
return Resource.query({}, options, successcb, errorcb);
};
Resource.count = function (queryJson, successcb, errorcb) {
var httpPromise = $http.get(collectionUrl, {
params: angular.extend({}, defaultParams, preparyQueryParam(queryJson), {c: true})
});
return promiseThen(httpPromise, successcb, errorcb, function(data){
return data;
});
};
Resource.distinct = function (field, queryJson, successcb, errorcb) {
var httpPromise = $http.post(dbUrl + '/runCommand', angular.extend({}, queryJson || {}, {
distinct:collectionName,
key:field}), {
params:defaultParams
});
return promiseThen(httpPromise, successcb, errorcb, function(data){
return data.values;
});
};
Resource.getById = function (id, successcb, errorcb) {
var httpPromise = $http.get(collectionUrl + '/' + id, {params:defaultParams});
return promiseThen(httpPromise, successcb, errorcb, resourceRespTransform);
};
Resource.getByObjectIds = function (ids, successcb, errorcb) {
var qin = [];
angular.forEach(ids, function (id) {
qin.push({$oid:id});
});
return Resource.query({_id:{$in:qin}}, successcb, errorcb);
};
//instance methods
Resource.prototype.$id = function () {
if (this._id && this._id.$oid) {
return this._id.$oid;
} else if (this._id) {
return this._id;
}
};
Resource.prototype.$save = function (successcb, errorcb) {
var httpPromise = $http.post(collectionUrl, this, {params:defaultParams});
return promiseThen(httpPromise, successcb, errorcb, resourceRespTransform);
};
Resource.prototype.$update = function (successcb, errorcb) {
var httpPromise = $http.put(collectionUrl + "/" + this.$id(), angular.extend({}, this, {_id:undefined}), {params:defaultParams});
return promiseThen(httpPromise, successcb, errorcb, resourceRespTransform);
};
Resource.prototype.$remove = function (successcb, errorcb) {
var httpPromise = $http['delete'](collectionUrl + "/" + this.$id(), {params:defaultParams});
return promiseThen(httpPromise, successcb, errorcb, resourceRespTransform);
};
Resource.prototype.$saveOrUpdate = function (savecb, updatecb, errorSavecb, errorUpdatecb) {
if (this.$id()) {
return this.$update(updatecb, errorUpdatecb);
} else {
return this.$save(savecb, errorSavecb);
}
};
return Resource;
}
return MmongolabResourceFactory;
}]);
|
/**
* @ngdoc filter
* @name join
* @kind function
*
* @description
* join a collection by a provided delimiter (space by default)
*/
angular.module('a8m.join', [])
.filter('join', function () {
return function (input, delimiter) {
if (isUndefined(input) || !isArray(input)) {
return input;
}
if (isUndefined(delimiter)) {
delimiter = ' ';
}
return input.join(delimiter);
};
})
;
|
import {Buffer} from 'node:buffer';
import {promises as fs} from 'node:fs';
import path from 'node:path';
import test from '@ava/test';
import {cwd, fixture} from '../helpers/exec.js';
import {withTemporaryFixture} from '../helpers/with-temporary-fixture.js';
test.serial('With invalid .snap file and --update-snapshots, skipped snaps are omitted', async t => {
await withTemporaryFixture(cwd('invalid-snapfile'), async cwd => {
const env = {AVA_FORCE_CI: 'not-ci'};
const snapPath = path.join(cwd, 'test.js.snap');
const reportPath = path.join(cwd, 'test.js.md');
await fs.writeFile(snapPath, Buffer.of(0x0A, 0x00, 0x00));
const result = await fixture(['--update-snapshots'], {cwd, env});
const report = await fs.readFile(reportPath, 'utf8');
t.snapshot(report, 'snapshot report');
t.snapshot(result.stats.passed, 'passed tests');
t.snapshot(result.stats.failed, 'failed tests');
t.snapshot(result.stats.skipped, 'skipped tests');
});
});
|
/* eslint-env jest */
import { mapDataReducer } from '../../src/reducers/mapDataReducer'
import ACTION_EVENTS from '../../src/actions/index'
import { fromJS, Map, OrderedSet } from 'immutable'
import metaData from '../../public/districts/pa/metaData.json'
const { MAP_SWITCH_LAYER, META_DATA } = ACTION_EVENTS
// State from the configure store
const initState = {
geoFiles: fromJS({}),
data: {},
addr: null
}
describe('Reducer::mapData', function () {
it('Switches branch', () => {
const filledState = Object.assign(
{},
initState,
{ geoFiles: fromJS(metaData.geoFiles) }
)
const geoFiles = filledState.geoFiles
const yearsFederal = OrderedSet(Object.keys(geoFiles.get('federal')))
const yearsHouse = OrderedSet(Object.keys(geoFiles.get('lower')))
const yearsSenate = OrderedSet(Object.keys(geoFiles.get('upper')))
const action = { type: MAP_SWITCH_LAYER, years: yearsFederal }
const stateChangeOne = mapDataReducer(initState, action)
// Assert the new and old state aren't the same instance
expect(stateChangeOne === filledState).toBeFalsy()
action.years = yearsHouse
const stateChangeTwo = mapDataReducer(stateChangeOne, action)
expect(stateChangeTwo === stateChangeOne).toBeFalsy()
action.years = yearsSenate
const stateChangeThree = mapDataReducer(stateChangeTwo, action)
expect(stateChangeTwo === stateChangeThree).toBeFalsy()
})
it('Loading MetaData', () => {
const { geoFiles } = metaData
const action = { type: META_DATA, geoFiles: fromJS(geoFiles) }
const newState = mapDataReducer(initState, action)
// Assert the new and old state aren't the same instance
expect(newState === initState).toBeFalsy()
// Test might be useless, consider cutting
expect(newState.geoFiles).toBeInstanceOf(Map)
// TODO: Test years
})
})
|
import storage from './oembed-storage';
import regexes from './regexes';
import providers from './providers';
function getContent(regex) {
return regex[0].match(regexes.content)[0].match(/['|"].*/)[0].slice(1);
}
function decodeText(text) {
return text
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/ /g, ' ')
.replace(/&#(x?)(\d+);/g, (m, p1, p2) => String.fromCharCode(((p1 === 'x') ? parseInt(p2, 16) : p2)));
}
function parseHTML(body) {
const bodyString = body.replace(/(\r\n|\n|\r)/g, '');
const res = bodyString.match(regexes.link);
if (res !== null) {
return res[0].match(regexes.matchHTTP)[0].replace(/&/g, '&');
}
const oembed = {
type: 'rich'
};
const props = [ 'title', 'description' ];
for (let i = 0; i < props.length; i++) {
const match = bodyString.match(regexes.propertyRegex(props[i]));
if (match && match.length) {
oembed[props[i]] = decodeText(getContent(match));
}
}
const propsWithType = [ 'width', 'height' ];
for (let i = 0; i < propsWithType.length; i++) {
const types = [ 'video', 'image' ];
for (let j = 0; j < types.length; j++) {
const match = bodyString.match(regexes.propertyRegex(propsWithType[i], types[j]));
if (match && match.length) {
oembed[propsWithType[i]] = parseInt(getContent(match), 10);
}
}
}
const imageUrl = bodyString.match(regexes.image);
if (imageUrl) {
oembed.thumbnail_url = getContent(imageUrl);
}
if (!oembed.title) {
const match = bodyString.match(regexes.title);
if (match && match.length) {
const title = title[0].match(/[>][^<]*/);
if (title && title.length) {
oembed.title = decodeText(title[0].slice(1));
}
}
}
if (!oembed.description) {
const match = bodyString.match(regexes.description);
if (match && match.length) {
const description = description[0].match(regexes.content)[0].match(/['|"][^'|^"]*/);
if (description && description.length) {
oembed.description = decodeText(description[0].slice(1));
}
}
}
if (Object.keys(oembed).length) {
return oembed;
} else {
throw new Error('No oEmbed data found');
}
}
async function embed(url) {
const res = await fetch(url);
const body = await res.text();
const parsed = parseHTML(body);
let data;
if (typeof parsed === 'string') {
data = await (await fetch(parsed)).json();
} else {
data = parsed;
}
if (data) {
storage.set(url, data);
return data;
}
}
async function get(url) {
if (typeof url !== 'string') {
throw new TypeError('URL must be a string');
}
if (!/^https?:\/\//i.test(url)) {
throw new Error("URL must start with 'http://' or 'https://'");
}
const json = await storage.get(url);
if (typeof json !== 'undefined') {
return json;
}
for (let i = 0, l = providers.length; i < l; i++) {
const provider = providers[i];
if (provider[0].test(url)) {
const endpoint = provider[1] + '?format=json&maxheight=240&url=' + encodeURIComponent(url);
const data = await (await fetch(endpoint)).json();
storage.set(url, data);
return data;
}
}
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.onload = function() {
if (request.status === 200) {
const contentType = request.getResponseHeader('content-type');
if (contentType && contentType.indexOf('image') > -1) {
resolve({
type: 'image',
thumbnail_url: url
});
} else if (contentType && contentType.indexOf('text/html') > -1) {
resolve(embed(url));
} else {
reject(new Error('Unknown content-type: ' + contentType));
}
} else {
reject(new Error(request.responseText + ': ' + request.responseCode));
}
};
request.open('HEAD', url, true);
request.send();
});
}
export default {
get
};
|
var insert = require('./insert')
insert('cursor.size', [{
hello: 'world1'
}, {
hello: 'world2'
}, {
hello: 'world3'
}, {
hello: 'world4'
}], function (db, t, done) {
db.a.find().skip(1).size(function (err, thesize) {
t.error(err)
t.equal(thesize, 3)
db.a.find().limit(2).size(function (err, theothersize) {
t.error(err)
t.equal(theothersize, 2)
done()
})
})
})
|
/*
下拉框相关的功能
- 支持搜索
- 可编辑文本
*/
$(function () {
// 按关键词搜索
var advanceSelectSelector = "[data-toggle='advance-select']";
var advanceSelectKeywordSelector = advanceSelectSelector + " .keyword";
$(document).on("keyup", advanceSelectKeywordSelector, function () {
var $this = $(this);
var keyword = $this.val().trim().toLowerCase();
$this.closest(advanceSelectSelector).find("option").each(function () {
var $option = $(this);
($option.text().toLowerCase().indexOf(keyword) >= 0) ? $option.show() : $option.hide();
})
});
// 选择项改变后应用到按钮或文本框
var advanceSelectFieldSelector = advanceSelectSelector + " select";
$(document).on("change", advanceSelectFieldSelector, function () {
var $this = $(this);
var selectedText = $this.find("option:selected").text().trim();
var $advanceSelect = $this.closest(advanceSelectSelector);
$advanceSelect.find(".option-text").text(selectedText);
$advanceSelect.find(".option-text-editable").val(selectedText).change();
});
// 页面载入时初始化高级下拉框
var setup = function ($elements) {
$elements.each(function () {
var $this = $(this);
var size = $this.closest(advanceSelectSelector).data("select-size") || 5;
$this.attr("size", "5");
$this.change();
});
};
setup($(advanceSelectFieldSelector));
$(document).on("dynamicLoaded", function (e, contents) {
setup($(contents).find(advanceSelectFieldSelector));
});
});
|
module.exports = {
description: 'ensures bundle imports are deconflicted (#659)'
};
|
/**
* Example of how to use bind arrays and Collections using cb-repeat
* attributes with ConboJS
*
* @author Neil Rackett
*/
conbo('example', function(undefined)
{
'use strict'
var ns = this;
ns.MyContext = conbo.Context.extend
({
initialize: function()
{
this.mapSingleton('myList', new conbo.List({source:[{name:'Tom'}, {name:'Dick'}, {name:'Sally'}]}));
}
});
/**
* Very simple item renderer example that simply applies a CSS class
* (the cb-repeat item renderer parameter is optional)
*/
ns.MyItemRenderer = conbo.ItemRenderer.extend
({
declarations: function()
{
this.className = 'item-renderer';
},
initialize: function()
{
this.bindAll();
},
removeMe: function()
{
this.list.splice(this.index, 1);
},
toString: function()
{
return 'MyItemRenderer';
},
});
ns.AnotherItemRenderer = ns.MyItemRenderer.extend
({
declarations: function()
{
this.className = 'another-item-renderer';
},
toString: function()
{
return 'AnotherItemRenderer';
},
});
ns.MyApp = conbo.Application.extend
({
namespace: ns,
contextClass: ns.MyContext,
myList: undefined,
boysNames:
[
'Aaron','Abdul','Abdullah','Abel','Abraham','Abram','Abriel','Ace','Adam','Adan'
,'Ade','Aden','Adnan','Adrian','Ahmad','Ahmed','Aidan','Aiden','Ainsley','Al'
,'Alain','Alan','Alastair','Albert','Alberto','Albie','Alden','Aldo','Alec','Alejandro'
,'Alen','Alesandro','Alex','Alexander','Alexis','Alfie','Alfonso','Alfred','Alfredo','Ali'
,'Alistair','Allan','Allen','Alonzo','Aloysius','Alphonso','Alton','Alvin','Amari','Amir'
,'Amit','Amos','Andre','Andreas','Andres','Andrew','Andy','Angel','Angelo','Angus'
,'Anthony','Anton','Antonio','Antony','Aran','Archer','Archie','Ari','Arjun','Arlo'
,'Arman','Armando','Arnold','Arrie','Art','Arthur','Arturo','Arwin','Asa','Asad'
,'Ash','Asher','Ashley','Ashton','Asif','Aspen','Aston','Atticus','Aubrey','Audwin'
,'August','Augustus','Austen','Austin','Avery','Axel','Ayaan','Ayden','Bailey','Barclay'
,'Barnaby','Barney','Barry','Bart','Bartholomew','Basil','Bay','Baylor','Beau','Beck'
,'Beckett','Bellamy','Ben','Benedict','Benjamin','Benji','Benjy','Bennett','Bennie','Benny'
,'Benson','Bentley','Bernard','Bernardo','Bernie','Bert','Bertie','Bertram','Bevan','Bill'
,'Billy','Bladen','Blain','Blaine','Blair','Blaise','Blake','Blaze','Bob','Bobby'
,'Bodie','Boris','Boston','Boyd','Brad','Braden','Bradford','Bradley','Bradwin','Brady'
],
girlsNames:
[
'Kalea','Kaleigh','Kali','Kalia','Kamala','Kamryn','Kara','Karen','Kari','Karin'
,'Karina','Karissa','Karla','Karlee','Karly','Karolina','Karyn','Kasey','Kassandra','Kassidy'
,'Kassie','Kat','Katara','Katarina','Kate','Katelyn','Katelynn','Katerina','Katharine','Katherine'
,'Kathleen','Kathryn','Kathy','Katia','Katie','Katlyn','Katrina','Katy','Katya','Kay'
,'Kaya','Kaye','Kayla','Kaylee','Kayleigh','Kayley','Kaylie','Kaylin','Keeley','Keely'
,'Keira','Keisha','Kelis','Kelley','Kelli','Kellie','Kelly','Kelsey','Kelsie','Kendall'
,'Kendra','Kennedy','Kenzie','Keri','Kerian','Kerri','Kerry','Kiana','Kiara','Kiera'
,'Kierra','Kiersten','Kiki','Kiley','Kim','Kimberlee','Kimberley','Kimberly','Kimbriella','Kimmy'
,'Kinley','Kinsey','Kinsley','Kira','Kirsten','Kirstin','Kirsty','Kiswa','Kitty','Kizzy'
,'Kora','Kourtney','Kris','Krista','Kristen','Kristi','Kristie','Kristin','Kristina','Kristine'
,'Kristy','Krystal','Kyla','Kylee','Kyleigh','Kylie','Kyra','Lacey','Lacie','Lacy'
,'Ladonna','Laila','Lakyn','Lala','Lana','Laney','Lara','Larissa','Latoya','Laura'
,'Laurel','Lauren','Lauri','Laurie','Lauryn','Lavana','Lavender','Lavinia','Layla','Lea'
,'Leah','Leandra','Leann','Leanna','Leanne','Lee','Leela','Leena','Leia','Leigh'
,'Leila','Leilani','Lela','Lena','Lenore','Leona','Leonie','Leora','Lesa','Lesley'
],
test: "TEST",
initialize: function()
{
this.bindAll();
},
addItem: function(event)
{
var array = (Math.random() > 0.5) ? this.boysNames : this.girlsNames,
index = Math.floor(Math.random()*array.length),
name = array[index];
this.myList.push({name:name});
},
removeItem: function(event)
{
this.myList.pop();
},
toString: function()
{
return 'MyApp';
},
});
});
|
ace.define('ace/theme/needs', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = false;
exports.cssClass = "ace-language";
exports.cssText = ".ace-language{\
}\
.ace_token_Keyword.ace_keyword{\
color: #708;\
}\
.ace_string{\
color: blue;\
}\
.ace_variable.ace_def{\
color: #71a;\
}\
.ace_entity-name-tag.ace_atom{\
color: #05a;\
}\
.ace_entity-name-tag.ace_type{\
color: #39238c;\
font-style: italic;\
}\
.ace_entity-name-tag.ace_true{\
color: #20800b;\
}\
.ace_entity-name-tag.ace_false{\
color: #be361b;\
}\
.ace_url{\
color: #0000FF;\
}\
.ace_variables{\
color: #000000;\
}\
.ace_comment{\
color: #236e24;\
}\
.ace_variable.ace_functions.ace_1{\
color: #DF7401;\
}\
.ace-language .ace_gutter {\
background: rgba(250, 250, 250, 0.5);\
color: #BDBDBD;\
overflow : visible;\
border-right: 1px solid rgba(0,0,0,0.05);\
}\
.ace-language .ace_print-margin {\
width: 1px;\
background: #e8e8e8;\
}\
.ace-language {\
background-color: #FFFFFF;\
}\
.ace-language .ace_cursor {\
color: black;\
}\
.ace-language .ace_invisible {\
color: rgb(191, 191, 191);\
}\
.ace-language .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
.ace-language .ace_constant.ace_language {\
color: rgb(88, 92, 246);\
}\
.ace-language .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
.ace-language .ace_invalid {\
background-color: rgb(153, 0, 0);\
color: white;\
}\
.ace-language .ace_fold {\
}\
.ace-language .ace_support.ace_function {\
color: rgb(60, 76, 114);\
}\
.ace-language .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
.ace-language .ace_support.ace_type,\
.ace-language .ace_support.ace_class\
.ace-language .ace_support.ace_other {\
color: rgb(109, 121, 222);\
}\
.ace-language .ace_variable.ace_parameter {\
font-style:italic;\
color:#FD971F;\
}\
.ace-language .ace_constant.ace_numeric {\
color: rgb(0, 0, 205);\
}\
.ace-language .ace_xml-pe {\
color: rgb(104, 104, 91);\
}\
.ace-language .ace_entity.ace_name.ace_function {\
color: #0000A2;\
}\
.ace-language .ace_heading {\
color: rgb(12, 7, 255);\
}\
.ace-language .ace_list {\
color:rgb(185, 6, 144);\
}\
.ace-language .ace_marker-layer .ace_selection {\
background: rgba(45, 151, 221, 0.29);\
}\
.ace-language .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
.ace-language .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
.ace-language .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
.ace-language .ace_marker-layer .ace_active-line {\
background: rgba(133, 151, 170, 0.09);\
}\
.ace-language .ace_gutter-active-line {\
background-color: rgba(66, 66, 66, 0.06);\
border-right: 1px solid rgba(66, 128, 178, 0.19);\
right: -1px;\
}\
.ace-language .ace_marker-layer .ace_selected-word {\
background: rgba(66, 128, 178, 0.12);\
border-bottom: 1px solid rgba(66, 128, 178, 0.19);\
}\
.ace-language .ace_storage,\
.ace-language .ace_meta.ace_tag {\
color: rgb(147, 15, 128);\
}\
.ace-language .ace_entity.ace_other.ace_attribute-name {\
color: #994409;\
}\
";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
/*const Config = require('electron-config')
const config = new Config({
defaults: {
autoStart: false,
backgroundMode: true,
colorTheme: "classic"
}
})
module.exports.config = config*/
nconf.argv()
.env()
.file({file: path.join(__dirname, 'config.json')});
module.exports = nconf;
|
/*
* EarningsTableFooter Messages
*
* This contains all the text for the EarningsTableFooter component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
header: {
id: 'app.components.EarningsTableFooter.header',
defaultMessage: 'This is the EarningsTableFooter component !',
},
});
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var inversify_express_utils_1 = require("inversify-express-utils");
var inversify_1 = require("inversify");
var HomeController = (function () {
function HomeController() {
}
HomeController.prototype.get = function () {
return 'Home sweet home';
};
return HomeController;
}());
__decorate([
inversify_express_utils_1.Get('/'),
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", String)
], HomeController.prototype, "get", null);
HomeController = __decorate([
inversify_1.injectable(),
inversify_express_utils_1.Controller('/')
], HomeController);
exports.HomeController = HomeController;
|
import { Meteor } from 'meteor/meteor';
import { _ } from 'meteor/underscore';
import { ReactiveVar } from 'meteor/reactive-var';
import { Template } from 'meteor/templating';
import { inheritUtilForm, handleInputChange as inheritedHandleInputChange } from '/client/utils/form';
import { getAttributeNumber } from '/db/dbArenaFighters';
import { alertDialog } from '/client/layout/alertDialog';
inheritUtilForm(Template.arenaStrategyForm);
const rSortedAttackSequence = new ReactiveVar([]);
Template.arenaStrategyForm.onCreated(function() {
this.validateModel = validateStrategyModel;
this.handleInputChange = handleStrategyInputChange;
this.saveModel = saveStrategyModel;
this.model.set(this.data.joinData);
this.draggingIndex = null;
rSortedAttackSequence.set([]);
});
Template.arenaStrategyForm.onRendered(function() {
this.model.set(this.data.joinData);
});
function validateStrategyModel(model) {
const error = {};
if (model.spCost > getAttributeNumber('sp', model.sp)) {
error.spCost = '特攻消耗數值不可超過角色的SP值!';
}
else if (model.spCost < 1) {
error.spCost = '特攻消耗數值不可低於1!';
}
else if (model.spCost > 10) {
error.spCost = '特攻消耗數值不可高於10!';
}
if (_.size(error) > 0) {
return error;
}
}
function handleStrategyInputChange(event) {
switch (event.currentTarget.name) {
case 'spCost': {
const model = this.model.get();
model.spCost = parseInt(event.currentTarget.value, 10);
this.model.set(model);
break;
}
case 'normalManner': {
const model = this.model.get();
model.normalManner = this.$input
.filter('[name="normalManner"]')
.map((index, input) => {
return input.value;
})
.toArray();
this.model.set(model);
break;
}
case 'specialManner': {
const model = this.model.get();
model.specialManner = this.$input
.filter('[name="specialManner"]')
.map((index, input) => {
return input.value;
})
.toArray();
this.model.set(model);
break;
}
default: {
inheritedHandleInputChange.call(this, event);
break;
}
}
}
function saveStrategyModel(model) {
const submitData = _.pick(model, 'spCost', 'normalManner', 'specialManner');
submitData.attackSequence = rSortedAttackSequence.get();
Meteor.customCall('decideArenaStrategy', model.companyId, submitData, (error) => {
if (! error) {
alertDialog.alert('決策完成!');
}
});
}
Template.arenaStrategyForm.helpers({
spForecast() {
const sp = getAttributeNumber('sp', this.joinData.sp);
const model = Template.instance().model.get();
const spCost = model.spCost;
const tenRoundForecast = Math.floor(Math.min((sp + 1) / spCost, spCost));
const maximumRound = Meteor.settings.public.arenaMaximumRound;
const maximumForecast = Math.floor(Math.min((sp + Math.floor(maximumRound / 10)) / spCost, spCost / 10 * maximumRound));
return `目前的SP量為 ${sp}
,在 10 回合的戰鬥中估計可以發出 ${tenRoundForecast} 次特殊攻擊,
在 ${maximumRound} 回合的戰鬥中估計可以發出 ${maximumForecast} 次特殊攻擊。`;
},
getManner(type, index) {
const model = Template.instance().model.get();
const fieldName = `${type}Manner`;
return model[fieldName][index];
},
hasEnemy() {
return this.shuffledFighterCompanyIdList.length > 0;
},
enemyList() {
const shuffledFighterCompanyIdList = this.shuffledFighterCompanyIdList;
const model = Template.instance().model.get();
return _.map(model.attackSequence, (attackIndex) => {
return {
_id: attackIndex,
companyId: shuffledFighterCompanyIdList[attackIndex]
};
});
},
notSorted(index) {
return ! _.contains(rSortedAttackSequence.get(), index);
},
sortedEnemyList() {
const shuffledFighterCompanyIdList = this.shuffledFighterCompanyIdList;
return _.map(rSortedAttackSequence.get(), (attackIndex) => {
return {
_id: attackIndex,
companyId: shuffledFighterCompanyIdList[attackIndex]
};
});
}
});
Template.arenaStrategyForm.events({
'click [data-action="sortAll"]'(event, templateInstance) {
const model = templateInstance.model.get();
const attackSequence = rSortedAttackSequence.get();
rSortedAttackSequence.set(_.union(attackSequence, model.attackSequence));
},
'click [data-add]'(event, templateInstance) {
const index = parseFloat(templateInstance.$(event.currentTarget).attr('data-add'));
const sortedAttackSequence = rSortedAttackSequence.get();
rSortedAttackSequence.set(_.union(sortedAttackSequence, [index]));
},
'click [data-remove]'(event, templateInstance) {
const index = parseFloat(templateInstance.$(event.currentTarget).attr('data-remove'));
const sortedAttackSequence = rSortedAttackSequence.get();
rSortedAttackSequence.set(_.without(sortedAttackSequence, index));
},
reset(event, templateInstance) {
event.preventDefault();
templateInstance.model.set(templateInstance.data.joinData);
rSortedAttackSequence.set([]);
}
});
|
import React, { PropTypes } from 'react';
import injectSheet from 'react-jss';
import styles, { colors } from 'modules/common/styles';
import InlineThumbnail from 'modules/common/publishes/inlineThumbnail';
const Compact = ({ order, classes }) => {
const { amount } = order;
return (
<div className={classes.compact}>
<div className={classes.products}>
{order.items.map((item, i) => (
<span key={i}>
<InlineThumbnail type={order.type} thumbnail={item.product.thumbnail} />
<small>{` ${item.product.name}`}</small>
</span>
))}
</div>
<div className={classes.amount}>
<span>{amount === -1 ? '待议' : `¥${amount}`}</span>
<small className={styles.colorSubTitle}>(总价)</small>
</div>
</div>
);
};
Compact.propTypes = {
order: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired,
};
export default injectSheet({
compact: {
display: 'flex',
alignItems: 'center',
color: colors.colorSubTitle,
lineHeight: '32px', // to align with cardMenu button
},
products: {
flex: '1',
display: 'flex',
flexWrap: 'wrap',
'& > span': {
maxWidth: '10em',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
overflow: 'hidden',
marginRight: 16,
},
},
amount: {
color: colors.colorPrice,
},
})(Compact);
|
/**
* jQuery Yii GridView plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
(function ($) {
var selectCheckedRows, methods,
yiiXHR={},
gridSettings = [];
/**
* 1. Selects rows that have checkbox checked (only checkbox that is connected with selecting a row)
* 2. Check if "check all" need to be checked/unchecked
* @return object the jQuery object
*/
selectCheckedRows = function (gridId) {
var settings = gridSettings[gridId],
table = $('#' + gridId).find('.' + settings.tableClass);
table.children('tbody').find('input.select-on-check').filter(':checked').each(function () {
$(this).closest('tr').addClass('selected');
});
table.children('thead').find('th input').filter('[type="checkbox"]').each(function () {
var name = this.name.substring(0, this.name.length - 4) + '[]', //.. remove '_all' and add '[]''
$checks = $("input[name='" + name + "']", table);
this.checked = $checks.length > 0 && $checks.length === $checks.filter(':checked').length;
});
return this;
};
methods = {
/**
* yiiGridView set function.
* @param options map settings for the grid view. Available options are as follows:
* - ajaxUpdate: array, IDs of the containers whose content may be updated by ajax response
* - ajaxVar: string, the name of the request variable indicating the ID of the element triggering the AJAX request
* - ajaxType: string, the type (GET or POST) of the AJAX request
* - pagerClass: string, the CSS class for the pager container
* - tableClass: string, the CSS class for the table
* - selectableRows: integer, the number of rows that can be selected
* - updateSelector: string, the selector for choosing which elements can trigger ajax requests
* - beforeAjaxUpdate: function, the function to be called before ajax request is sent
* - afterAjaxUpdate: function, the function to be called after ajax response is received
* - ajaxUpdateError: function, the function to be called if an ajax error occurs
* - selectionChanged: function, the function to be called after the row selection is changed
* @return object the jQuery object
*/
init: function (options) {
var settings = $.extend({
ajaxUpdate: [],
ajaxVar: 'ajax',
ajaxType: 'GET',
pagerClass: 'pager',
loadingClass: 'loading',
filterClass: 'filters',
tableClass: 'items',
selectableRows: 1
// updateSelector: '#id .pager a, '#id .grid thead th a',
// beforeAjaxUpdate: function (id) {},
// afterAjaxUpdate: function (id, data) {},
// selectionChanged: function (id) {},
// url: 'ajax request URL'
}, options || {});
settings.tableClass = settings.tableClass.replace(/\s+/g, '.');
return this.each(function () {
var eventType,
$grid = $(this),
id = $grid.attr('id'),
pagerSelector = '#' + id + ' .' + settings.pagerClass.replace(/\s+/g, '.') + ' a',
sortSelector = '#' + id + ' .' + settings.tableClass + ' thead th a.sort-link',
inputSelector = '#' + id + ' .' + settings.filterClass + ' input, ' + '#' + id + ' .' + settings.filterClass + ' select';
settings.updateSelector = settings.updateSelector
.replace('{page}', pagerSelector)
.replace('{sort}', sortSelector);
settings.filterSelector = settings.filterSelector
.replace('{filter}', inputSelector);
gridSettings[id] = settings;
if (settings.ajaxUpdate.length > 0) {
$(document).on('click.yiiGridView', settings.updateSelector, function () {
// Check to see if History.js is enabled for our Browser
if (settings.enableHistory && window.History.enabled) {
// Ajaxify this link
var url = $(this).attr('href').split('?'),
params = $.deparam.querystring('?'+ (url[1] || ''));
delete params[settings.ajaxVar];
window.History.pushState(null, document.title, decodeURIComponent($.param.querystring(url[0], params)));
} else {
$('#' + id).yiiGridView('update', {url: $(this).attr('href')});
}
return false;
});
}
$(document).on('change.yiiGridView keydown.yiiGridView', settings.filterSelector, function (event) {
if (event.type === 'keydown') {
if (event.keyCode !== 13) {
return; // only react to enter key
} else {
eventType = 'keydown';
}
} else {
// prevent processing for both keydown and change events
if (eventType === 'keydown') {
eventType = '';
return;
}
}
var data = $(settings.filterSelector).serialize();
if (settings.pageVar !== undefined) {
data += '&' + settings.pageVar + '=1';
}
if (settings.enableHistory && settings.ajaxUpdate !== false && window.History.enabled) {
// Ajaxify this link
var url = $('#' + id).yiiGridView('getUrl'),
params = $.deparam.querystring($.param.querystring(url, data));
delete params[settings.ajaxVar];
window.History.pushState(null, document.title, decodeURIComponent($.param.querystring(url.substr(0, url.indexOf('?')), params)));
} else {
$('#' + id).yiiGridView('update', {data: data});
}
return false;
});
if (settings.enableHistory && settings.ajaxUpdate !== false && window.History.enabled) {
$(window).bind('statechange', function() { // Note: We are using statechange instead of popstate
var State = window.History.getState(); // Note: We are using History.getState() instead of event.state
$('#' + id).yiiGridView('update', {url: State.url});
});
}
if (settings.selectableRows > 0) {
selectCheckedRows(this.id);
$(document).on('click.yiiGridView', '#' + id + ' .' + settings.tableClass + ' > tbody > tr', function (e) {
var $currentGrid, $row, isRowSelected, $checks,
$target = $(e.target);
if ($target.closest('td').is('.empty,.button-column') || (e.target.type === 'checkbox' && !$target.hasClass('select-on-check'))) {
return;
}
$row = $(this);
$currentGrid = $('#' + id);
$checks = $('input.select-on-check', $currentGrid);
isRowSelected = $row.toggleClass('selected').hasClass('selected');
if (settings.selectableRows === 1) {
$row.siblings().removeClass('selected');
$checks.prop('checked', false);
}
$('input.select-on-check', $row).prop('checked', isRowSelected);
$("input.select-on-check-all", $currentGrid).prop('checked', $checks.length === $checks.filter(':checked').length);
if (settings.selectionChanged !== undefined) {
settings.selectionChanged(id);
}
});
if (settings.selectableRows > 1) {
$(document).on('click.yiiGridView', '#' + id + ' .select-on-check-all', function () {
var $currentGrid = $('#' + id),
$checks = $('input.select-on-check', $currentGrid),
$checksAll = $('input.select-on-check-all', $currentGrid),
$rows = $currentGrid.find('.' + settings.tableClass).children('tbody').children();
if (this.checked) {
$rows.addClass('selected');
$checks.prop('checked', true);
$checksAll.prop('checked', true);
} else {
$rows.removeClass('selected');
$checks.prop('checked', false);
$checksAll.prop('checked', false);
}
if (settings.selectionChanged !== undefined) {
settings.selectionChanged(id);
}
});
}
} else {
$(document).on('click.yiiGridView', '#' + id + ' .select-on-check', false);
}
});
},
/**
* Returns the key value for the specified row
* @param row integer the row number (zero-based index)
* @return string the key value
*/
getKey: function (row) {
return this.children('.keys').children('span').eq(row).text();
},
/**
* Returns the URL that generates the grid view content.
* @return string the URL that generates the grid view content.
*/
getUrl: function () {
var sUrl = gridSettings[this.attr('id')].url;
return sUrl || this.children('.keys').attr('title');
},
/**
* Returns the jQuery collection of the cells in the specified row.
* @param row integer the row number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified row.
*/
getRow: function (row) {
var sClass = gridSettings[this.attr('id')].tableClass;
return this.find('.' + sClass).children('tbody').children('tr').eq(row).children();
},
/**
* Returns the jQuery collection of the cells in the specified column.
* @param column integer the column number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified column.
*/
getColumn: function (column) {
var sClass = gridSettings[this.attr('id')].tableClass;
return this.find('.' + sClass).children('tbody').children('tr').children('td:nth-child(' + (column + 1) + ')');
},
/**
* Performs an AJAX-based update of the grid view contents.
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the grid view.
* @return object the jQuery object
*/
update: function (options) {
var customError;
if (options && options.error !== undefined) {
customError = options.error;
delete options.error;
}
return this.each(function () {
var $form,
$grid = $(this),
id = $grid.attr('id'),
settings = gridSettings[id];
options = $.extend({
type: settings.ajaxType,
url: $grid.yiiGridView('getUrl'),
success: function (data) {
var $data = $('<div>' + data + '</div>');
$.each(settings.ajaxUpdate, function (i, el) {
var updateId = '#' + el;
$(updateId).replaceWith($(updateId, $data));
});
if (settings.afterAjaxUpdate !== undefined) {
settings.afterAjaxUpdate(id, data);
}
if (settings.selectableRows > 0) {
selectCheckedRows(id);
}
},
complete: function () {
yiiXHR[id] = null;
$grid.removeClass(settings.loadingClass);
},
error: function (XHR, textStatus, errorThrown) {
var ret, err;
if (XHR.readyState === 0 || XHR.status === 0) {
return;
}
if (customError !== undefined) {
ret = customError(XHR);
if (ret !== undefined && !ret) {
return;
}
}
switch (textStatus) {
case 'timeout':
err = 'The request timed out!';
break;
case 'parsererror':
err = 'Parser error!';
break;
case 'error':
if (XHR.status && !/^\s*$/.test(XHR.status)) {
err = 'Error ' + XHR.status;
} else {
err = 'Error';
}
if (XHR.responseText && !/^\s*$/.test(XHR.responseText)) {
err = err + ': ' + XHR.responseText;
}
break;
}
if (settings.ajaxUpdateError !== undefined) {
settings.ajaxUpdateError(XHR, textStatus, errorThrown, err);
} else if (err) {
alert(err);
}
}
}, options || {});
if (options.type === 'GET') {
if (options.data !== undefined) {
options.url = $.param.querystring(options.url, options.data);
options.data = {};
}
} else {
if (options.data === undefined) {
options.data = $(settings.filterSelector).serialize();
}
}
if(yiiXHR[id] != null){
yiiXHR[id].abort();
}
//class must be added after yiiXHR.abort otherwise ajax.error will remove it
$grid.addClass(settings.loadingClass);
if (settings.ajaxUpdate !== false) {
if(settings.ajaxVar) {
options.url = $.param.querystring(options.url, settings.ajaxVar + '=' + id);
}
if (settings.beforeAjaxUpdate !== undefined) {
settings.beforeAjaxUpdate(id, options);
}
yiiXHR[id] = $.ajax(options);
} else { // non-ajax mode
if (options.type === 'GET') {
window.location.href = options.url;
} else { // POST mode
$form = $('<form action="' + options.url + '" method="post"></form>').appendTo('body');
if (options.data === undefined) {
options.data = {};
}
if (options.data.returnUrl === undefined) {
options.data.returnUrl = window.location.href;
}
$.each(options.data, function (name, value) {
$form.append($('<input type="hidden" name="t" value="" />').attr('name', name).val(value));
});
$form.submit();
}
}
});
},
/**
* Returns the key values of the currently selected rows.
* @return array the key values of the currently selected rows.
*/
getSelection: function () {
var settings = gridSettings[this.attr('id')],
keys = this.find('.keys span'),
selection = [];
this.find('.' + settings.tableClass).children('tbody').children().each(function (i) {
if ($(this).hasClass('selected')) {
selection.push(keys.eq(i).text());
}
});
return selection;
},
/**
* Returns the key values of the currently checked rows.
* @param column_id string the ID of the column
* @return array the key values of the currently checked rows.
*/
getChecked: function (column_id) {
var settings = gridSettings[this.attr('id')],
keys = this.find('.keys span'),
checked = [];
if (column_id.substring(column_id.length - 2) !== '[]') {
column_id = column_id + '[]';
}
this.find('.' + settings.tableClass).children('tbody').children('tr').children('td').children('input[name="' + column_id + '"]').each(function (i) {
if (this.checked) {
checked.push(keys.eq(i).text());
}
});
return checked;
}
};
$.fn.yiiGridView = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.yiiGridView');
return false;
}
};
/******************************************************************************
*** DEPRECATED METHODS
*** used before Yii 1.1.9
******************************************************************************/
$.fn.yiiGridView.settings = gridSettings;
/**
* Returns the key value for the specified row
* @param id string the ID of the grid view container
* @param row integer the row number (zero-based index)
* @return string the key value
*/
$.fn.yiiGridView.getKey = function (id, row) {
return $('#' + id).yiiGridView('getKey', row);
};
/**
* Returns the URL that generates the grid view content.
* @param id string the ID of the grid view container
* @return string the URL that generates the grid view content.
*/
$.fn.yiiGridView.getUrl = function (id) {
return $('#' + id).yiiGridView('getUrl');
};
/**
* Returns the jQuery collection of the cells in the specified row.
* @param id string the ID of the grid view container
* @param row integer the row number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified row.
*/
$.fn.yiiGridView.getRow = function (id, row) {
return $('#' + id).yiiGridView('getRow', row);
};
/**
* Returns the jQuery collection of the cells in the specified column.
* @param id string the ID of the grid view container
* @param column integer the column number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified column.
*/
$.fn.yiiGridView.getColumn = function (id, column) {
return $('#' + id).yiiGridView('getColumn', column);
};
/**
* Performs an AJAX-based update of the grid view contents.
* @param id string the ID of the grid view container
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the grid view.
*/
$.fn.yiiGridView.update = function (id, options) {
$('#' + id).yiiGridView('update', options);
};
/**
* Returns the key values of the currently selected rows.
* @param id string the ID of the grid view container
* @return array the key values of the currently selected rows.
*/
$.fn.yiiGridView.getSelection = function (id) {
return $('#' + id).yiiGridView('getSelection');
};
/**
* Returns the key values of the currently checked rows.
* @param id string the ID of the grid view container
* @param column_id string the ID of the column
* @return array the key values of the currently checked rows.
*/
$.fn.yiiGridView.getChecked = function (id, column_id) {
return $('#' + id).yiiGridView('getChecked', column_id);
};
})(jQuery);
$(document).ready(function(){
$notifycontainer=$("#notify-container").notify({
speed: 500,
custom: true,
expires: 5000
});
$.each(LS.messages,function(key, oMessage){
if(typeof oMessage.message ==="string")
{
if(typeof oMessage.type !="string")
{
oMessage.template="default-notify";
}
else
{
oMessage.template=oMessage.type+"-notify";
}
}
$notifycontainer.notify("create", oMessage.template, { message:oMessage.message});
});
});
/*
Copyright 2012 Igor Vaynberg
Version: 3.2 Timestamp: Mon Sep 10 10:38:04 PDT 2012
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in
compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is
distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
*/
(function ($) {
if(typeof $.fn.each2 == "undefined"){
$.fn.extend({
/*
* 4-10 times faster .each replacement
* use it carefully, as it overrides jQuery context of element on each iteration
*/
each2 : function (c) {
var j = $([0]), i = -1, l = this.length;
while (
++i < l
&& (j.context = j[0] = this[i])
&& c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
);
return this;
}
});
}
})(jQuery);
(function ($, undefined) {
"use strict";
/*global document, window, jQuery, console */
if (window.Select2 !== undefined) {
return;
}
var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer;
KEY = {
TAB: 9,
ENTER: 13,
ESC: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
SHIFT: 16,
CTRL: 17,
ALT: 18,
PAGE_UP: 33,
PAGE_DOWN: 34,
HOME: 36,
END: 35,
BACKSPACE: 8,
DELETE: 46,
isArrow: function (k) {
k = k.which ? k.which : k;
switch (k) {
case KEY.LEFT:
case KEY.RIGHT:
case KEY.UP:
case KEY.DOWN:
return true;
}
return false;
},
isControl: function (e) {
var k = e.which;
switch (k) {
case KEY.SHIFT:
case KEY.CTRL:
case KEY.ALT:
return true;
}
if (e.metaKey) return true;
return false;
},
isFunctionKey: function (k) {
k = k.which ? k.which : k;
return k >= 112 && k <= 123;
}
};
nextUid=(function() { var counter=1; return function() { return counter++; }; }());
function indexOf(value, array) {
var i = 0, l = array.length, v;
if (typeof value === "undefined") {
return -1;
}
if (value.constructor === String) {
for (; i < l; i = i + 1) if (value.localeCompare(array[i]) === 0) return i;
} else {
for (; i < l; i = i + 1) {
v = array[i];
if (v.constructor === String) {
if (v.localeCompare(value) === 0) return i;
} else {
if (v === value) return i;
}
}
}
return -1;
}
/**
* Compares equality of a and b taking into account that a and b may be strings, in which case localeCompare is used
* @param a
* @param b
*/
function equal(a, b) {
if (a === b) return true;
if (a === undefined || b === undefined) return false;
if (a === null || b === null) return false;
if (a.constructor === String) return a.localeCompare(b) === 0;
if (b.constructor === String) return b.localeCompare(a) === 0;
return false;
}
/**
* Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
* strings
* @param string
* @param separator
*/
function splitVal(string, separator) {
var val, i, l;
if (string === null || string.length < 1) return [];
val = string.split(separator);
for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
return val;
}
function getSideBorderPadding(element) {
return element.outerWidth() - element.width();
}
function installKeyUpChangeEvent(element) {
var key="keyup-change-value";
element.bind("keydown", function () {
if ($.data(element, key) === undefined) {
$.data(element, key, element.val());
}
});
element.bind("keyup", function () {
var val= $.data(element, key);
if (val !== undefined && element.val() !== val) {
$.removeData(element, key);
element.trigger("keyup-change");
}
});
}
$(document).delegate("body", "mousemove", function (e) {
$.data(document, "select2-lastpos", {x: e.pageX, y: e.pageY});
});
/**
* filters mouse events so an event is fired only if the mouse moved.
*
* filters out mouse events that occur when mouse is stationary but
* the elements under the pointer are scrolled.
*/
function installFilteredMouseMove(element) {
element.bind("mousemove", function (e) {
var lastpos = $.data(document, "select2-lastpos");
if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
$(e.target).trigger("mousemove-filtered", e);
}
});
}
/**
* Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
* within the last quietMillis milliseconds.
*
* @param quietMillis number of milliseconds to wait before invoking fn
* @param fn function to be debounced
* @param ctx object to be used as this reference within fn
* @return debounced version of fn
*/
function debounce(quietMillis, fn, ctx) {
ctx = ctx || undefined;
var timeout;
return function () {
var args = arguments;
window.clearTimeout(timeout);
timeout = window.setTimeout(function() {
fn.apply(ctx, args);
}, quietMillis);
};
}
/**
* A simple implementation of a thunk
* @param formula function used to lazily initialize the thunk
* @return {Function}
*/
function thunk(formula) {
var evaluated = false,
value;
return function() {
if (evaluated === false) { value = formula(); evaluated = true; }
return value;
};
};
function installDebouncedScroll(threshold, element) {
var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
element.bind("scroll", function (e) {
if (indexOf(e.target, element.get()) >= 0) notify(e);
});
}
function killEvent(event) {
event.preventDefault();
event.stopPropagation();
}
function measureTextWidth(e) {
if (!sizer){
var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
sizer = $("<div></div>").css({
position: "absolute",
left: "-10000px",
top: "-10000px",
display: "none",
fontSize: style.fontSize,
fontFamily: style.fontFamily,
fontStyle: style.fontStyle,
fontWeight: style.fontWeight,
letterSpacing: style.letterSpacing,
textTransform: style.textTransform,
whiteSpace: "nowrap"
});
$("body").append(sizer);
}
sizer.text(e.val());
return sizer.width();
}
function markMatch(text, term, markup) {
var match=text.toUpperCase().indexOf(term.toUpperCase()),
tl=term.length;
if (match<0) {
markup.push(text);
return;
}
markup.push(text.substring(0, match));
markup.push("<span class='select2-match'>");
markup.push(text.substring(match, match + tl));
markup.push("</span>");
markup.push(text.substring(match + tl, text.length));
}
/**
* Produces an ajax-based query function
*
* @param options object containing configuration paramters
* @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
* @param options.url url for the data
* @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
* @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
* @param options.traditional a boolean flag that should be true if you wish to use the traditional style of param serialization for the ajax request
* @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
* @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
* The expected format is an object containing the following keys:
* results array of objects that will be used as choices
* more (optional) boolean indicating whether there are more results available
* Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
*/
function ajax(options) {
var timeout, // current scheduled but not yet executed request
requestSequence = 0, // sequence used to drop out-of-order responses
handler = null,
quietMillis = options.quietMillis || 100;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
requestSequence += 1; // increment the sequence
var requestNumber = requestSequence, // this request's sequence number
data = options.data, // ajax data function
transport = options.transport || $.ajax,
traditional = options.traditional || false,
type = options.type || 'GET'; // set type of request (GET or POST)
data = data.call(this, query.term, query.page, query.context);
if( null !== handler) { handler.abort(); }
handler = transport.call(null, {
url: options.url,
dataType: options.dataType,
data: data,
type: type,
traditional: traditional,
success: function (data) {
if (requestNumber < requestSequence) {
return;
}
// TODO 3.0 - replace query.page with query so users have access to term, page, etc.
var results = options.results(data, query.page);
query.callback(results);
}
});
}, quietMillis);
};
}
/**
* Produces a query function that works with a local array
*
* @param options object containing configuration parameters. The options parameter can either be an array or an
* object.
*
* If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
*
* If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
* an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
* key can either be a String in which case it is expected that each element in the 'data' array has a key with the
* value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
* the text.
*/
function local(options) {
var data = options, // data elements
dataText,
text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
if (!$.isArray(data)) {
text = data.text;
// if text is not a function we assume it to be a key name
if (!$.isFunction(text)) {
dataText = data.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
text = function (item) { return item[dataText]; };
}
data = data.results;
}
return function (query) {
var t = query.term, filtered = { results: [] }, process;
if (t === "") {
query.callback({results: data});
return;
}
process = function(datum, collection) {
var group, attr;
datum = datum[0];
if (datum.children) {
group = {};
for (attr in datum) {
if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
}
group.children=[];
$(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
if (group.children.length) {
collection.push(group);
}
} else {
if (query.matcher(t, text(datum))) {
collection.push(datum);
}
}
};
$(data).each2(function(i, datum) { process(datum, filtered.results); });
query.callback(filtered);
};
}
// TODO javadoc
function tags(data) {
// TODO even for a function we should probably return a wrapper that does the same object/string check as
// the function for arrays. otherwise only functions that return objects are supported.
if ($.isFunction(data)) {
return data;
}
// if not a function we assume it to be an array
return function (query) {
var t = query.term, filtered = {results: []};
$(data).each(function () {
var isObject = this.text !== undefined,
text = isObject ? this.text : this;
if (t === "" || query.matcher(t, text)) {
filtered.results.push(isObject ? this : {id: this, text: this});
}
});
query.callback(filtered);
};
}
/**
* Checks if the formatter function should be used.
*
* Throws an error if it is not a function. Returns true if it should be used,
* false if no formatting should be performed.
*
* @param formatter
*/
function checkFormatter(formatter, formatterName) {
if ($.isFunction(formatter)) return true;
if (!formatter) return false;
throw new Error("formatterName must be a function or a falsy value");
}
function evaluate(val) {
return $.isFunction(val) ? val() : val;
}
function countResults(results) {
var count = 0;
$.each(results, function(i, item) {
if (item.children) {
count += countResults(item.children);
} else {
count++;
}
});
return count;
}
/**
* Default tokenizer. This function uses breaks the input on substring match of any string from the
* opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
* two options have to be defined in order for the tokenizer to work.
*
* @param input text user has typed so far or pasted into the search field
* @param selection currently selected choices
* @param selectCallback function(choice) callback tho add the choice to selection
* @param opts select2's opts
* @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
*/
function defaultTokenizer(input, selection, selectCallback, opts) {
var original = input, // store the original so we can compare and know if we need to tell the search to update its text
dupe = false, // check for whether a token we extracted represents a duplicate selected choice
token, // token
index, // position at which the separator was found
i, l, // looping variables
separator; // the matched separator
if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
while (true) {
index = -1;
for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
separator = opts.tokenSeparators[i];
index = input.indexOf(separator);
if (index >= 0) break;
}
if (index < 0) break; // did not find any token separator in the input string, bail
token = input.substring(0, index);
input = input.substring(index + separator.length);
if (token.length > 0) {
token = opts.createSearchChoice(token, selection);
if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
dupe = false;
for (i = 0, l = selection.length; i < l; i++) {
if (equal(opts.id(token), opts.id(selection[i]))) {
dupe = true; break;
}
}
if (!dupe) selectCallback(token);
}
}
}
if (original.localeCompare(input) != 0) return input;
}
/**
* blurs any Select2 container that has focus when an element outside them was clicked or received focus
*
* also takes care of clicks on label tags that point to the source element
*/
$(document).ready(function () {
$(document).delegate("body", "mousedown touchend", function (e) {
var target = $(e.target).closest("div.select2-container").get(0), attr;
if (target) {
$(document).find("div.select2-container-active").each(function () {
if (this !== target) $(this).data("select2").blur();
});
} else {
target = $(e.target).closest("div.select2-drop").get(0);
$(document).find("div.select2-drop-active").each(function () {
if (this !== target) $(this).data("select2").blur();
});
}
target=$(e.target);
attr = target.attr("for");
if ("LABEL" === e.target.tagName && attr && attr.length > 0) {
target = $("#"+attr);
target = target.data("select2");
if (target !== undefined) { target.focus(); e.preventDefault();}
}
});
});
/**
* Creates a new class
*
* @param superClass
* @param methods
*/
function clazz(SuperClass, methods) {
var constructor = function () {};
constructor.prototype = new SuperClass;
constructor.prototype.constructor = constructor;
constructor.prototype.parent = SuperClass.prototype;
constructor.prototype = $.extend(constructor.prototype, methods);
return constructor;
}
AbstractSelect2 = clazz(Object, {
// abstract
bind: function (func) {
var self = this;
return function () {
func.apply(self, arguments);
};
},
// abstract
init: function (opts) {
var results, search, resultsSelector = ".select2-results";
// prepare options
this.opts = opts = this.prepareOpts(opts);
this.id=opts.id;
// destroy if called on an existing component
if (opts.element.data("select2") !== undefined &&
opts.element.data("select2") !== null) {
this.destroy();
}
this.enabled=true;
this.container = this.createContainer();
this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
this.container.attr("id", this.containerId);
// cache the body so future lookups are cheap
this.body = thunk(function() { return opts.element.closest("body"); });
if (opts.element.attr("class") !== undefined) {
this.container.addClass(opts.element.attr("class").replace(/validate\[[\S ]+] ?/, ''));
}
this.container.css(evaluate(opts.containerCss));
this.container.addClass(evaluate(opts.containerCssClass));
// swap container for the element
this.opts.element
.data("select2", this)
.hide()
.before(this.container);
this.container.data("select2", this);
this.dropdown = this.container.find(".select2-drop");
this.dropdown.addClass(evaluate(opts.dropdownCssClass));
this.dropdown.data("select2", this);
this.results = results = this.container.find(resultsSelector);
this.search = search = this.container.find("input.select2-input");
search.attr("tabIndex", this.opts.element.attr("tabIndex"));
this.resultsPage = 0;
this.context = null;
// initialize the container
this.initContainer();
this.initContainerWidth();
installFilteredMouseMove(this.results);
this.dropdown.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
installDebouncedScroll(80, this.results);
this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
// if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
if ($.fn.mousewheel) {
results.mousewheel(function (e, delta, deltaX, deltaY) {
var top = results.scrollTop(), height;
if (deltaY > 0 && top - deltaY <= 0) {
results.scrollTop(0);
killEvent(e);
} else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
results.scrollTop(results.get(0).scrollHeight - results.height());
killEvent(e);
}
});
}
installKeyUpChangeEvent(search);
search.bind("keyup-change", this.bind(this.updateResults));
search.bind("focus", function () { search.addClass("select2-focused"); if (search.val() === " ") search.val(""); });
search.bind("blur", function () { search.removeClass("select2-focused");});
this.dropdown.delegate(resultsSelector, "mouseup", this.bind(function (e) {
if ($(e.target).closest(".select2-result-selectable:not(.select2-disabled)").length > 0) {
this.highlightUnderEvent(e);
this.selectHighlighted(e);
} else {
this.focusSearch();
}
killEvent(e);
}));
// trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
// for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
// dom it will trigger the popup close, which is not what we want
this.dropdown.bind("click mouseup mousedown", function (e) { e.stopPropagation(); });
if ($.isFunction(this.opts.initSelection)) {
// initialize selection based on the current value of the source element
this.initSelection();
// if the user has provided a function that can set selection based on the value of the source element
// we monitor the change event on the element and trigger it, allowing for two way synchronization
this.monitorSource();
}
if (opts.element.is(":disabled") || opts.element.is("[readonly='readonly']")) this.disable();
},
// abstract
destroy: function () {
var select2 = this.opts.element.data("select2");
if (select2 !== undefined) {
select2.container.remove();
select2.dropdown.remove();
select2.opts.element
.removeData("select2")
.unbind(".select2")
.show();
}
},
// abstract
prepareOpts: function (opts) {
var element, select, idKey, ajaxUrl;
element = opts.element;
if (element.get(0).tagName.toLowerCase() === "select") {
this.select = select = opts.element;
}
if (select) {
// these options are not allowed when attached to a select because they are picked up off the element itself
$.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
if (this in opts) {
throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
}
});
}
opts = $.extend({}, {
populateResults: function(container, results, query) {
var populate, data, result, children, id=this.opts.id, self=this;
populate=function(results, container, depth) {
var i, l, result, selectable, compound, node, label, innerContainer, formatted;
for (i = 0, l = results.length; i < l; i = i + 1) {
result=results[i];
selectable=id(result) !== undefined;
compound=result.children && result.children.length > 0;
node=$("<li></li>");
node.addClass("select2-results-dept-"+depth);
node.addClass("select2-result");
node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
if (compound) { node.addClass("select2-result-with-children"); }
node.addClass(self.opts.formatResultCssClass(result));
label=$("<div></div>");
label.addClass("select2-result-label");
formatted=opts.formatResult(result, label, query);
if (formatted!==undefined) {
label.html(self.opts.escapeMarkup(formatted));
}
node.append(label);
if (compound) {
innerContainer=$("<ul></ul>");
innerContainer.addClass("select2-result-sub");
populate(result.children, innerContainer, depth+1);
node.append(innerContainer);
}
node.data("select2-data", result);
container.append(node);
}
};
populate(results, container, 0);
}
}, $.fn.select2.defaults, opts);
if (typeof(opts.id) !== "function") {
idKey = opts.id;
opts.id = function (e) { return e[idKey]; };
}
if (select) {
opts.query = this.bind(function (query) {
var data = { results: [], more: false },
term = query.term,
children, firstChild, process;
process=function(element, collection) {
var group;
if (element.is("option")) {
if (query.matcher(term, element.text(), element)) {
collection.push({id:element.attr("value"), text:element.text(), element: element.get(), css: element.attr("class")});
}
} else if (element.is("optgroup")) {
group={text:element.attr("label"), children:[], element: element.get(), css: element.attr("class")};
element.children().each2(function(i, elm) { process(elm, group.children); });
if (group.children.length>0) {
collection.push(group);
}
}
};
children=element.children();
// ignore the placeholder option if there is one
if (this.getPlaceholder() !== undefined && children.length > 0) {
firstChild = children[0];
if ($(firstChild).text() === "") {
children=children.not(firstChild);
}
}
children.each2(function(i, elm) { process(elm, data.results); });
query.callback(data);
});
// this is needed because inside val() we construct choices from options and there id is hardcoded
opts.id=function(e) { return e.id; };
opts.formatResultCssClass = function(data) { return data.css; }
} else {
if (!("query" in opts)) {
if ("ajax" in opts) {
ajaxUrl = opts.element.data("ajax-url");
if (ajaxUrl && ajaxUrl.length > 0) {
opts.ajax.url = ajaxUrl;
}
opts.query = ajax(opts.ajax);
} else if ("data" in opts) {
opts.query = local(opts.data);
} else if ("tags" in opts) {
opts.query = tags(opts.tags);
opts.createSearchChoice = function (term) { return {id: term, text: term}; };
opts.initSelection = function (element, callback) {
var data = [];
$(splitVal(element.val(), opts.separator)).each(function () {
var id = this, text = this, tags=opts.tags;
if ($.isFunction(tags)) tags=tags();
$(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
data.push({id: id, text: text});
});
callback(data);
};
}
}
}
if (typeof(opts.query) !== "function") {
throw "query function not defined for Select2 " + opts.element.attr("id");
}
return opts;
},
/**
* Monitor the original element for changes and update select2 accordingly
*/
// abstract
monitorSource: function () {
this.opts.element.bind("change.select2", this.bind(function (e) {
if (this.opts.element.data("select2-change-triggered") !== true) {
this.initSelection();
}
}));
},
/**
* Triggers the change event on the source element
*/
// abstract
triggerChange: function (details) {
details = details || {};
details= $.extend({}, details, { type: "change", val: this.val() });
// prevents recursive triggering
this.opts.element.data("select2-change-triggered", true);
this.opts.element.trigger(details);
this.opts.element.data("select2-change-triggered", false);
// some validation frameworks ignore the change event and listen instead to keyup, click for selects
// so here we trigger the click event manually
this.opts.element.click();
// ValidationEngine ignorea the change event and listens instead to blur
// so here we trigger the blur event manually if so desired
if (this.opts.blurOnChange)
this.opts.element.blur();
},
// abstract
enable: function() {
if (this.enabled) return;
this.enabled=true;
this.container.removeClass("select2-container-disabled");
},
// abstract
disable: function() {
if (!this.enabled) return;
this.close();
this.enabled=false;
this.container.addClass("select2-container-disabled");
},
// abstract
opened: function () {
return this.container.hasClass("select2-dropdown-open");
},
// abstract
positionDropdown: function() {
var offset = this.container.offset(),
height = this.container.outerHeight(),
width = this.container.outerWidth(),
dropHeight = this.dropdown.outerHeight(),
viewportBottom = $(window).scrollTop() + document.documentElement.clientHeight,
dropTop = offset.top + height,
dropLeft = offset.left,
enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
aboveNow = this.dropdown.hasClass("select2-drop-above"),
bodyOffset,
above,
css;
// console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
// console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
// fix positioning when body has an offset and is not position: static
if (this.body().css('position') !== 'static') {
bodyOffset = this.body().offset();
dropTop -= bodyOffset.top;
dropLeft -= bodyOffset.left;
}
// always prefer the current above/below alignment, unless there is not enough room
if (aboveNow) {
above = true;
if (!enoughRoomAbove && enoughRoomBelow) above = false;
} else {
above = false;
if (!enoughRoomBelow && enoughRoomAbove) above = true;
}
if (above) {
dropTop = offset.top - dropHeight;
this.container.addClass("select2-drop-above");
this.dropdown.addClass("select2-drop-above");
}
else {
this.container.removeClass("select2-drop-above");
this.dropdown.removeClass("select2-drop-above");
}
css = $.extend({
top: dropTop,
left: dropLeft,
width: width
}, evaluate(this.opts.dropdownCss));
this.dropdown.css(css);
},
// abstract
shouldOpen: function() {
var event;
if (this.opened()) return false;
event = $.Event("open");
this.opts.element.trigger(event);
return !event.isDefaultPrevented();
},
// abstract
clearDropdownAlignmentPreference: function() {
// clear the classes used to figure out the preference of where the dropdown should be opened
this.container.removeClass("select2-drop-above");
this.dropdown.removeClass("select2-drop-above");
},
/**
* Opens the dropdown
*
* @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
* the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
*/
// abstract
open: function () {
if (!this.shouldOpen()) return false;
window.setTimeout(this.bind(this.opening), 1);
return true;
},
/**
* Performs the opening of the dropdown
*/
// abstract
opening: function() {
var cid = this.containerId, selector = this.containerSelector,
scroll = "scroll." + cid, resize = "resize." + cid;
this.container.parents().each(function() {
$(this).bind(scroll, function() {
var s2 = $(selector);
if (s2.length == 0) {
$(this).unbind(scroll);
}
s2.select2("close");
});
});
$(window).bind(resize, function() {
var s2 = $(selector);
if (s2.length == 0) {
$(window).unbind(resize);
}
s2.select2("close");
});
this.clearDropdownAlignmentPreference();
if (this.search.val() === " ") { this.search.val(""); }
this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
this.updateResults(true);
if(this.dropdown[0] !== this.body().children().last()[0]) {
this.dropdown.detach().appendTo(this.body());
}
this.dropdown.show();
this.positionDropdown();
this.dropdown.addClass("select2-drop-active");
this.ensureHighlightVisible();
this.focusSearch();
},
// abstract
close: function () {
if (!this.opened()) return;
var self = this;
this.container.parents().each(function() {
$(this).unbind("scroll." + self.containerId);
});
$(window).unbind("resize." + this.containerId);
this.clearDropdownAlignmentPreference();
this.dropdown.hide();
this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
this.results.empty();
this.clearSearch();
this.opts.element.trigger($.Event("close"));
},
// abstract
clearSearch: function () {
},
// abstract
ensureHighlightVisible: function () {
var results = this.results, children, index, child, hb, rb, y, more;
index = this.highlight();
if (index < 0) return;
if (index == 0) {
// if the first element is highlighted scroll all the way to the top,
// that way any unselectable headers above it will also be scrolled
// into view
results.scrollTop(0);
return;
}
children = results.find(".select2-result-selectable");
child = $(children[index]);
hb = child.offset().top + child.outerHeight();
// if this is the last child lets also make sure select2-more-results is visible
if (index === children.length - 1) {
more = results.find("li.select2-more-results");
if (more.length > 0) {
hb = more.offset().top + more.outerHeight();
}
}
rb = results.offset().top + results.outerHeight();
if (hb > rb) {
results.scrollTop(results.scrollTop() + (hb - rb));
}
y = child.offset().top - results.offset().top;
// make sure the top of the element is visible
if (y < 0) {
results.scrollTop(results.scrollTop() + y); // y is negative
}
},
// abstract
moveHighlight: function (delta) {
var choices = this.results.find(".select2-result-selectable"),
index = this.highlight();
while (index > -1 && index < choices.length) {
index += delta;
var choice = $(choices[index]);
if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled")) {
this.highlight(index);
break;
}
}
},
// abstract
highlight: function (index) {
var choices = this.results.find(".select2-result-selectable").not(".select2-disabled");
if (arguments.length === 0) {
return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
}
if (index >= choices.length) index = choices.length - 1;
if (index < 0) index = 0;
choices.removeClass("select2-highlighted");
$(choices[index]).addClass("select2-highlighted");
this.ensureHighlightVisible();
},
// abstract
countSelectableResults: function() {
return this.results.find(".select2-result-selectable").not(".select2-disabled").length;
},
// abstract
highlightUnderEvent: function (event) {
var el = $(event.target).closest(".select2-result-selectable");
if (el.length > 0 && !el.is(".select2-highlighted")) {
var choices = this.results.find('.select2-result-selectable');
this.highlight(choices.index(el));
} else if (el.length == 0) {
// if we are over an unselectable item remove al highlights
this.results.find(".select2-highlighted").removeClass("select2-highlighted");
}
},
// abstract
loadMoreIfNeeded: function () {
var results = this.results,
more = results.find("li.select2-more-results"),
below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
offset = -1, // index of first element without data
page = this.resultsPage + 1,
self=this,
term=this.search.val(),
context=this.context;
if (more.length === 0) return;
below = more.offset().top - results.offset().top - results.height();
if (below <= 0) {
more.addClass("select2-active");
this.opts.query({
term: term,
page: page,
context: context,
matcher: this.opts.matcher,
callback: this.bind(function (data) {
// ignore a response if the select2 has been closed before it was received
if (!self.opened()) return;
self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
if (data.more===true) {
more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
} else {
more.remove();
}
self.positionDropdown();
self.resultsPage = page;
})});
}
},
/**
* Default tokenizer function which does nothing
*/
tokenize: function() {
},
/**
* @param initial whether or not this is the call to this method right after the dropdown has been opened
*/
// abstract
updateResults: function (initial) {
var search = this.search, results = this.results, opts = this.opts, data, self=this, input;
// if the search is currently hidden we do not alter the results
if (initial !== true && (this.showSearchInput === false || !this.opened())) {
return;
}
search.addClass("select2-active");
function postRender() {
results.scrollTop(0);
search.removeClass("select2-active");
self.positionDropdown();
}
function render(html) {
results.html(self.opts.escapeMarkup(html));
postRender();
}
if (opts.maximumSelectionSize >=1) {
data = this.data();
if ($.isArray(data) && data.length >= opts.maximumSelectionSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(opts.maximumSelectionSize) + "</li>");
return;
}
}
if (search.val().length < opts.minimumInputLength && checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
return;
}
else {
render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
}
// give the tokenizer a chance to pre-process the input
input = this.tokenize();
if (input != undefined && input != null) {
search.val(input);
}
this.resultsPage = 1;
opts.query({
term: search.val(),
page: this.resultsPage,
context: null,
matcher: opts.matcher,
callback: this.bind(function (data) {
var def; // default choice
// ignore a response if the select2 has been closed before it was received
if (!this.opened()) return;
// save context, if any
this.context = (data.context===undefined) ? null : data.context;
// create a default choice and prepend it to the list
if (this.opts.createSearchChoice && search.val() !== "") {
def = this.opts.createSearchChoice.call(null, search.val(), data.results);
if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
if ($(data.results).filter(
function () {
return equal(self.id(this), self.id(def));
}).length === 0) {
data.results.unshift(def);
}
}
}
if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
return;
}
results.empty();
self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
}
this.postprocessResults(data, initial);
postRender();
})});
},
// abstract
cancel: function () {
this.close();
},
// abstract
blur: function () {
this.close();
this.container.removeClass("select2-container-active");
this.dropdown.removeClass("select2-drop-active");
// synonymous to .is(':focus'), which is available in jquery >= 1.6
if (this.search[0] === document.activeElement) { this.search.blur(); }
this.clearSearch();
this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
},
// abstract
focusSearch: function () {
// need to do it here as well as in timeout so it works in IE
this.search.show();
this.search.focus();
/* we do this in a timeout so that current event processing can complete before this code is executed.
this makes sure the search field is focussed even if the current event would blur it */
window.setTimeout(this.bind(function () {
// reset the value so IE places the cursor at the end of the input box
this.search.show();
this.search.focus();
this.search.val(this.search.val());
}), 10);
},
// abstract
selectHighlighted: function () {
var index=this.highlight(),
highlighted=this.results.find(".select2-highlighted").not(".select2-disabled"),
data = highlighted.closest('.select2-result-selectable').data("select2-data");
if (data) {
highlighted.addClass("select2-disabled");
this.highlight(index);
this.onSelect(data);
}
},
// abstract
getPlaceholder: function () {
return this.opts.element.attr("placeholder") ||
this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
this.opts.element.data("placeholder") ||
this.opts.placeholder;
},
/**
* Get the desired width for the container element. This is
* derived first from option `width` passed to select2, then
* the inline 'style' on the original element, and finally
* falls back to the jQuery calculated element width.
*/
// abstract
initContainerWidth: function () {
function resolveContainerWidth() {
var style, attrs, matches, i, l;
if (this.opts.width === "off") {
return null;
} else if (this.opts.width === "element"){
return this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px';
} else if (this.opts.width === "copy" || this.opts.width === "resolve") {
// check if there is inline style on the element that contains width
style = this.opts.element.attr('style');
if (style !== undefined) {
attrs = style.split(';');
for (i = 0, l = attrs.length; i < l; i = i + 1) {
matches = attrs[i].replace(/\s/g, '')
.match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
if (matches !== null && matches.length >= 1)
return matches[1];
}
}
if (this.opts.width === "resolve") {
// next check if css('width') can resolve a width that is percent based, this is sometimes possible
// when attached to input type=hidden or elements hidden via css
style = this.opts.element.css('width');
if (style.indexOf("%") > 0) return style;
// finally, fallback on the calculated width of the element
return (this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px');
}
return null;
} else if ($.isFunction(this.opts.width)) {
return this.opts.width();
} else {
return this.opts.width;
}
};
var width = resolveContainerWidth.call(this);
if (width !== null) {
this.container.attr("style", "width: "+width);
}
}
});
SingleSelect2 = clazz(AbstractSelect2, {
// single
createContainer: function () {
var container = $("<div></div>", {
"class": "select2-container"
}).html([
" <a href='#' onclick='return false;' class='select2-choice'>",
" <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
" <div><b></b></div>" ,
"</a>",
" <div class='select2-drop select2-offscreen'>" ,
" <div class='select2-search'>" ,
" <input type='text' autocomplete='off' class='select2-input'/>" ,
" </div>" ,
" <ul class='select2-results'>" ,
" </ul>" ,
"</div>"].join(""));
return container;
},
// single
opening: function () {
this.search.show();
this.parent.opening.apply(this, arguments);
this.dropdown.removeClass("select2-offscreen");
},
// single
close: function () {
if (!this.opened()) return;
this.parent.close.apply(this, arguments);
this.dropdown.removeAttr("style").addClass("select2-offscreen").insertAfter(this.selection).show();
},
// single
focus: function () {
this.close();
this.selection.focus();
},
// single
isFocused: function () {
return this.selection[0] === document.activeElement;
},
// single
cancel: function () {
this.parent.cancel.apply(this, arguments);
this.selection.focus();
},
// single
initContainer: function () {
var selection,
container = this.container,
dropdown = this.dropdown,
clickingInside = false;
this.selection = selection = container.find(".select2-choice");
this.search.bind("keydown", this.bind(function (e) {
if (!this.enabled) return;
if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
// prevent the page from scrolling
killEvent(e);
return;
}
if (this.opened()) {
switch (e.which) {
case KEY.UP:
case KEY.DOWN:
this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
killEvent(e);
return;
case KEY.TAB:
case KEY.ENTER:
this.selectHighlighted();
killEvent(e);
return;
case KEY.ESC:
this.cancel(e);
killEvent(e);
return;
}
} else {
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
return;
}
if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
return;
}
this.open();
if (e.which === KEY.ENTER) {
// do not propagate the event otherwise we open, and propagate enter which closes
return;
}
}
}));
this.search.bind("focus", this.bind(function() {
this.selection.attr("tabIndex", "-1");
}));
this.search.bind("blur", this.bind(function() {
if (!this.opened()) this.container.removeClass("select2-container-active");
window.setTimeout(this.bind(function() { this.selection.attr("tabIndex", this.opts.element.attr("tabIndex")); }), 10);
}));
selection.bind("mousedown", this.bind(function (e) {
clickingInside = true;
if (this.opened()) {
this.close();
this.selection.focus();
} else if (this.enabled) {
this.open();
}
clickingInside = false;
}));
dropdown.bind("mousedown", this.bind(function() { this.search.focus(); }));
selection.bind("focus", this.bind(function() {
this.container.addClass("select2-container-active");
// hide the search so the tab key does not focus on it
this.search.attr("tabIndex", "-1");
}));
selection.bind("blur", this.bind(function() {
if (!this.opened()) {
this.container.removeClass("select2-container-active");
}
window.setTimeout(this.bind(function() { this.search.attr("tabIndex", this.opts.element.attr("tabIndex")); }), 10);
}));
selection.bind("keydown", this.bind(function(e) {
if (!this.enabled) return;
if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
// prevent the page from scrolling
killEvent(e);
return;
}
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
|| e.which === KEY.ESC) {
return;
}
if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
return;
}
if (e.which == KEY.DELETE) {
if (this.opts.allowClear) {
this.clear();
}
return;
}
this.open();
if (e.which === KEY.ENTER) {
// do not propagate the event otherwise we open, and propagate enter which closes
killEvent(e);
return;
}
// do not set the search input value for non-alpha-numeric keys
// otherwise pressing down results in a '(' being set in the search field
if (e.which < 48 ) { // '0' == 48
killEvent(e);
return;
}
var keyWritten = String.fromCharCode(e.which).toLowerCase();
if (e.shiftKey) {
keyWritten = keyWritten.toUpperCase();
}
// focus the field before calling val so the cursor ends up after the value instead of before
this.search.focus();
this.search.val(keyWritten);
// prevent event propagation so it doesnt replay on the now focussed search field and result in double key entry
killEvent(e);
}));
selection.delegate("abbr", "mousedown", this.bind(function (e) {
if (!this.enabled) return;
this.clear();
killEvent(e);
this.close();
this.triggerChange();
this.selection.focus();
}));
this.setPlaceholder();
this.search.bind("focus", this.bind(function() {
this.container.addClass("select2-container-active");
}));
},
// single
clear: function() {
this.opts.element.val("");
this.selection.find("span").empty();
this.selection.removeData("select2-data");
this.setPlaceholder();
},
/**
* Sets selection based on source element's value
*/
// single
initSelection: function () {
var selected;
if (this.opts.element.val() === "") {
this.close();
this.setPlaceholder();
} else {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(selected){
if (selected !== undefined && selected !== null) {
self.updateSelection(selected);
self.close();
self.setPlaceholder();
}
});
}
},
// single
prepareOpts: function () {
var opts = this.parent.prepareOpts.apply(this, arguments);
if (opts.element.get(0).tagName.toLowerCase() === "select") {
// install the selection initializer
opts.initSelection = function (element, callback) {
var selected = element.find(":selected");
// a single select box always has a value, no need to null check 'selected'
if ($.isFunction(callback))
callback({id: selected.attr("value"), text: selected.text()});
};
}
return opts;
},
// single
setPlaceholder: function () {
var placeholder = this.getPlaceholder();
if (this.opts.element.val() === "" && placeholder !== undefined) {
// check for a first blank option if attached to a select
if (this.select && this.select.find("option:first").text() !== "") return;
this.selection.find("span").html(this.opts.escapeMarkup(placeholder));
this.selection.addClass("select2-default");
this.selection.find("abbr").hide();
}
},
// single
postprocessResults: function (data, initial) {
var selected = 0, self = this, showSearchInput = true;
// find the selected element in the result list
this.results.find(".select2-result-selectable").each2(function (i, elm) {
if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
selected = i;
return false;
}
});
// and highlight it
this.highlight(selected);
// hide the search box if this is the first we got the results and there are a few of them
if (initial === true) {
showSearchInput = this.showSearchInput = countResults(data.results) >= this.opts.minimumResultsForSearch;
this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
//add "select2-with-searchbox" to the container if search box is shown
$(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
}
},
// single
onSelect: function (data) {
var old = this.opts.element.val();
this.opts.element.val(this.id(data));
this.updateSelection(data);
this.close();
this.selection.focus();
if (!equal(old, this.id(data))) { this.triggerChange(); }
},
// single
updateSelection: function (data) {
var container=this.selection.find("span"), formatted;
this.selection.data("select2-data", data);
container.empty();
formatted=this.opts.formatSelection(data, container);
if (formatted !== undefined) {
container.append(this.opts.escapeMarkup(formatted));
}
this.selection.removeClass("select2-default");
if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
this.selection.find("abbr").show();
}
},
// single
val: function () {
var val, data = null, self = this;
if (arguments.length === 0) {
return this.opts.element.val();
}
val = arguments[0];
if (this.select) {
this.select
.val(val)
.find(":selected").each2(function (i, elm) {
data = {id: elm.attr("value"), text: elm.text()};
return false;
});
this.updateSelection(data);
this.setPlaceholder();
} else {
if (this.opts.initSelection === undefined) {
throw new Error("cannot call val() if initSelection() is not defined");
}
// val is an id. !val is true for [undefined,null,'']
if (!val) {
this.clear();
return;
}
this.opts.element.val(val);
this.opts.initSelection(this.opts.element, function(data){
self.opts.element.val(!data ? "" : self.id(data));
self.updateSelection(data);
self.setPlaceholder();
});
}
},
// single
clearSearch: function () {
this.search.val("");
},
// single
data: function(value) {
var data;
if (arguments.length === 0) {
data = this.selection.data("select2-data");
if (data == undefined) data = null;
return data;
} else {
if (!value || value === "") {
this.clear();
} else {
this.opts.element.val(!value ? "" : this.id(value));
this.updateSelection(value);
}
}
}
});
MultiSelect2 = clazz(AbstractSelect2, {
// multi
createContainer: function () {
var container = $("<div></div>", {
"class": "select2-container select2-container-multi"
}).html([
" <ul class='select2-choices'>",
//"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
" <li class='select2-search-field'>" ,
" <input type='text' autocomplete='off' class='select2-input'>" ,
" </li>" ,
"</ul>" ,
"<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
" <ul class='select2-results'>" ,
" </ul>" ,
"</div>"].join(""));
return container;
},
// multi
prepareOpts: function () {
var opts = this.parent.prepareOpts.apply(this, arguments);
// TODO validate placeholder is a string if specified
if (opts.element.get(0).tagName.toLowerCase() === "select") {
// install sthe selection initializer
opts.initSelection = function (element,callback) {
var data = [];
element.find(":selected").each2(function (i, elm) {
data.push({id: elm.attr("value"), text: elm.text()});
});
if ($.isFunction(callback))
callback(data);
};
}
return opts;
},
// multi
initContainer: function () {
var selector = ".select2-choices", selection;
this.searchContainer = this.container.find(".select2-search-field");
this.selection = selection = this.container.find(selector);
this.search.bind("keydown", this.bind(function (e) {
if (!this.enabled) return;
if (e.which === KEY.BACKSPACE && this.search.val() === "") {
this.close();
var choices,
selected = selection.find(".select2-search-choice-focus");
if (selected.length > 0) {
this.unselect(selected.first());
this.search.width(10);
killEvent(e);
return;
}
choices = selection.find(".select2-search-choice");
if (choices.length > 0) {
choices.last().addClass("select2-search-choice-focus");
}
} else {
selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
}
if (this.opened()) {
switch (e.which) {
case KEY.UP:
case KEY.DOWN:
this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
killEvent(e);
return;
case KEY.ENTER:
case KEY.TAB:
this.selectHighlighted();
killEvent(e);
return;
case KEY.ESC:
this.cancel(e);
killEvent(e);
return;
}
}
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
|| e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
return;
}
if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
return;
}
this.open();
if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
// prevent the page from scrolling
killEvent(e);
}
}));
this.search.bind("keyup", this.bind(this.resizeSearch));
this.search.bind("blur", this.bind(function(e) {
this.container.removeClass("select2-container-active");
this.search.removeClass("select2-focused");
this.clearSearch();
e.stopImmediatePropagation();
}));
this.container.delegate(selector, "mousedown", this.bind(function (e) {
if (!this.enabled) return;
if ($(e.target).closest(".select2-search-choice").length > 0) {
// clicked inside a select2 search choice, do not open
return;
}
this.clearPlaceholder();
this.open();
this.focusSearch();
e.preventDefault();
}));
this.container.delegate(selector, "focus", this.bind(function () {
if (!this.enabled) return;
this.container.addClass("select2-container-active");
this.dropdown.addClass("select2-drop-active");
this.clearPlaceholder();
}));
// set the placeholder if necessary
this.clearSearch();
},
// multi
enable: function() {
if (this.enabled) return;
this.parent.enable.apply(this, arguments);
this.search.removeAttr("disabled");
},
// multi
disable: function() {
if (!this.enabled) return;
this.parent.disable.apply(this, arguments);
this.search.attr("disabled", true);
},
// multi
initSelection: function () {
var data;
if (this.opts.element.val() === "") {
this.updateSelection([]);
this.close();
// set the placeholder if necessary
this.clearSearch();
}
if (this.select || this.opts.element.val() !== "") {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(data){
if (data !== undefined && data !== null) {
self.updateSelection(data);
self.close();
// set the placeholder if necessary
self.clearSearch();
}
});
}
},
// multi
clearSearch: function () {
var placeholder = this.getPlaceholder();
if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
this.search.val(placeholder).addClass("select2-default");
// stretch the search box to full width of the container so as much of the placeholder is visible as possible
this.resizeSearch();
} else {
// we set this to " " instead of "" and later clear it on focus() because there is a firefox bug
// that does not properly render the caret when the field starts out blank
this.search.val(" ").width(10);
}
},
// multi
clearPlaceholder: function () {
if (this.search.hasClass("select2-default")) {
this.search.val("").removeClass("select2-default");
} else {
// work around for the space character we set to avoid firefox caret bug
if (this.search.val() === " ") this.search.val("");
}
},
// multi
opening: function () {
this.parent.opening.apply(this, arguments);
this.clearPlaceholder();
this.resizeSearch();
this.focusSearch();
},
// multi
close: function () {
if (!this.opened()) return;
this.parent.close.apply(this, arguments);
},
// multi
focus: function () {
this.close();
this.search.focus();
},
// multi
isFocused: function () {
return this.search.hasClass("select2-focused");
},
// multi
updateSelection: function (data) {
var ids = [], filtered = [], self = this;
// filter out duplicates
$(data).each(function () {
if (indexOf(self.id(this), ids) < 0) {
ids.push(self.id(this));
filtered.push(this);
}
});
data = filtered;
this.selection.find(".select2-search-choice").remove();
$(data).each(function () {
self.addSelectedChoice(this);
});
self.postprocessResults();
},
tokenize: function() {
var input = this.search.val();
input = this.opts.tokenizer(input, this.data(), this.bind(this.onSelect), this.opts);
if (input != null && input != undefined) {
this.search.val(input);
if (input.length > 0) {
this.open();
}
}
},
// multi
onSelect: function (data) {
this.addSelectedChoice(data);
if (this.select) { this.postprocessResults(); }
if (this.opts.closeOnSelect) {
this.close();
this.search.width(10);
} else {
if (this.countSelectableResults()>0) {
this.search.width(10);
this.resizeSearch();
this.positionDropdown();
} else {
// if nothing left to select close
this.close();
}
}
// since its not possible to select an element that has already been
// added we do not need to check if this is a new element before firing change
this.triggerChange({ added: data });
this.focusSearch();
},
// multi
cancel: function () {
this.close();
this.focusSearch();
},
// multi
addSelectedChoice: function (data) {
var choice=$(
"<li class='select2-search-choice'>" +
" <div></div>" +
" <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
"</li>"),
id = this.id(data),
val = this.getVal(),
formatted;
formatted=this.opts.formatSelection(data, choice);
choice.find("div").replaceWith("<div>"+this.opts.escapeMarkup(formatted)+"</div>");
choice.find(".select2-search-choice-close")
.bind("mousedown", killEvent)
.bind("click dblclick", this.bind(function (e) {
if (!this.enabled) return;
$(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
this.unselect($(e.target));
this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
this.close();
this.focusSearch();
})).dequeue();
killEvent(e);
})).bind("focus", this.bind(function () {
if (!this.enabled) return;
this.container.addClass("select2-container-active");
this.dropdown.addClass("select2-drop-active");
}));
choice.data("select2-data", data);
choice.insertBefore(this.searchContainer);
val.push(id);
this.setVal(val);
},
// multi
unselect: function (selected) {
var val = this.getVal(),
data,
index;
selected = selected.closest(".select2-search-choice");
if (selected.length === 0) {
throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
}
data = selected.data("select2-data");
index = indexOf(this.id(data), val);
if (index >= 0) {
val.splice(index, 1);
this.setVal(val);
if (this.select) this.postprocessResults();
}
selected.remove();
this.triggerChange({ removed: data });
},
// multi
postprocessResults: function () {
var val = this.getVal(),
choices = this.results.find(".select2-result-selectable"),
compound = this.results.find(".select2-result-with-children"),
self = this;
choices.each2(function (i, choice) {
var id = self.id(choice.data("select2-data"));
if (indexOf(id, val) >= 0) {
choice.addClass("select2-disabled").removeClass("select2-result-selectable");
} else {
choice.removeClass("select2-disabled").addClass("select2-result-selectable");
}
});
compound.each2(function(i, e) {
if (e.find(".select2-result-selectable").length==0) {
e.addClass("select2-disabled");
} else {
e.removeClass("select2-disabled");
}
});
choices.each2(function (i, choice) {
if (!choice.hasClass("select2-disabled") && choice.hasClass("select2-result-selectable")) {
self.highlight(0);
return false;
}
});
},
// multi
resizeSearch: function () {
var minimumWidth, left, maxWidth, containerLeft, searchWidth,
sideBorderPadding = getSideBorderPadding(this.search);
minimumWidth = measureTextWidth(this.search) + 10;
left = this.search.offset().left;
maxWidth = this.selection.width();
containerLeft = this.selection.offset().left;
searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
if (searchWidth < minimumWidth) {
searchWidth = maxWidth - sideBorderPadding;
}
if (searchWidth < 40) {
searchWidth = maxWidth - sideBorderPadding;
}
this.search.width(searchWidth);
},
// multi
getVal: function () {
var val;
if (this.select) {
val = this.select.val();
return val === null ? [] : val;
} else {
val = this.opts.element.val();
return splitVal(val, this.opts.separator);
}
},
// multi
setVal: function (val) {
var unique;
if (this.select) {
this.select.val(val);
} else {
unique = [];
// filter out duplicates
$(val).each(function () {
if (indexOf(this, unique) < 0) unique.push(this);
});
this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
}
},
// multi
val: function () {
var val, data = [], self=this;
if (arguments.length === 0) {
return this.getVal();
}
val = arguments[0];
if (!val) {
this.opts.element.val("");
this.updateSelection([]);
this.clearSearch();
return;
}
// val is a list of ids
this.setVal(val);
if (this.select) {
this.select.find(":selected").each(function () {
data.push({id: $(this).attr("value"), text: $(this).text()});
});
this.updateSelection(data);
} else {
if (this.opts.initSelection === undefined) {
throw new Error("val() cannot be called if initSelection() is not defined")
}
this.opts.initSelection(this.opts.element, function(data){
var ids=$(data).map(self.id);
self.setVal(ids);
self.updateSelection(data);
self.clearSearch();
});
}
this.clearSearch();
},
// multi
onSortStart: function() {
if (this.select) {
throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
}
// collapse search field into 0 width so its container can be collapsed as well
this.search.width(0);
// hide the container
this.searchContainer.hide();
},
// multi
onSortEnd:function() {
var val=[], self=this;
// show search and move it to the end of the list
this.searchContainer.show();
// make sure the search container is the last item in the list
this.searchContainer.appendTo(this.searchContainer.parent());
// since we collapsed the width in dragStarted, we resize it here
this.resizeSearch();
// update selection
this.selection.find(".select2-search-choice").each(function() {
val.push(self.opts.id($(this).data("select2-data")));
});
this.setVal(val);
this.triggerChange();
},
// multi
data: function(values) {
var self=this, ids;
if (arguments.length === 0) {
return this.selection
.find(".select2-search-choice")
.map(function() { return $(this).data("select2-data"); })
.get();
} else {
if (!values) { values = []; }
ids = $.map(values, function(e) { return self.opts.id(e)});
this.setVal(ids);
this.updateSelection(values);
this.clearSearch();
}
}
});
$.fn.select2 = function () {
var args = Array.prototype.slice.call(arguments, 0),
opts,
select2,
value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
this.each(function () {
if (args.length === 0 || typeof(args[0]) === "object") {
opts = args.length === 0 ? {} : $.extend({}, args[0]);
opts.element = $(this);
if (opts.element.get(0).tagName.toLowerCase() === "select") {
multiple = opts.element.attr("multiple");
} else {
multiple = opts.multiple || false;
if ("tags" in opts) {opts.multiple = multiple = true;}
}
select2 = multiple ? new MultiSelect2() : new SingleSelect2();
select2.init(opts);
} else if (typeof(args[0]) === "string") {
if (indexOf(args[0], allowedMethods) < 0) {
throw "Unknown method: " + args[0];
}
value = undefined;
select2 = $(this).data("select2");
if (select2 === undefined) return;
if (args[0] === "container") {
value=select2.container;
} else {
value = select2[args[0]].apply(select2, args.slice(1));
}
if (value !== undefined) {return false;}
} else {
throw "Invalid arguments to select2 plugin: " + args;
}
});
return (value === undefined) ? this : value;
};
// plugin defaults, accessible to users
$.fn.select2.defaults = {
width: "copy",
closeOnSelect: true,
openOnEnter: true,
containerCss: {},
dropdownCss: {},
containerCssClass: "",
dropdownCssClass: "",
formatResult: function(result, container, query) {
var markup=[];
markMatch(result.text, query.term, markup);
return markup.join("");
},
formatSelection: function (data, container) {
return data ? data.text : undefined;
},
formatResultCssClass: function(data) {return undefined;},
formatNoMatches: function () { return "No matches found"; },
formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
formatLoadMore: function (pageNumber) { return "Loading more results..."; },
formatSearching: function () { return "Searching..."; },
minimumResultsForSearch: 0,
minimumInputLength: 0,
maximumSelectionSize: 0,
id: function (e) { return e.id; },
matcher: function(term, text) {
return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
},
separator: ",",
tokenSeparators: [],
tokenizer: defaultTokenizer,
escapeMarkup: function (markup) {
if (markup && typeof(markup) === "string") {
return markup.replace(/&/g, "&");
}
return markup;
},
blurOnChange: false
};
// exports
window.Select2 = {
query: {
ajax: ajax,
local: local,
tags: tags
}, util: {
debounce: debounce,
markMatch: markMatch
}, "class": {
"abstract": AbstractSelect2,
"single": SingleSelect2,
"multi": MultiSelect2
}
};
}(jQuery));
|
export default {
el: {
colorpicker: {
confirm: 'OK',
clear: 'Очистить'
},
datepicker: {
now: 'Сейчас',
today: 'Сегодня',
cancel: 'Отмена',
clear: 'Очистить',
confirm: 'OK',
selectDate: 'Выбрать дату',
selectTime: 'Выбрать время',
startDate: 'Дата начала',
startTime: 'Время начала',
endDate: 'Дата окончания',
endTime: 'Время окончания',
prevYear: 'Предыдущий год',
nextYear: 'Следующий год',
prevMonth: 'Предыдущий месяц',
nextMonth: 'Следующий месяц',
year: '',
month1: 'Январь',
month2: 'Февраль',
month3: 'Март',
month4: 'Апрель',
month5: 'Май',
month6: 'Июнь',
month7: 'Июль',
month8: 'Август',
month9: 'Сентябрь',
month10: 'Октябрь',
month11: 'Ноябрь',
month12: 'Декабрь',
// week: 'week',
weeks: {
sun: 'Вс',
mon: 'Пн',
tue: 'Вт',
wed: 'Ср',
thu: 'Чт',
fri: 'Пт',
sat: 'Сб'
},
months: {
jan: 'Янв',
feb: 'Фев',
mar: 'Мар',
apr: 'Апр',
may: 'Май',
jun: 'Июн',
jul: 'Июл',
aug: 'Авг',
sep: 'Сен',
oct: 'Окт',
nov: 'Ноя',
dec: 'Дек'
}
},
select: {
loading: 'Загрузка',
noMatch: 'Совпадений не найдено',
noData: 'Нет данных',
placeholder: 'Выбрать'
},
cascader: {
noMatch: 'Совпадений не найдено',
loading: 'Загрузка',
placeholder: 'Выбрать'
},
pagination: {
goto: 'Перейти',
pagesize: 'на странице',
total: 'Всего {total}',
pageClassifier: ''
},
messagebox: {
title: 'Сообщение',
confirm: 'OK',
cancel: 'Отмена',
error: 'Недопустимый ввод данных'
},
upload: {
deleteTip: 'Нажмите [Удалить] для удаления',
delete: 'Удалить',
preview: 'Превью',
continue: 'Продолжить'
},
table: {
emptyText: 'Нет данных',
confirmFilter: 'Подтвердить',
resetFilter: 'Сбросить',
clearFilter: 'Все',
sumText: 'Сумма'
},
tree: {
emptyText: 'Нет данных'
},
transfer: {
noMatch: 'Совпадений не найдено',
noData: 'Нет данных',
titles: ['Список 1', 'Список 2'],
filterPlaceholder: 'Введите ключевое слово',
noCheckedFormat: '{total} пунктов',
hasCheckedFormat: '{checked}/{total} выбрано'
}
}
};
|
'use strict';
angular.module('sandstone.slurm')
.directive('saDuration', function (){
return {
restrict: 'A',
require: 'ngModel',
scope: {
minDuration: '=',
maxDuration: '='
},
link: function($scope, elem, attr, ngModel) {
var isValid = function(duration) {
var cmps;
var min = parseInt($scope.minDuration, 10);
var max = parseInt($scope.maxDuration, 10);
var valid, validMin, validMax;
valid = validMin = validMax = false;
try {
cmps = duration.split(/\:|\-/).reverse();
} catch(err) {
return false;
}
var mins = 0;
if (cmps.length === 1) {
// MM
mins += parseInt(cmps[0],10);
} else {
// ...:SS
var secs = parseFloat(cmps[0]) / 60.0;
mins += parseInt(secs);
}
if (cmps.length > 1) {
// MM:SS
mins += parseInt(cmps[1],10);
}
if (cmps.length > 2) {
// HH:MM:SS
mins += 60 * parseInt(cmps[2],10);
}
if (cmps.length > 3) {
// DD-HH:MM:SS
mins += 1440 * parseInt(cmps[3],10);
}
if ((typeof min !== 'undefined') && (!isNaN(min))) {
validMin = min <= mins;
} else {
validMin = true;
}
if ((typeof max !== 'undefined') && (!isNaN(max))) {
validMax = mins <= max;
} else {
validMax = true;
}
valid = validMin && validMax;
return valid;
};
ngModel.$parsers.unshift(function(value) {
var valid = isValid(value);
ngModel.$setValidity('saDuration', valid);
return valid ? value : undefined;
});
ngModel.$formatters.unshift(function(value) {
var valid = isValid(value);
ngModel.$setValidity('saDuration', valid);
return value;
});
}
};
});
|
var async = require('async');
describe('addCommand', function() {
before(h.setupMultibrowser());
before(function(done) {
var self = this;
this.matrix.addCommand('getUrlAndTitle', function(callback) {
var result = {},
error;
this.url(function(err, url) {
error = err;
result.url = url.browserA.value;
})
.getTitle(function(err, title) {
error = err;
result.title = title.browserB;
})
.pause(1000)
.call(callback.bind(this, error, result));
});
this.browserA.url(conf.testPage.subPage);
this.browserB.url(conf.testPage.start);
this.matrix.call(done);
});
it('added a `getUrlAndTitle` command', function(done) {
this.matrix
.getUrlAndTitle(function(err, result) {
assert.ifError(err);
assert.strictEqual(result.url, conf.testPage.subPage);
assert.strictEqual(result.title, conf.testPage.title);
})
.call(done);
});
it('should promisify added command', function(done) {
this.matrix
.getUrlAndTitle().then(function(result) {
assert.strictEqual(result.url, conf.testPage.subPage);
assert.strictEqual(result.title, conf.testPage.title);
})
.call(done);
});
it('should not register that command to other instances', function() {
assert.ifError(this.browserA.getUrlAndTitle);
assert.ifError(this.browserB.getUrlAndTitle);
});
}); |
/*
## To write to the benchmark csv
```bash
mocha test/c1_eventemitter_security_benchmarks.js.js | grep ^CSV | awk 'END {print ""} {printf "%i %s,", $2, $NF}' >> test/c1_eventemitter_security_benchmarks.js.csv
```
To also see it.
nother console
```
tail -f test/.e2e_eventemitter_embedded_benchmarks.csv
```
*/
var expect = require('expect.js');
var happn = require('../../lib/index');
var service = happn.service;
var happn_client = happn.client;
var async = require('async');
var HAPPNER_STOP_DELAY = 5000;
describe('c1_eventemitter_security_benchmarks.js', function() {
var testport = 8000;
var test_secret = 'test_secret';
var mode = "embedded";
var default_timeout = 100000;
var happnInstance = null;
before('should initialize the service', function(callback) {
this.timeout(20000);
try {
service.create({
secure:true,
mode: 'embedded',
services: {
auth: {
path: './services/auth/service.js',
config: {
authTokenSecret: 'a256a2fd43bf441483c5177fc85fd9d3',
systemSecret: test_secret
}
},
data: {
path: './services/data_embedded/service.js',
config: {}
},
pubsub: {
path: './services/pubsub/service.js'
}
},
utils: {
log_level: 'info|error|warning',
log_component: 'prepare'
}
},
function(e, happn) {
if (e)
return callback(e);
happnInstance = happn;
callback();
});
} catch (e) {
callback(e);
}
});
after(function(done) {
this.timeout(HAPPNER_STOP_DELAY + 5000);
happnInstance.stop(function(e){
setTimeout(function(){
done(e);
}, HAPPNER_STOP_DELAY)
});
});
var publisherclient;
var listenerclient;
it('should initialize the clients', function(callback) {
this.timeout(default_timeout);
try {
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
secure:true,
plugin: happn.client_plugins.intra_process,
context: happnInstance
}, function(e, instance) {
if (e) return callback(e);
publisherclient = instance;
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
secure:true,
plugin: happn.client_plugins.intra_process,
context: happnInstance
}, function(e, instance) {
if (e) return callback(e);
listenerclient = instance;
callback();
});
});
} catch (e) {
callback(e);
}
});
it('should handle sequences of events by writing as soon as possible -slow?', function(callback) {
this.timeout(default_timeout);
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
plugin: happn.client_plugins.intra_process,
context: happnInstance,
secure:true,
},
function(e, stressTestClient) {
if (e) return callback(e);
var count = 0;
var expected = 1000;
var receivedCount = 0;
var timerName = 'CSV.colm 1 ' + expected + 'Events - no wait';
var writeData = function() {
if (count == expected) return;
publisherclient.set('/e2e_test1/testsubscribe/sequence5', {
property1: count++
}, {
excludeId: true
}, function(e, result) {
writeData();
});
}
stressTestClient.on('/e2e_test1/testsubscribe/sequence5', {
event_type: 'set',
count: 0
}, function(message) {
receivedCount++;
if (receivedCount == expected) {
console.timeEnd(timerName);
callback();
}
},
function(e) {
if (!e) {
console.time(timerName);
writeData();
} else
callback(e);
});
});
});
it('should handle sequences of events by when the previous one is done, without storing', function(callback) {
this.timeout(default_timeout);
var count = 0;
var expected = 1000;
var receivedCount = 0;
var timerName = 'CSV.colm 2 ' + expected + 'Events - no store';
var writeData = function() {
if (receivedCount == expected) return;
////////console.log('putting data: ', count);
publisherclient.set('/e2e_test1/testsubscribe/sequence3', {
property1: receivedCount
}, {
noStore: true
},
function(e, result) {
if (e)
return callback(e);
//////console.log('put data: ', result);
});
}
//path, event_type, count, handler, done
//first listen for the change
listenerclient.on('/e2e_test1/testsubscribe/sequence3', {
event_type: 'set',
count: 0
}, function(message) {
receivedCount++;
if (receivedCount == expected) {
console.timeEnd(timerName);
callback();
} else
writeData();
}, function(e) {
if (!e) {
console.time(timerName);
writeData();
} else
callback(e);
});
});
it('should handle sequences of events by writing each one after each other asap, without storing', function(callback) {
this.timeout(default_timeout);
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
plugin: happn.client_plugins.intra_process,
context: happnInstance,
secure:true,
},
function(e, stressTestClient) {
if (e) return callback(e);
var count = 0;
var expected = 1000;
var receivedCount = 0;
var timerName = 'CSV.colm 3 ' + expected + 'Events - no wait - no store';
stressTestClient.on('/e2e_test1/testsubscribe/sequence1', {
event_type: 'set',
count: 0
},
function(message) {
receivedCount++;
if (receivedCount == expected) {
console.timeEnd(timerName);
callback();
}
}, function(e) {
if (!e) {
console.time(timerName);
function writeData() {
if (count == expected) {
return;
}
publisherclient.set('/e2e_test1/testsubscribe/sequence1', {
property1: count++
}, {
noStore: true
}, function(e, result) {
writeData();
});
}
writeData();
} else
callback(e);
});
});
});
it('should handle sequences of events by writing each one after each other asap, without storing - deferring setImmediate every 100', function(callback) {
this.timeout(default_timeout);
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
plugin: happn.client_plugins.intra_process,
context: happnInstance,
secure:true,
},
function(e, stressTestClient) {
if (e) return callback(e);
var count = 0;
var expected = 1000;
var receivedCount = 0;
var timerName = 'CSV.colm 3 ' + expected + 'Events - no wait - no store';
stressTestClient.on('/e2e_test1/testsubscribe/sequence1', {
event_type: 'set',
count: 0,
config: {
deferSetImmediate: 100
}
}, function(message, meta) {
////console.log(message, meta);
receivedCount++;
if (receivedCount == expected) {
console.timeEnd(timerName);
callback();
}
},
function(e) {
if (!e) {
console.time(timerName);
function writeData() {
if (count == expected) {
return;
}
publisherclient.set('/e2e_test1/testsubscribe/sequence1', {
property1: count++
}, {
noStore: true
}, function(e, result) {
writeData();
});
}
writeData();
} else
callback(e);
});
});
});
it('should handle sequences of events by writing as soon as possible - not persisting, using noStore - and ensure the events push the correct data values back', function(callback) {
this.timeout(default_timeout);
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
plugin: happn.client_plugins.intra_process,
context: happnInstance,
secure:true,
},
function(e, stressTestClient) {
if (e) return callback(e);
setTimeout(function() {
var count = 0;
var expected = 1000;
var timerName = 'CSV.colm 4 testTime1';
var receivedCount = 0;
var received = {};
var sent = [expected];
for (var i = 0; i < expected; i++) {
sent[i] = require('shortid').generate();
}
stressTestClient.on('/e2e_test1/testsubscribe/sequence_nostore', {
event_type: 'set',
count: 0
},
function(message) {
receivedCount++;
if (received[message.property1])
received[message.property1] = received[message.property1] + 1;
else
received[message.property1] = 1;
if (receivedCount == sent.length) {
console.timeEnd(timerName);
expect(Object.keys(received).length == expected).to.be(true);
callback();
}
},
function(e) {
if (!e) {
expect(stressTestClient.events['/SET@/e2e_test1/testsubscribe/sequence_nostore'].length).to.be(1);
console.time(timerName);
while (count < expected) {
publisherclient.set('/e2e_test1/testsubscribe/sequence_nostore', {
property1: sent[count]
}, {
noStore: true
}, function(e, result) {
if (e)
return callback(e);
});
count++;
}
} else callback(e);
});
}, 2000)
});
});
it('should handle sequences of events by writing as soon as possible - persisting, and ensure the events push the correct data values back', function(callback) {
this.timeout(default_timeout);
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
plugin: happn.client_plugins.intra_process,
context: happnInstance,
secure:true,
},
function(e, stressTestClient) {
if (e) return callback(e);
var count = 0;
var timerName = 'CSV.colm 5 testTime2';
var expected = 1000;
var receivedCount = 0;
var received = {};
var sent = [];
for (var i = 0; i < expected; i++) {
sent[i] = require('shortid').generate();
}
stressTestClient.on('/e2e_test1/testsubscribe/sequence_persist', {event_type:'set',count:0},
function(message) {
////console.log(message);
receivedCount++;
if (received[message.property1])
received[message.property1] = received[message.property1] + 1;
else
received[message.property1] = 1;
if (receivedCount == sent.length) {
console.timeEnd(timerName);
////console.log(received);
expect(Object.keys(received).length == expected).to.be(true);
callback();
}
},
function(e) {
if (e) return callback(e);
expect(stressTestClient.events['/SET@/e2e_test1/testsubscribe/sequence_persist'].length).to.be(1);
console.time(timerName);
while (count < expected) {
publisherclient.set('/e2e_test1/testsubscribe/sequence_persist', {property1: sent[count]}, {},
function(e, result) {
if (e) return callback(e);
});
count++;
}
});
});
});
it('should handle sequences of events by writing as soon as possible', function(callback) {
this.timeout(default_timeout);
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
plugin: happn.client_plugins.intra_process,
context: happnInstance,
secure:true,
},
function(e, stressTestClient) {
if (e) return callback(e);
var count = 0;
var expected = 1000;
var receivedCount = 0;
var timerName = 'CSV.colm 6 ' + expected + 'Events - no wait';
stressTestClient.on('/e2e_test1/testsubscribe/sequence4', {
event_type: 'set',
count: 0
}, function(message) {
receivedCount++;
if (receivedCount == expected) {
console.timeEnd(timerName);
callback();
}
}, function(e) {
if (!e) {
console.time(timerName);
writeData();
} else
callback(e);
});
function writeData() {
if (count == expected) return;
publisherclient.set('/e2e_test1/testsubscribe/sequence4', {
property1: count++
}, {
excludeId: true
}, function(e, result) {
writeData();
});
}
});
});
it('should handle sequences of events by when the previous one is done', function(callback) {
this.timeout(default_timeout);
var count = 0;
var expected = 1000;
var receivedCount = 0;
var timerName = 'CSV.colm 7 ' + expected + 'Events';
listenerclient.on('/e2e_test1/testsubscribe/sequence32', {
event_type: 'set',
count: 0
}, function(message) {
receivedCount++;
if (receivedCount == expected) {
console.timeEnd(timerName);
callback();
}
}, function(e) {
if (!e) {
console.time(timerName);
writeData();
} else
callback(e);
});
function writeData() {
if (count == expected) return;
publisherclient.set('/e2e_test1/testsubscribe/sequence32', {
property1: count++
}, {
excludeId: true
}, function(e, result) {
writeData();
});
}
});
it('should handle sequences of events by writing as soon as possible -slow?', function(callback) {
this.timeout(default_timeout);
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
plugin: happn.client_plugins.intra_process,
context: happnInstance,
secure:true,
},
function(e, stressTestClient) {
if (e) return callback(e);
var count = 0;
var expected = 1000;
var receivedCount = 0;
var timerName = 'CSV.colm 8 ' + expected + 'Events - no wait';
var writeData = function() {
if (count == expected) return;
publisherclient.set('/e2e_test1/testsubscribe/sequence5', {
property1: count++
}, {
excludeId: true
}, function(e, result) {
writeData();
});
}
stressTestClient.on('/e2e_test1/testsubscribe/sequence5', {
event_type: 'set',
count: 0
}, function(message) {
receivedCount++;
if (receivedCount == expected) {
console.timeEnd(timerName);
callback();
}
}, function(e) {
if (!e) {
console.time(timerName);
writeData();
} else
callback(e);
});
});
});
it('should handle sequences of events by when the previous one is done', function(callback) {
this.timeout(default_timeout);
var count = 0;
var expected = 1000;
var receivedCount = 0;
var timerName = 'CSV.colm 9 ' + expected + 'Events';
listenerclient.on('/e2e_test1/testsubscribe/sequence31', {
event_type: 'set',
count: 0
}, function(message) {
receivedCount++;
if (receivedCount == expected) {
console.timeEnd(timerName);
callback();
}
}, function(e) {
function writeData() {
if (count == expected) return;
publisherclient.set('/e2e_test1/testsubscribe/sequence31', {
property1: count++
}, {
excludeId: true
}, function(e, result) {
writeData();
});
}
if (!e) {
console.time(timerName);
writeData();
} else
callback(e);
});
});
it('should handle sequences of events by writing as soon as possible -slow?', function(callback) {
this.timeout(default_timeout);
happn_client.create({
config:{username:'_ADMIN', password:'happn'},
plugin: happn.client_plugins.intra_process,
context: happnInstance,
secure:true,
},
function(e, stressTestClient) {
if (e) return callback(e);
var count = 0;
var expected = 1000;
var receivedCount = 0;
var timerName = 'CSV.colm 10 ' + expected + 'Events - no wait';
var writeData = function() {
if (count == expected) return;
publisherclient.set('/e2e_test1/testsubscribe/sequence5', {
property1: count++
}, {
excludeId: true
}, function(e, result) {
writeData();
});
}
stressTestClient.on('/e2e_test1/testsubscribe/sequence5', {
event_type: 'set',
count: 0
}, function(message) {
receivedCount++;
if (receivedCount == expected) {
console.timeEnd(timerName);
callback();
}
}, function(e) {
if (!e) {
console.time(timerName);
writeData();
} else
callback(e);
});
});
});
}); |
// flow-typed signature: d6d0cc53e665766936940cec9fd7b7e0
// flow-typed version: <<STUB>>/run-sequence_v^1.0.2/flow_v0.35.0
/**
* This is an autogenerated libdef stub for:
*
* 'run-sequence'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'run-sequence' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module 'run-sequence/index' {
declare module.exports: $Exports<'run-sequence'>;
}
declare module 'run-sequence/index.js' {
declare module.exports: $Exports<'run-sequence'>;
}
|
export const AUTH_SIGNIN = 'AUTH_SIGNIN';
export const AUTH_SIGNOUT = 'AUTH_SIGNOUT';
export const signIn = (token) => {
localStorage.setItem('token', token);
return { type: AUTH_SIGNIN };
};
export const signOut = () => {
localStorage.removeItem('token');
return { type: AUTH_SIGNOUT };
};
|
Schemas = {}; |
(function(){
var nv = window.nv || {};
nv.version = '1.1.15b';
nv.dev = true //set false when in production
window.nv = nv;
nv.tooltip = nv.tooltip || {}; // For the tooltip system
nv.utils = nv.utils || {}; // Utility subsystem
nv.models = nv.models || {}; //stores all the possible models/components
nv.charts = {}; //stores all the ready to use charts
nv.graphs = []; //stores all the graphs currently on the page
nv.logs = {}; //stores some statistics and potential error messages
nv.dispatch = d3.dispatch('render_start', 'render_end');
// *************************************************************************
// Development render timers - disabled if dev = false
if (nv.dev) {
nv.dispatch.on('render_start', function(e) {
nv.logs.startTime = +new Date();
});
nv.dispatch.on('render_end', function(e) {
nv.logs.endTime = +new Date();
nv.logs.totalTime = nv.logs.endTime - nv.logs.startTime;
nv.log('total', nv.logs.totalTime); // used for development, to keep track of graph generation times
});
}
// ********************************************
// Public Core NV functions
// Logs all arguments, and returns the last so you can test things in place
// Note: in IE8 console.log is an object not a function, and if modernizr is used
// then calling Function.prototype.bind with with anything other than a function
// causes a TypeError to be thrown.
nv.log = function() {
if (nv.dev && console.log && console.log.apply)
console.log.apply(console, arguments)
else if (nv.dev && typeof console.log == "function" && Function.prototype.bind) {
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
}
return arguments[arguments.length - 1];
};
nv.render = function render(step) {
step = step || 1; // number of graphs to generate in each timeout loop
nv.render.active = true;
nv.dispatch.render_start();
setTimeout(function() {
var chart, graph;
for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) {
chart = graph.generate();
if (typeof graph.callback == typeof(Function)) graph.callback(chart);
nv.graphs.push(chart);
}
nv.render.queue.splice(0, i);
if (nv.render.queue.length) setTimeout(arguments.callee, 0);
else {
nv.dispatch.render_end();
nv.render.active = false;
}
}, 0);
};
nv.render.active = false;
nv.render.queue = [];
nv.addGraph = function(obj) {
if (typeof arguments[0] === typeof(Function))
obj = {generate: arguments[0], callback: arguments[1]};
nv.render.queue.push(obj);
if (!nv.render.active) nv.render();
};
nv.identity = function(d) { return d; };
nv.strip = function(s) { return s.replace(/(\s|&)/g,''); };
function daysInMonth(month,year) {
return (new Date(year, month+1, 0)).getDate();
}
function d3_time_range(floor, step, number) {
return function(t0, t1, dt) {
var time = floor(t0), times = [];
if (time < t0) step(time);
if (dt > 1) {
while (time < t1) {
var date = new Date(+time);
if ((number(date) % dt === 0)) times.push(date);
step(time);
}
} else {
while (time < t1) { times.push(new Date(+time)); step(time); }
}
return times;
};
}
d3.time.monthEnd = function(date) {
return new Date(date.getFullYear(), date.getMonth(), 0);
};
d3.time.monthEnds = d3_time_range(d3.time.monthEnd, function(date) {
date.setUTCDate(date.getUTCDate() + 1);
date.setDate(daysInMonth(date.getMonth() + 1, date.getFullYear()));
}, function(date) {
return date.getMonth();
}
);
/* Utility class to handle creation of an interactive layer.
This places a rectangle on top of the chart. When you mouse move over it, it sends a dispatch
containing the X-coordinate. It can also render a vertical line where the mouse is located.
dispatch.elementMousemove is the important event to latch onto. It is fired whenever the mouse moves over
the rectangle. The dispatch is given one object which contains the mouseX/Y location.
It also has 'pointXValue', which is the conversion of mouseX to the x-axis scale.
*/
nv.interactiveGuideline = function() {
"use strict";
var tooltip = nv.models.tooltip();
//Public settings
var width = null
, height = null
//Please pass in the bounding chart's top and left margins
//This is important for calculating the correct mouseX/Y positions.
, margin = {left: 0, top: 0}
, xScale = d3.scale.linear()
, yScale = d3.scale.linear()
, dispatch = d3.dispatch('elementMousemove', 'elementMouseout','elementDblclick')
, showGuideLine = true
, svgContainer = null
//Must pass in the bounding chart's <svg> container.
//The mousemove event is attached to this container.
;
//Private variables
var isMSIE = navigator.userAgent.indexOf("MSIE") !== -1 //Check user-agent for Microsoft Internet Explorer.
;
function layer(selection) {
selection.each(function(data) {
var container = d3.select(this);
var availableWidth = (width || 960), availableHeight = (height || 400);
var wrap = container.selectAll("g.nv-wrap.nv-interactiveLineLayer").data([data]);
var wrapEnter = wrap.enter()
.append("g").attr("class", " nv-wrap nv-interactiveLineLayer");
wrapEnter.append("g").attr("class","nv-interactiveGuideLine");
if (!svgContainer) {
return;
}
function mouseHandler() {
var d3mouse = d3.mouse(this);
var mouseX = d3mouse[0];
var mouseY = d3mouse[1];
var subtractMargin = true;
var mouseOutAnyReason = false;
if (isMSIE) {
/*
D3.js (or maybe SVG.getScreenCTM) has a nasty bug in Internet Explorer 10.
d3.mouse() returns incorrect X,Y mouse coordinates when mouse moving
over a rect in IE 10.
However, d3.event.offsetX/Y also returns the mouse coordinates
relative to the triggering <rect>. So we use offsetX/Y on IE.
*/
mouseX = d3.event.offsetX;
mouseY = d3.event.offsetY;
/*
On IE, if you attach a mouse event listener to the <svg> container,
it will actually trigger it for all the child elements (like <path>, <circle>, etc).
When this happens on IE, the offsetX/Y is set to where ever the child element
is located.
As a result, we do NOT need to subtract margins to figure out the mouse X/Y
position under this scenario. Removing the line below *will* cause
the interactive layer to not work right on IE.
*/
if(d3.event.target.tagName !== "svg")
subtractMargin = false;
if (d3.event.target.className.baseVal.match("nv-legend"))
mouseOutAnyReason = true;
}
if(subtractMargin) {
mouseX -= margin.left;
mouseY -= margin.top;
}
/* If mouseX/Y is outside of the chart's bounds,
trigger a mouseOut event.
*/
if (mouseX < 0 || mouseY < 0
|| mouseX > availableWidth || mouseY > availableHeight
|| (d3.event.relatedTarget && d3.event.relatedTarget.ownerSVGElement === undefined)
|| mouseOutAnyReason
)
{
if (isMSIE) {
if (d3.event.relatedTarget
&& d3.event.relatedTarget.ownerSVGElement === undefined
&& d3.event.relatedTarget.className.match(tooltip.nvPointerEventsClass)) {
return;
}
}
dispatch.elementMouseout({
mouseX: mouseX,
mouseY: mouseY
});
layer.renderGuideLine(null); //hide the guideline
return;
}
var pointXValue = xScale.invert(mouseX);
dispatch.elementMousemove({
mouseX: mouseX,
mouseY: mouseY,
pointXValue: pointXValue
});
//If user double clicks the layer, fire a elementDblclick dispatch.
if (d3.event.type === "dblclick") {
dispatch.elementDblclick({
mouseX: mouseX,
mouseY: mouseY,
pointXValue: pointXValue
});
}
}
svgContainer
.on("mousemove",mouseHandler, true)
.on("mouseout" ,mouseHandler,true)
.on("dblclick" ,mouseHandler)
;
//Draws a vertical guideline at the given X postion.
layer.renderGuideLine = function(x) {
if (!showGuideLine) return;
var line = wrap.select(".nv-interactiveGuideLine")
.selectAll("line")
.data((x != null) ? [nv.utils.NaNtoZero(x)] : [], String);
line.enter()
.append("line")
.attr("class", "nv-guideline")
.attr("x1", function(d) { return d;})
.attr("x2", function(d) { return d;})
.attr("y1", availableHeight)
.attr("y2",0)
;
line.exit().remove();
}
});
}
layer.dispatch = dispatch;
layer.tooltip = tooltip;
layer.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return layer;
};
layer.width = function(_) {
if (!arguments.length) return width;
width = _;
return layer;
};
layer.height = function(_) {
if (!arguments.length) return height;
height = _;
return layer;
};
layer.xScale = function(_) {
if (!arguments.length) return xScale;
xScale = _;
return layer;
};
layer.showGuideLine = function(_) {
if (!arguments.length) return showGuideLine;
showGuideLine = _;
return layer;
};
layer.svgContainer = function(_) {
if (!arguments.length) return svgContainer;
svgContainer = _;
return layer;
};
return layer;
};
/* Utility class that uses d3.bisect to find the index in a given array, where a search value can be inserted.
This is different from normal bisectLeft; this function finds the nearest index to insert the search value.
For instance, lets say your array is [1,2,3,5,10,30], and you search for 28.
Normal d3.bisectLeft will return 4, because 28 is inserted after the number 10. But interactiveBisect will return 5
because 28 is closer to 30 than 10.
Unit tests can be found in: interactiveBisectTest.html
Has the following known issues:
* Will not work if the data points move backwards (ie, 10,9,8,7, etc) or if the data points are in random order.
* Won't work if there are duplicate x coordinate values.
*/
nv.interactiveBisect = function (values, searchVal, xAccessor) {
"use strict";
if (! values instanceof Array) return null;
if (typeof xAccessor !== 'function') xAccessor = function(d,i) { return d.x;}
var bisect = d3.bisector(xAccessor).left;
var index = d3.max([0, bisect(values,searchVal) - 1]);
var currentValue = xAccessor(values[index], index);
if (typeof currentValue === 'undefined') currentValue = index;
if (currentValue === searchVal) return index; //found exact match
var nextIndex = d3.min([index+1, values.length - 1]);
var nextValue = xAccessor(values[nextIndex], nextIndex);
if (typeof nextValue === 'undefined') nextValue = nextIndex;
if (Math.abs(nextValue - searchVal) >= Math.abs(currentValue - searchVal))
return index;
else
return nextIndex
};
/*
Returns the index in the array "values" that is closest to searchVal.
Only returns an index if searchVal is within some "threshold".
Otherwise, returns null.
*/
nv.nearestValueIndex = function (values, searchVal, threshold) {
"use strict";
var yDistMax = Infinity, indexToHighlight = null;
values.forEach(function(d,i) {
var delta = Math.abs(searchVal - d);
if ( delta <= yDistMax && delta < threshold) {
yDistMax = delta;
indexToHighlight = i;
}
});
return indexToHighlight;
};/* Tooltip rendering model for nvd3 charts.
window.nv.models.tooltip is the updated,new way to render tooltips.
window.nv.tooltip.show is the old tooltip code.
window.nv.tooltip.* also has various helper methods.
*/
(function() {
"use strict";
window.nv.tooltip = {};
/* Model which can be instantiated to handle tooltip rendering.
Example usage:
var tip = nv.models.tooltip().gravity('w').distance(23)
.data(myDataObject);
tip(); //just invoke the returned function to render tooltip.
*/
window.nv.models.tooltip = function() {
var content = null //HTML contents of the tooltip. If null, the content is generated via the data variable.
, data = null /* Tooltip data. If data is given in the proper format, a consistent tooltip is generated.
Format of data:
{
key: "Date",
value: "August 2009",
series: [
{
key: "Series 1",
value: "Value 1",
color: "#000"
},
{
key: "Series 2",
value: "Value 2",
color: "#00f"
}
]
}
*/
, gravity = 'w' //Can be 'n','s','e','w'. Determines how tooltip is positioned.
, distance = 50 //Distance to offset tooltip from the mouse location.
, snapDistance = 25 //Tolerance allowed before tooltip is moved from its current position (creates 'snapping' effect)
, fixedTop = null //If not null, this fixes the top position of the tooltip.
, classes = null //Attaches additional CSS classes to the tooltip DIV that is created.
, chartContainer = null //Parent DIV, of the SVG Container that holds the chart.
, tooltipElem = null //actual DOM element representing the tooltip.
, position = {left: null, top: null} //Relative position of the tooltip inside chartContainer.
, enabled = true //True -> tooltips are rendered. False -> don't render tooltips.
//Generates a unique id when you create a new tooltip() object
, id = "nvtooltip-" + Math.floor(Math.random() * 100000)
;
//CSS class to specify whether element should not have mouse events.
var nvPointerEventsClass = "nv-pointer-events-none";
//Format function for the tooltip values column
var valueFormatter = function(d,i) {
return d;
};
//Format function for the tooltip header value.
var headerFormatter = function(d) {
return d;
};
//By default, the tooltip model renders a beautiful table inside a DIV.
//You can override this function if a custom tooltip is desired.
var contentGenerator = function(d) {
if (content != null) return content;
if (d == null) return '';
var table = d3.select(document.createElement("table"));
var theadEnter = table.selectAll("thead")
.data([d])
.enter().append("thead");
theadEnter.append("tr")
.append("td")
.attr("colspan",3)
.append("strong")
.classed("x-value",true)
.html(headerFormatter(d.value));
var tbodyEnter = table.selectAll("tbody")
.data([d])
.enter().append("tbody");
var trowEnter = tbodyEnter.selectAll("tr")
.data(function(p) { return p.series})
.enter()
.append("tr")
.classed("highlight", function(p) { return p.highlight})
;
trowEnter.append("td")
.classed("legend-color-guide",true)
.append("div")
.style("background-color", function(p) { return p.color});
trowEnter.append("td")
.classed("key",true)
.html(function(p) {return p.key});
trowEnter.append("td")
.classed("value",true)
.html(function(p,i) { return valueFormatter(p.value,i) });
trowEnter.selectAll("td").each(function(p) {
if (p.highlight) {
var opacityScale = d3.scale.linear().domain([0,1]).range(["#fff",p.color]);
var opacity = 0.6;
d3.select(this)
.style("border-bottom-color", opacityScale(opacity))
.style("border-top-color", opacityScale(opacity))
;
}
});
var html = table.node().outerHTML;
if (d.footer !== undefined)
html += "<div class='footer'>" + d.footer + "</div>";
return html;
};
var dataSeriesExists = function(d) {
if (d && d.series && d.series.length > 0) return true;
return false;
};
//In situations where the chart is in a 'viewBox', re-position the tooltip based on how far chart is zoomed.
function convertViewBoxRatio() {
if (chartContainer) {
var svg = d3.select(chartContainer);
if (svg.node().tagName !== "svg") {
svg = svg.select("svg");
}
var viewBox = (svg.node()) ? svg.attr('viewBox') : null;
if (viewBox) {
viewBox = viewBox.split(' ');
var ratio = parseInt(svg.style('width')) / viewBox[2];
position.left = position.left * ratio;
position.top = position.top * ratio;
}
}
}
//Creates new tooltip container, or uses existing one on DOM.
function getTooltipContainer(newContent) {
var body;
if (chartContainer)
body = d3.select(chartContainer);
else
body = d3.select("body");
var container = body.select(".nvtooltip");
if (container.node() === null) {
//Create new tooltip div if it doesn't exist on DOM.
container = body.append("div")
.attr("class", "nvtooltip " + (classes? classes: "xy-tooltip"))
.attr("id",id)
;
}
container.node().innerHTML = newContent;
container.style("top",0).style("left",0).style("opacity",0);
container.selectAll("div, table, td, tr").classed(nvPointerEventsClass,true)
container.classed(nvPointerEventsClass,true);
return container.node();
}
//Draw the tooltip onto the DOM.
function nvtooltip() {
if (!enabled) return;
if (!dataSeriesExists(data)) return;
convertViewBoxRatio();
var left = position.left;
var top = (fixedTop != null) ? fixedTop : position.top;
var container = getTooltipContainer(contentGenerator(data));
tooltipElem = container;
if (chartContainer) {
var svgComp = chartContainer.getElementsByTagName("svg")[0];
var boundRect = (svgComp) ? svgComp.getBoundingClientRect() : chartContainer.getBoundingClientRect();
var svgOffset = {left:0,top:0};
if (svgComp) {
var svgBound = svgComp.getBoundingClientRect();
var chartBound = chartContainer.getBoundingClientRect();
var svgBoundTop = svgBound.top;
//Defensive code. Sometimes, svgBoundTop can be a really negative
// number, like -134254. That's a bug.
// If such a number is found, use zero instead. FireFox bug only
if (svgBoundTop < 0) {
var containerBound = chartContainer.getBoundingClientRect();
svgBoundTop = (Math.abs(svgBoundTop) > containerBound.height) ? 0 : svgBoundTop;
}
svgOffset.top = Math.abs(svgBoundTop - chartBound.top);
svgOffset.left = Math.abs(svgBound.left - chartBound.left);
}
//If the parent container is an overflow <div> with scrollbars, subtract the scroll offsets.
//You need to also add any offset between the <svg> element and its containing <div>
//Finally, add any offset of the containing <div> on the whole page.
left += chartContainer.offsetLeft + svgOffset.left - 2*chartContainer.scrollLeft;
top += chartContainer.offsetTop + svgOffset.top - 2*chartContainer.scrollTop;
}
if (snapDistance && snapDistance > 0) {
top = Math.floor(top/snapDistance) * snapDistance;
}
nv.tooltip.calcTooltipPosition([left,top], gravity, distance, container);
return nvtooltip;
};
nvtooltip.nvPointerEventsClass = nvPointerEventsClass;
nvtooltip.content = function(_) {
if (!arguments.length) return content;
content = _;
return nvtooltip;
};
//Returns tooltipElem...not able to set it.
nvtooltip.tooltipElem = function() {
return tooltipElem;
};
nvtooltip.contentGenerator = function(_) {
if (!arguments.length) return contentGenerator;
if (typeof _ === 'function') {
contentGenerator = _;
}
return nvtooltip;
};
nvtooltip.data = function(_) {
if (!arguments.length) return data;
data = _;
return nvtooltip;
};
nvtooltip.gravity = function(_) {
if (!arguments.length) return gravity;
gravity = _;
return nvtooltip;
};
nvtooltip.distance = function(_) {
if (!arguments.length) return distance;
distance = _;
return nvtooltip;
};
nvtooltip.snapDistance = function(_) {
if (!arguments.length) return snapDistance;
snapDistance = _;
return nvtooltip;
};
nvtooltip.classes = function(_) {
if (!arguments.length) return classes;
classes = _;
return nvtooltip;
};
nvtooltip.chartContainer = function(_) {
if (!arguments.length) return chartContainer;
chartContainer = _;
return nvtooltip;
};
nvtooltip.position = function(_) {
if (!arguments.length) return position;
position.left = (typeof _.left !== 'undefined') ? _.left : position.left;
position.top = (typeof _.top !== 'undefined') ? _.top : position.top;
return nvtooltip;
};
nvtooltip.fixedTop = function(_) {
if (!arguments.length) return fixedTop;
fixedTop = _;
return nvtooltip;
};
nvtooltip.enabled = function(_) {
if (!arguments.length) return enabled;
enabled = _;
return nvtooltip;
};
nvtooltip.valueFormatter = function(_) {
if (!arguments.length) return valueFormatter;
if (typeof _ === 'function') {
valueFormatter = _;
}
return nvtooltip;
};
nvtooltip.headerFormatter = function(_) {
if (!arguments.length) return headerFormatter;
if (typeof _ === 'function') {
headerFormatter = _;
}
return nvtooltip;
};
//id() is a read-only function. You can't use it to set the id.
nvtooltip.id = function() {
return id;
};
return nvtooltip;
};
//Original tooltip.show function. Kept for backward compatibility.
// pos = [left,top]
nv.tooltip.show = function(pos, content, gravity, dist, parentContainer, classes) {
//Create new tooltip div if it doesn't exist on DOM.
var container = document.createElement('div');
container.className = 'nvtooltip ' + (classes ? classes : 'xy-tooltip');
var body = parentContainer;
if ( !parentContainer || parentContainer.tagName.match(/g|svg/i)) {
//If the parent element is an SVG element, place tooltip in the <body> element.
body = document.getElementsByTagName('body')[0];
}
container.style.left = 0;
container.style.top = 0;
container.style.opacity = 0;
container.innerHTML = content;
body.appendChild(container);
//If the parent container is an overflow <div> with scrollbars, subtract the scroll offsets.
if (parentContainer) {
pos[0] = pos[0] - parentContainer.scrollLeft;
pos[1] = pos[1] - parentContainer.scrollTop;
}
nv.tooltip.calcTooltipPosition(pos, gravity, dist, container);
};
//Looks up the ancestry of a DOM element, and returns the first NON-svg node.
nv.tooltip.findFirstNonSVGParent = function(Elem) {
while(Elem.tagName.match(/^g|svg$/i) !== null) {
Elem = Elem.parentNode;
}
return Elem;
};
//Finds the total offsetTop of a given DOM element.
//Looks up the entire ancestry of an element, up to the first relatively positioned element.
nv.tooltip.findTotalOffsetTop = function ( Elem, initialTop ) {
var offsetTop = initialTop;
do {
if( !isNaN( Elem.offsetTop ) ) {
offsetTop += (Elem.offsetTop);
}
} while( Elem = Elem.offsetParent );
return offsetTop;
};
//Finds the total offsetLeft of a given DOM element.
//Looks up the entire ancestry of an element, up to the first relatively positioned element.
nv.tooltip.findTotalOffsetLeft = function ( Elem, initialLeft) {
var offsetLeft = initialLeft;
do {
if( !isNaN( Elem.offsetLeft ) ) {
offsetLeft += (Elem.offsetLeft);
}
} while( Elem = Elem.offsetParent );
return offsetLeft;
};
//Global utility function to render a tooltip on the DOM.
//pos = [left,top] coordinates of where to place the tooltip, relative to the SVG chart container.
//gravity = how to orient the tooltip
//dist = how far away from the mouse to place tooltip
//container = tooltip DIV
nv.tooltip.calcTooltipPosition = function(pos, gravity, dist, container) {
var height = parseInt(container.offsetHeight),
width = parseInt(container.offsetWidth),
windowWidth = nv.utils.windowSize().width,
windowHeight = nv.utils.windowSize().height,
scrollTop = window.pageYOffset,
scrollLeft = window.pageXOffset,
left, top;
windowHeight = window.innerWidth >= document.body.scrollWidth ? windowHeight : windowHeight - 16;
windowWidth = window.innerHeight >= document.body.scrollHeight ? windowWidth : windowWidth - 16;
gravity = gravity || 's';
dist = dist || 20;
var tooltipTop = function ( Elem ) {
return nv.tooltip.findTotalOffsetTop(Elem, top);
};
var tooltipLeft = function ( Elem ) {
return nv.tooltip.findTotalOffsetLeft(Elem,left);
};
switch (gravity) {
case 'e':
left = pos[0] - width - dist;
top = pos[1] - (height / 2);
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft < scrollLeft) left = pos[0] + dist > scrollLeft ? pos[0] + dist : scrollLeft - tLeft + left;
if (tTop < scrollTop) top = scrollTop - tTop + top;
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
break;
case 'w':
left = pos[0] + dist;
top = pos[1] - (height / 2);
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft + width > windowWidth) left = pos[0] - width - dist;
if (tTop < scrollTop) top = scrollTop + 5;
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
break;
case 'n':
left = pos[0] - (width / 2) - 5;
top = pos[1] + dist;
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft < scrollLeft) left = scrollLeft + 5;
if (tLeft + width > windowWidth) left = left - width/2 + 5;
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
break;
case 's':
left = pos[0] - (width / 2);
top = pos[1] - height - dist;
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft < scrollLeft) left = scrollLeft + 5;
if (tLeft + width > windowWidth) left = left - width/2 + 5;
if (scrollTop > tTop) top = scrollTop;
break;
case 'none':
left = pos[0];
top = pos[1] - dist;
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
break;
}
container.style.left = left+'px';
container.style.top = top+'px';
container.style.opacity = 1;
container.style.position = 'absolute';
return container;
};
//Global utility function to remove tooltips from the DOM.
nv.tooltip.cleanup = function() {
// Find the tooltips, mark them for removal by this class (so others cleanups won't find it)
var tooltips = document.getElementsByClassName('nvtooltip');
var purging = [];
while(tooltips.length) {
purging.push(tooltips[0]);
tooltips[0].style.transitionDelay = '0 !important';
tooltips[0].style.opacity = 0;
tooltips[0].className = 'nvtooltip-pending-removal';
}
setTimeout(function() {
while (purging.length) {
var removeMe = purging.pop();
removeMe.parentNode.removeChild(removeMe);
}
}, 500);
};
})();
nv.utils.windowSize = function() {
// Sane defaults
var size = {width: 640, height: 480};
// Earlier IE uses Doc.body
if (document.body && document.body.offsetWidth) {
size.width = document.body.offsetWidth;
size.height = document.body.offsetHeight;
}
// IE can use depending on mode it is in
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
size.width = document.documentElement.offsetWidth;
size.height = document.documentElement.offsetHeight;
}
// Most recent browsers use
if (window.innerWidth && window.innerHeight) {
size.width = window.innerWidth;
size.height = window.innerHeight;
}
return (size);
};
// Easy way to bind multiple functions to window.onresize
// TODO: give a way to remove a function after its bound, other than removing all of them
nv.utils.windowResize = function(fun){
if (fun === undefined) return;
var oldresize = window.onresize;
window.onresize = function(e) {
if (typeof oldresize == 'function') oldresize(e);
fun(e);
}
}
// Backwards compatible way to implement more d3-like coloring of graphs.
// If passed an array, wrap it in a function which implements the old default
// behavior
nv.utils.getColor = function(color) {
if (!arguments.length) return nv.utils.defaultColor(); //if you pass in nothing, get default colors back
if( Object.prototype.toString.call( color ) === '[object Array]' )
return function(d, i) { return d.color || color[i % color.length]; };
else
return color;
//can't really help it if someone passes rubbish as color
}
// Default color chooser uses the index of an object as before.
nv.utils.defaultColor = function() {
var colors = d3.scale.category20().range();
return function(d, i) { return d.color || colors[i % colors.length] };
}
// Returns a color function that takes the result of 'getKey' for each series and
// looks for a corresponding color from the dictionary,
nv.utils.customTheme = function(dictionary, getKey, defaultColors) {
getKey = getKey || function(series) { return series.key }; // use default series.key if getKey is undefined
defaultColors = defaultColors || d3.scale.category20().range(); //default color function
var defIndex = defaultColors.length; //current default color (going in reverse)
return function(series, index) {
var key = getKey(series);
if (!defIndex) defIndex = defaultColors.length; //used all the default colors, start over
if (typeof dictionary[key] !== "undefined")
return (typeof dictionary[key] === "function") ? dictionary[key]() : dictionary[key];
else
return defaultColors[--defIndex]; // no match in dictionary, use default color
}
}
// From the PJAX example on d3js.org, while this is not really directly needed
// it's a very cool method for doing pjax, I may expand upon it a little bit,
// open to suggestions on anything that may be useful
nv.utils.pjax = function(links, content) {
d3.selectAll(links).on("click", function() {
history.pushState(this.href, this.textContent, this.href);
load(this.href);
d3.event.preventDefault();
});
function load(href) {
d3.html(href, function(fragment) {
var target = d3.select(content).node();
target.parentNode.replaceChild(d3.select(fragment).select(content).node(), target);
nv.utils.pjax(links, content);
});
}
d3.select(window).on("popstate", function() {
if (d3.event.state) load(d3.event.state);
});
}
/* For situations where we want to approximate the width in pixels for an SVG:text element.
Most common instance is when the element is in a display:none; container.
Forumla is : text.length * font-size * constant_factor
*/
nv.utils.calcApproxTextWidth = function (svgTextElem) {
if (typeof svgTextElem.style === 'function'
&& typeof svgTextElem.text === 'function') {
var fontSize = parseInt(svgTextElem.style("font-size").replace("px",""));
var textLength = svgTextElem.text().length;
return textLength * fontSize * 0.5;
}
return 0;
};
/* Numbers that are undefined, null or NaN, convert them to zeros.
*/
nv.utils.NaNtoZero = function(n) {
if (typeof n !== 'number'
|| isNaN(n)
|| n === null
|| n === Infinity) return 0;
return n;
};
/*
Snippet of code you can insert into each nv.models.* to give you the ability to
do things like:
chart.options({
showXAxis: true,
tooltips: true
});
To enable in the chart:
chart.options = nv.utils.optionsFunc.bind(chart);
*/
nv.utils.optionsFunc = function(args) {
if (args) {
d3.map(args).forEach((function(key,value) {
if (typeof this[key] === "function") {
this[key](value);
}
}).bind(this));
}
return this;
};nv.models.axis = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var axis = d3.svg.axis()
;
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 75 //only used for tickLabel currently
, height = 60 //only used for tickLabel currently
, scale = d3.scale.linear()
, axisLabelText = null
, showMaxMin = true //TODO: showMaxMin should be disabled on all ordinal scaled axes
, highlightZero = true
, rotateLabels = 0
, rotateYLabel = true
, staggerLabels = false
, isOrdinal = false
, ticks = null
, axisLabelDistance = 30 //The larger this number is, the closer the axis label is to the axis.
;
axis
.scale(scale)
.orient('bottom')
.tickFormat(function(d) { return d })
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var scale0;
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this);
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-axis').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-axis');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g')
//------------------------------------------------------------
if (ticks !== null)
axis.ticks(ticks);
else if (axis.orient() == 'top' || axis.orient() == 'bottom')
axis.ticks(Math.abs(scale.range()[1] - scale.range()[0]) / 100);
//TODO: consider calculating width/height based on whether or not label is added, for reference in charts using this component
g.transition().call(axis);
scale0 = scale0 || axis.scale();
var fmt = axis.tickFormat();
if (fmt == null) {
fmt = scale0.tickFormat();
}
var axisLabel = g.selectAll('text.nv-axislabel')
.data([axisLabelText || null]);
axisLabel.exit().remove();
switch (axis.orient()) {
case 'top':
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]));
axisLabel
.attr('text-anchor', 'middle')
.attr('y', 0)
.attr('x', w/2);
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text');
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(' + scale(d) + ',0)'
})
.select('text')
.attr('dy', '-0.5em')
.attr('y', -axis.tickPadding())
.attr('text-anchor', 'middle')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
axisMaxMin.transition()
.attr('transform', function(d,i) {
return 'translate(' + scale.range()[i] + ',0)'
});
}
break;
case 'bottom':
var xLabelMargin = 36;
var maxTextWidth = 30;
var xTicks = g.selectAll('g').select("text");
if (rotateLabels%360) {
//Calculate the longest xTick width
xTicks.each(function(d,i){
var width = this.getBBox().width;
if(width > maxTextWidth) maxTextWidth = width;
});
//Convert to radians before calculating sin. Add 30 to margin for healthy padding.
var sin = Math.abs(Math.sin(rotateLabels*Math.PI/180));
var xLabelMargin = (sin ? sin*maxTextWidth : maxTextWidth)+30;
//Rotate all xTicks
xTicks
.attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' })
.style('text-anchor', rotateLabels%360 > 0 ? 'start' : 'end');
}
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]));
axisLabel
.attr('text-anchor', 'middle')
.attr('y', xLabelMargin)
.attr('x', w/2);
if (showMaxMin) {
//if (showMaxMin && !isOrdinal) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
//.data(scale.domain())
.data([scale.domain()[0], scale.domain()[scale.domain().length - 1]]);
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text');
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)'
})
.select('text')
.attr('dy', '.71em')
.attr('y', axis.tickPadding())
.attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' })
.style('text-anchor', rotateLabels ? (rotateLabels%360 > 0 ? 'start' : 'end') : 'middle')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
axisMaxMin.transition()
.attr('transform', function(d,i) {
//return 'translate(' + scale.range()[i] + ',0)'
//return 'translate(' + scale(d) + ',0)'
return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)'
});
}
if (staggerLabels)
xTicks
.attr('transform', function(d,i) { return 'translate(0,' + (i % 2 == 0 ? '0' : '12') + ')' });
break;
case 'right':
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
axisLabel
.style('text-anchor', rotateYLabel ? 'middle' : 'begin')
.attr('transform', rotateYLabel ? 'rotate(90)' : '')
.attr('y', rotateYLabel ? (-Math.max(margin.right,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
.attr('x', rotateYLabel ? (scale.range()[0] / 2) : axis.tickPadding());
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text')
.style('opacity', 0);
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(0,' + scale(d) + ')'
})
.select('text')
.attr('dy', '.32em')
.attr('y', 0)
.attr('x', axis.tickPadding())
.style('text-anchor', 'start')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
axisMaxMin.transition()
.attr('transform', function(d,i) {
return 'translate(0,' + scale.range()[i] + ')'
})
.select('text')
.style('opacity', 1);
}
break;
case 'left':
/*
//For dynamically placing the label. Can be used with dynamically-sized chart axis margins
var yTicks = g.selectAll('g').select("text");
yTicks.each(function(d,i){
var labelPadding = this.getBBox().width + axis.tickPadding() + 16;
if(labelPadding > width) width = labelPadding;
});
*/
axisLabel.enter().append('text').attr('class', 'nv-axislabel');
axisLabel
.style('text-anchor', rotateYLabel ? 'middle' : 'end')
.attr('transform', rotateYLabel ? 'rotate(-90)' : '')
.attr('y', rotateYLabel ? (-Math.max(margin.left,width) + axisLabelDistance) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
.attr('x', rotateYLabel ? (-scale.range()[0] / 2) : -axis.tickPadding());
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text')
.style('opacity', 0);
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(0,' + scale0(d) + ')'
})
.select('text')
.attr('dy', '.32em')
.attr('y', 0)
.attr('x', -axis.tickPadding())
.attr('text-anchor', 'end')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
axisMaxMin.transition()
.attr('transform', function(d,i) {
return 'translate(0,' + scale.range()[i] + ')'
})
.select('text')
.style('opacity', 1);
}
break;
}
axisLabel
.text(function(d) { return d });
if (showMaxMin && (axis.orient() === 'left' || axis.orient() === 'right')) {
//check if max and min overlap other values, if so, hide the values that overlap
g.selectAll('g') // the g's wrapping each tick
.each(function(d,i) {
d3.select(this).select('text').attr('opacity', 1);
if (scale(d) < scale.range()[1] + 10 || scale(d) > scale.range()[0] - 10) { // 10 is assuming text height is 16... if d is 0, leave it!
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
d3.select(this).attr('opacity', 0);
d3.select(this).select('text').attr('opacity', 0); // Don't remove the ZERO line!!
}
});
//if Max and Min = 0 only show min, Issue #281
if (scale.domain()[0] == scale.domain()[1] && scale.domain()[0] == 0)
wrap.selectAll('g.nv-axisMaxMin')
.style('opacity', function(d,i) { return !i ? 1 : 0 });
}
if (showMaxMin && (axis.orient() === 'top' || axis.orient() === 'bottom')) {
var maxMinRange = [];
wrap.selectAll('g.nv-axisMaxMin')
.each(function(d,i) {
try {
if (i) // i== 1, max position
maxMinRange.push(scale(d) - this.getBBox().width - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
else // i==0, min position
maxMinRange.push(scale(d) + this.getBBox().width + 4)
}catch (err) {
if (i) // i== 1, max position
maxMinRange.push(scale(d) - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
else // i==0, min position
maxMinRange.push(scale(d) + 4)
}
});
g.selectAll('g') // the g's wrapping each tick
.each(function(d,i) {
if (scale(d) < maxMinRange[0] || scale(d) > maxMinRange[1]) {
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
d3.select(this).remove();
else
d3.select(this).select('text').remove(); // Don't remove the ZERO line!!
}
});
}
//highlight zero line ... Maybe should not be an option and should just be in CSS?
if (highlightZero)
g.selectAll('.tick')
.filter(function(d) { return !parseFloat(Math.round(d.__data__*100000)/1000000) && (d.__data__ !== undefined) }) //this is because sometimes the 0 tick is a very small fraction, TODO: think of cleaner technique
.classed('zero', true);
//store old scales for use in transitions on update
scale0 = scale.copy();
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.axis = axis;
d3.rebind(chart, axis, 'orient', 'tickValues', 'tickSubdivide', 'tickSize', 'tickPadding', 'tickFormat');
d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); //these are also accessible by chart.scale(), but added common ones directly for ease of use
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if(!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
}
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.ticks = function(_) {
if (!arguments.length) return ticks;
ticks = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.axisLabel = function(_) {
if (!arguments.length) return axisLabelText;
axisLabelText = _;
return chart;
}
chart.showMaxMin = function(_) {
if (!arguments.length) return showMaxMin;
showMaxMin = _;
return chart;
}
chart.highlightZero = function(_) {
if (!arguments.length) return highlightZero;
highlightZero = _;
return chart;
}
chart.scale = function(_) {
if (!arguments.length) return scale;
scale = _;
axis.scale(scale);
isOrdinal = typeof scale.rangeBands === 'function';
d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands');
return chart;
}
chart.rotateYLabel = function(_) {
if(!arguments.length) return rotateYLabel;
rotateYLabel = _;
return chart;
}
chart.rotateLabels = function(_) {
if(!arguments.length) return rotateLabels;
rotateLabels = _;
return chart;
}
chart.staggerLabels = function(_) {
if (!arguments.length) return staggerLabels;
staggerLabels = _;
return chart;
};
chart.axisLabelDistance = function(_) {
if (!arguments.length) return axisLabelDistance;
axisLabelDistance = _;
return chart;
};
//============================================================
return chart;
}
//TODO: consider deprecating and using multibar with single series for this
nv.models.historicalBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, x = d3.scale.linear()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, forceX = []
, forceY = [0]
, padData = false
, clipEdge = true
, color = nv.utils.defaultColor()
, xDomain
, yDomain
, xRange
, yRange
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
, interactive = true
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
//------------------------------------------------------------
// Setup Scales
x .domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ))
if (padData)
x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
else
x.range(xRange || [0, availableWidth]);
y .domain(yDomain || d3.extent(data[0].values.map(getY).concat(forceY) ))
.range(yRange || [availableHeight, 0]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
: y.domain([-1,1]);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-historicalBar-' + id).data([data[0].values]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-historicalBar-' + id);
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-bars');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
container
.on('click', function(d,i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
defsEnter.append('clipPath')
.attr('id', 'nv-chart-clip-path-' + id)
.append('rect');
wrap.select('#nv-chart-clip-path-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
var bars = wrap.select('.nv-bars').selectAll('.nv-bar')
.data(function(d) { return d }, function(d,i) {return getX(d,i)});
bars.exit().remove();
var barsEnter = bars.enter().append('rect')
//.attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i })
.attr('x', 0 )
.attr('y', function(d,i) { return nv.utils.NaNtoZero(y(Math.max(0, getY(d,i)))) })
.attr('height', function(d,i) { return nv.utils.NaNtoZero(Math.abs(y(getY(d,i)) - y(0))) })
.attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; })
.on('mouseover', function(d,i) {
if (!interactive) return;
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
point: d,
series: data[0],
pos: [x(getX(d,i)), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: 0,
e: d3.event
});
})
.on('mouseout', function(d,i) {
if (!interactive) return;
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
point: d,
series: data[0],
pointIndex: i,
seriesIndex: 0,
e: d3.event
});
})
.on('click', function(d,i) {
if (!interactive) return;
dispatch.elementClick({
//label: d[label],
value: getY(d,i),
data: d,
index: i,
pos: [x(getX(d,i)), y(getY(d,i))],
e: d3.event,
id: id
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
if (!interactive) return;
dispatch.elementDblClick({
//label: d[label],
value: getY(d,i),
data: d,
index: i,
pos: [x(getX(d,i)), y(getY(d,i))],
e: d3.event,
id: id
});
d3.event.stopPropagation();
});
bars
.attr('fill', function(d,i) { return color(d, i); })
.attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i })
.transition()
.attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; })
//TODO: better width calculations that don't assume always uniform data spacing;w
.attr('width', (availableWidth / data[0].values.length) * .9 );
bars.transition()
.attr('y', function(d,i) {
var rval = getY(d,i) < 0 ?
y(0) :
y(0) - y(getY(d,i)) < 1 ?
y(0) - 1 :
y(getY(d,i));
return nv.utils.NaNtoZero(rval);
})
.attr('height', function(d,i) { return nv.utils.NaNtoZero(Math.max(Math.abs(y(getY(d,i)) - y(0)),1)) });
});
return chart;
}
//Create methods to allow outside functions to highlight a specific bar.
chart.highlightPoint = function(pointIndex, isHoverOver) {
d3.select(".nv-historicalBar-" + id)
.select(".nv-bars .nv-bar-0-" + pointIndex)
.classed("hover", isHoverOver)
;
};
chart.clearHighlights = function() {
d3.select(".nv-historicalBar-" + id)
.select(".nv-bars .nv-bar.hover")
.classed("hover", false)
;
};
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.xScale = function(_) {
if (!arguments.length) return x;
x = _;
return chart;
};
chart.yScale = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.xDomain = function(_) {
if (!arguments.length) return xDomain;
xDomain = _;
return chart;
};
chart.yDomain = function(_) {
if (!arguments.length) return yDomain;
yDomain = _;
return chart;
};
chart.xRange = function(_) {
if (!arguments.length) return xRange;
xRange = _;
return chart;
};
chart.yRange = function(_) {
if (!arguments.length) return yRange;
yRange = _;
return chart;
};
chart.forceX = function(_) {
if (!arguments.length) return forceX;
forceX = _;
return chart;
};
chart.forceY = function(_) {
if (!arguments.length) return forceY;
forceY = _;
return chart;
};
chart.padData = function(_) {
if (!arguments.length) return padData;
padData = _;
return chart;
};
chart.clipEdge = function(_) {
if (!arguments.length) return clipEdge;
clipEdge = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.id = function(_) {
if (!arguments.length) return id;
id = _;
return chart;
};
chart.interactive = function(_) {
if(!arguments.length) return interactive;
interactive = false;
return chart;
};
//============================================================
return chart;
}
// Chart design based on the recommendations of Stephen Few. Implementation
// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
// http://projects.instantcognition.com/protovis/bulletchart/
nv.models.bullet = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, orient = 'left' // TODO top & bottom
, reverse = false
, ranges = function(d) { return d.ranges }
, markers = function(d) { return d.markers }
, measures = function(d) { return d.measures }
, rangeLabels = function(d) { return d.rangeLabels ? d.rangeLabels : [] }
, markerLabels = function(d) { return d.markerLabels ? d.markerLabels : [] }
, measureLabels = function(d) { return d.measureLabels ? d.measureLabels : [] }
, forceX = [0] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
, width = 380
, height = 30
, tickFormat = null
, color = nv.utils.getColor(['#1f77b4'])
, dispatch = d3.dispatch('elementMouseover', 'elementMouseout')
;
//============================================================
function chart(selection) {
selection.each(function(d, i) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
var rangez = ranges.call(this, d, i).slice().sort(d3.descending),
markerz = markers.call(this, d, i).slice().sort(d3.descending),
measurez = measures.call(this, d, i).slice().sort(d3.descending),
rangeLabelz = rangeLabels.call(this, d, i).slice(),
markerLabelz = markerLabels.call(this, d, i).slice(),
measureLabelz = measureLabels.call(this, d, i).slice();
//------------------------------------------------------------
// Setup Scales
// Compute the new x-scale.
var x1 = d3.scale.linear()
.domain( d3.extent(d3.merge([forceX, rangez])) )
.range(reverse ? [availableWidth, 0] : [0, availableWidth]);
// Retrieve the old x-scale, if this is an update.
var x0 = this.__chart__ || d3.scale.linear()
.domain([0, Infinity])
.range(x1.range());
// Stash the new scale.
this.__chart__ = x1;
var rangeMin = d3.min(rangez), //rangez[2]
rangeMax = d3.max(rangez), //rangez[0]
rangeAvg = rangez[1];
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-bullet').data([d]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bullet');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('rect').attr('class', 'nv-range nv-rangeMax');
gEnter.append('rect').attr('class', 'nv-range nv-rangeAvg');
gEnter.append('rect').attr('class', 'nv-range nv-rangeMin');
gEnter.append('rect').attr('class', 'nv-measure');
gEnter.append('path').attr('class', 'nv-markerTriangle');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0)
w1 = function(d) { return Math.abs(x1(d) - x1(0)) };
var xp0 = function(d) { return d < 0 ? x0(d) : x0(0) },
xp1 = function(d) { return d < 0 ? x1(d) : x1(0) };
g.select('rect.nv-rangeMax')
.attr('height', availableHeight)
.attr('width', w1(rangeMax > 0 ? rangeMax : rangeMin))
.attr('x', xp1(rangeMax > 0 ? rangeMax : rangeMin))
.datum(rangeMax > 0 ? rangeMax : rangeMin)
/*
.attr('x', rangeMin < 0 ?
rangeMax > 0 ?
x1(rangeMin)
: x1(rangeMax)
: x1(0))
*/
g.select('rect.nv-rangeAvg')
.attr('height', availableHeight)
.attr('width', w1(rangeAvg))
.attr('x', xp1(rangeAvg))
.datum(rangeAvg)
/*
.attr('width', rangeMax <= 0 ?
x1(rangeMax) - x1(rangeAvg)
: x1(rangeAvg) - x1(rangeMin))
.attr('x', rangeMax <= 0 ?
x1(rangeAvg)
: x1(rangeMin))
*/
g.select('rect.nv-rangeMin')
.attr('height', availableHeight)
.attr('width', w1(rangeMax))
.attr('x', xp1(rangeMax))
.attr('width', w1(rangeMax > 0 ? rangeMin : rangeMax))
.attr('x', xp1(rangeMax > 0 ? rangeMin : rangeMax))
.datum(rangeMax > 0 ? rangeMin : rangeMax)
/*
.attr('width', rangeMax <= 0 ?
x1(rangeAvg) - x1(rangeMin)
: x1(rangeMax) - x1(rangeAvg))
.attr('x', rangeMax <= 0 ?
x1(rangeMin)
: x1(rangeAvg))
*/
g.select('rect.nv-measure')
.style('fill', color)
.attr('height', availableHeight / 3)
.attr('y', availableHeight / 3)
.attr('width', measurez < 0 ?
x1(0) - x1(measurez[0])
: x1(measurez[0]) - x1(0))
.attr('x', xp1(measurez))
.on('mouseover', function() {
dispatch.elementMouseover({
value: measurez[0],
label: measureLabelz[0] || 'Current',
pos: [x1(measurez[0]), availableHeight/2]
})
})
.on('mouseout', function() {
dispatch.elementMouseout({
value: measurez[0],
label: measureLabelz[0] || 'Current'
})
})
var h3 = availableHeight / 6;
if (markerz[0]) {
g.selectAll('path.nv-markerTriangle')
.attr('transform', function(d) { return 'translate(' + x1(markerz[0]) + ',' + (availableHeight / 2) + ')' })
.attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z')
.on('mouseover', function() {
dispatch.elementMouseover({
value: markerz[0],
label: markerLabelz[0] || 'Previous',
pos: [x1(markerz[0]), availableHeight/2]
})
})
.on('mouseout', function() {
dispatch.elementMouseout({
value: markerz[0],
label: markerLabelz[0] || 'Previous'
})
});
} else {
g.selectAll('path.nv-markerTriangle').remove();
}
wrap.selectAll('.nv-range')
.on('mouseover', function(d,i) {
var label = rangeLabelz[i] || (!i ? "Maximum" : i == 1 ? "Mean" : "Minimum");
dispatch.elementMouseover({
value: d,
label: label,
pos: [x1(d), availableHeight/2]
})
})
.on('mouseout', function(d,i) {
var label = rangeLabelz[i] || (!i ? "Maximum" : i == 1 ? "Mean" : "Minimum");
dispatch.elementMouseout({
value: d,
label: label
})
})
/* // THIS IS THE PREVIOUS BULLET IMPLEMENTATION, WILL REMOVE SHORTLY
// Update the range rects.
var range = g.selectAll('rect.nv-range')
.data(rangez);
range.enter().append('rect')
.attr('class', function(d, i) { return 'nv-range nv-s' + i; })
.attr('width', w0)
.attr('height', availableHeight)
.attr('x', reverse ? x0 : 0)
.on('mouseover', function(d,i) {
dispatch.elementMouseover({
value: d,
label: (i <= 0) ? 'Maximum' : (i > 1) ? 'Minimum' : 'Mean', //TODO: make these labels a variable
pos: [x1(d), availableHeight/2]
})
})
.on('mouseout', function(d,i) {
dispatch.elementMouseout({
value: d,
label: (i <= 0) ? 'Minimum' : (i >=1) ? 'Maximum' : 'Mean' //TODO: make these labels a variable
})
})
d3.transition(range)
.attr('x', reverse ? x1 : 0)
.attr('width', w1)
.attr('height', availableHeight);
// Update the measure rects.
var measure = g.selectAll('rect.nv-measure')
.data(measurez);
measure.enter().append('rect')
.attr('class', function(d, i) { return 'nv-measure nv-s' + i; })
.style('fill', function(d,i) { return color(d,i ) })
.attr('width', w0)
.attr('height', availableHeight / 3)
.attr('x', reverse ? x0 : 0)
.attr('y', availableHeight / 3)
.on('mouseover', function(d) {
dispatch.elementMouseover({
value: d,
label: 'Current', //TODO: make these labels a variable
pos: [x1(d), availableHeight/2]
})
})
.on('mouseout', function(d) {
dispatch.elementMouseout({
value: d,
label: 'Current' //TODO: make these labels a variable
})
})
d3.transition(measure)
.attr('width', w1)
.attr('height', availableHeight / 3)
.attr('x', reverse ? x1 : 0)
.attr('y', availableHeight / 3);
// Update the marker lines.
var marker = g.selectAll('path.nv-markerTriangle')
.data(markerz);
var h3 = availableHeight / 6;
marker.enter().append('path')
.attr('class', 'nv-markerTriangle')
.attr('transform', function(d) { return 'translate(' + x0(d) + ',' + (availableHeight / 2) + ')' })
.attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z')
.on('mouseover', function(d,i) {
dispatch.elementMouseover({
value: d,
label: 'Previous',
pos: [x1(d), availableHeight/2]
})
})
.on('mouseout', function(d,i) {
dispatch.elementMouseout({
value: d,
label: 'Previous'
})
});
d3.transition(marker)
.attr('transform', function(d) { return 'translate(' + (x1(d) - x1(0)) + ',' + (availableHeight / 2) + ')' });
marker.exit().remove();
*/
});
// d3.timer.flush(); // Not needed?
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
// left, right, top, bottom
chart.orient = function(_) {
if (!arguments.length) return orient;
orient = _;
reverse = orient == 'right' || orient == 'bottom';
return chart;
};
// ranges (bad, satisfactory, good)
chart.ranges = function(_) {
if (!arguments.length) return ranges;
ranges = _;
return chart;
};
// markers (previous, goal)
chart.markers = function(_) {
if (!arguments.length) return markers;
markers = _;
return chart;
};
// measures (actual, forecast)
chart.measures = function(_) {
if (!arguments.length) return measures;
measures = _;
return chart;
};
chart.forceX = function(_) {
if (!arguments.length) return forceX;
forceX = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.tickFormat = function(_) {
if (!arguments.length) return tickFormat;
tickFormat = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
//============================================================
return chart;
};
// Chart design based on the recommendations of Stephen Few. Implementation
// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
// http://projects.instantcognition.com/protovis/bulletchart/
nv.models.bulletChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var bullet = nv.models.bullet()
;
var orient = 'left' // TODO top & bottom
, reverse = false
, margin = {top: 5, right: 40, bottom: 20, left: 120}
, ranges = function(d) { return d.ranges }
, markers = function(d) { return d.markers }
, measures = function(d) { return d.measures }
, width = null
, height = 55
, tickFormat = null
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + x + '</h3>' +
'<p>' + y + '</p>'
}
, noData = 'No Data Available.'
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ) + margin.left,
top = e.pos[1] + ( offsetElement.offsetTop || 0) + margin.top,
content = tooltip(e.key, e.label, e.value, e, chart);
nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(d, i) {
var container = d3.select(this);
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
that = this;
chart.update = function() { chart(selection) };
chart.container = this;
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!d || !ranges.call(this, d, i)) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', 18 + margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
var rangez = ranges.call(this, d, i).slice().sort(d3.descending),
markerz = markers.call(this, d, i).slice().sort(d3.descending),
measurez = measures.call(this, d, i).slice().sort(d3.descending);
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-bulletChart').data([d]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bulletChart');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-bulletWrap');
gEnter.append('g').attr('class', 'nv-titles');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
// Compute the new x-scale.
var x1 = d3.scale.linear()
.domain([0, Math.max(rangez[0], markerz[0], measurez[0])]) // TODO: need to allow forceX and forceY, and xDomain, yDomain
.range(reverse ? [availableWidth, 0] : [0, availableWidth]);
// Retrieve the old x-scale, if this is an update.
var x0 = this.__chart__ || d3.scale.linear()
.domain([0, Infinity])
.range(x1.range());
// Stash the new scale.
this.__chart__ = x1;
/*
// Derive width-scales from the x-scales.
var w0 = bulletWidth(x0),
w1 = bulletWidth(x1);
function bulletWidth(x) {
var x0 = x(0);
return function(d) {
return Math.abs(x(d) - x(0));
};
}
function bulletTranslate(x) {
return function(d) {
return 'translate(' + x(d) + ',0)';
};
}
*/
var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0)
w1 = function(d) { return Math.abs(x1(d) - x1(0)) };
var title = gEnter.select('.nv-titles').append('g')
.attr('text-anchor', 'end')
.attr('transform', 'translate(-6,' + (height - margin.top - margin.bottom) / 2 + ')');
title.append('text')
.attr('class', 'nv-title')
.text(function(d) { return d.title; });
title.append('text')
.attr('class', 'nv-subtitle')
.attr('dy', '1em')
.text(function(d) { return d.subtitle; });
bullet
.width(availableWidth)
.height(availableHeight)
var bulletWrap = g.select('.nv-bulletWrap');
d3.transition(bulletWrap).call(bullet);
// Compute the tick format.
var format = tickFormat || x1.tickFormat( availableWidth / 100 );
// Update the tick groups.
var tick = g.selectAll('g.nv-tick')
.data(x1.ticks( availableWidth / 50 ), function(d) {
return this.textContent || format(d);
});
// Initialize the ticks with the old scale, x0.
var tickEnter = tick.enter().append('g')
.attr('class', 'nv-tick')
.attr('transform', function(d) { return 'translate(' + x0(d) + ',0)' })
.style('opacity', 1e-6);
tickEnter.append('line')
.attr('y1', availableHeight)
.attr('y2', availableHeight * 7 / 6);
tickEnter.append('text')
.attr('text-anchor', 'middle')
.attr('dy', '1em')
.attr('y', availableHeight * 7 / 6)
.text(format);
// Transition the updating ticks to the new scale, x1.
var tickUpdate = d3.transition(tick)
.attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' })
.style('opacity', 1);
tickUpdate.select('line')
.attr('y1', availableHeight)
.attr('y2', availableHeight * 7 / 6);
tickUpdate.select('text')
.attr('y', availableHeight * 7 / 6);
// Transition the exiting ticks to the new scale, x1.
d3.transition(tick.exit())
.attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' })
.style('opacity', 1e-6)
.remove();
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
dispatch.on('tooltipShow', function(e) {
e.key = d.title;
if (tooltips) showTooltip(e, that.parentNode);
});
//============================================================
});
d3.timer.flush();
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
bullet.dispatch.on('elementMouseover.tooltip', function(e) {
dispatch.tooltipShow(e);
});
bullet.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.bullet = bullet;
d3.rebind(chart, bullet, 'color');
chart.options = nv.utils.optionsFunc.bind(chart);
// left, right, top, bottom
chart.orient = function(x) {
if (!arguments.length) return orient;
orient = x;
reverse = orient == 'right' || orient == 'bottom';
return chart;
};
// ranges (bad, satisfactory, good)
chart.ranges = function(x) {
if (!arguments.length) return ranges;
ranges = x;
return chart;
};
// markers (previous, goal)
chart.markers = function(x) {
if (!arguments.length) return markers;
markers = x;
return chart;
};
// measures (actual, forecast)
chart.measures = function(x) {
if (!arguments.length) return measures;
measures = x;
return chart;
};
chart.width = function(x) {
if (!arguments.length) return width;
width = x;
return chart;
};
chart.height = function(x) {
if (!arguments.length) return height;
height = x;
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.tickFormat = function(x) {
if (!arguments.length) return tickFormat;
tickFormat = x;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
//============================================================
return chart;
};
nv.models.cumulativeLineChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var lines = nv.models.line()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, controls = nv.models.legend()
, interactiveLayer = nv.interactiveGuideline()
;
var margin = {top: 30, right: 30, bottom: 50, left: 60}
, color = nv.utils.defaultColor()
, width = null
, height = null
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, tooltips = true
, showControls = true
, useInteractiveGuideline = false
, rescaleY = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' at ' + x + '</p>'
}
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, id = lines.id()
, state = { index: 0, rescaleY: rescaleY }
, defaultState = null
, noData = 'No Data Available.'
, average = function(d) { return d.average }
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
, transitionDuration = 250
, noErrorCheck = false //if set to TRUE, will bypass an error check in the indexify function.
;
xAxis
.orient('bottom')
.tickPadding(7)
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
;
//============================================================
controls.updateState(false);
//============================================================
// Private Variables
//------------------------------------------------------------
var dx = d3.scale.linear()
, index = {i: 0, x: 0}
;
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)),
y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, null, null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this).classed('nv-chart-' + id, true),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
var indexDrag = d3.behavior.drag()
.on('dragstart', dragStart)
.on('drag', dragMove)
.on('dragend', dragEnd);
function dragStart(d,i) {
d3.select(chart.container)
.style('cursor', 'ew-resize');
}
function dragMove(d,i) {
index.x = d3.event.x;
index.i = Math.round(dx.invert(index.x));
updateZero();
}
function dragEnd(d,i) {
d3.select(chart.container)
.style('cursor', 'auto');
// update state and send stateChange with new index
state.index = index.i;
dispatch.stateChange(state);
}
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = lines.xScale();
y = lines.yScale();
if (!rescaleY) {
var seriesDomains = data
.filter(function(series) { return !series.disabled })
.map(function(series,i) {
var initialDomain = d3.extent(series.values, lines.y());
//account for series being disabled when losing 95% or more
if (initialDomain[0] < -.95) initialDomain[0] = -.95;
return [
(initialDomain[0] - initialDomain[1]) / (1 + initialDomain[1]),
(initialDomain[1] - initialDomain[0]) / (1 + initialDomain[0])
];
});
var completeDomain = [
d3.min(seriesDomains, function(d) { return d[0] }),
d3.max(seriesDomains, function(d) { return d[1] })
]
lines.yDomain(completeDomain);
} else {
lines.yDomain(null);
}
dx .domain([0, data[0].values.length - 1]) //Assumes all series have same length
.range([0, availableWidth])
.clamp(true);
//------------------------------------------------------------
var data = indexify(index.i, data);
//------------------------------------------------------------
// Setup containers and skeleton of chart
var interactivePointerEvents = (useInteractiveGuideline) ? "none" : "all";
var wrap = container.selectAll('g.nv-wrap.nv-cumulativeLine').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-cumulativeLine').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-interactive');
gEnter.append('g').attr('class', 'nv-x nv-axis').style("pointer-events","none");
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-background');
gEnter.append('g').attr('class', 'nv-linesWrap').style("pointer-events",interactivePointerEvents);
gEnter.append('g').attr('class', 'nv-avgLinesWrap').style("pointer-events","none");
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width(availableWidth);
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')')
}
//------------------------------------------------------------
//------------------------------------------------------------
// Controls
if (showControls) {
var controlsData = [
{ key: 'Re-scale y-axis', disabled: !rescaleY }
];
controls
.width(140)
.color(['#444', '#444', '#444'])
.rightAlign(false)
.margin({top: 5, right: 0, bottom: 5, left: 20})
;
g.select('.nv-controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
// Show error if series goes below 100%
var tempDisabled = data.filter(function(d) { return d.tempDisabled });
wrap.select('.tempDisabled').remove(); //clean-up and prevent duplicates
if (tempDisabled.length) {
wrap.append('text').attr('class', 'tempDisabled')
.attr('x', availableWidth / 2)
.attr('y', '-.71em')
.style('text-anchor', 'end')
.text(tempDisabled.map(function(d) { return d.key }).join(', ') + ' values cannot be calculated for this time period.');
}
//------------------------------------------------------------
// Main Chart Component(s)
//------------------------------------------------------------
//Set up interactive layer
if (useInteractiveGuideline) {
interactiveLayer
.width(availableWidth)
.height(availableHeight)
.margin({left:margin.left,top:margin.top})
.svgContainer(container)
.xScale(x);
wrap.select(".nv-interactive").call(interactiveLayer);
}
gEnter.select('.nv-background')
.append('rect');
g.select('.nv-background rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
lines
//.x(function(d) { return d.x })
.y(function(d) { return d.display.y })
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && !data[i].tempDisabled; }));
var linesWrap = g.select('.nv-linesWrap')
.datum(data.filter(function(d) { return !d.disabled && !d.tempDisabled }));
//d3.transition(linesWrap).call(lines);
linesWrap.call(lines);
/*Handle average lines [AN-612] ----------------------------*/
//Store a series index number in the data array.
data.forEach(function(d,i) {
d.seriesIndex = i;
});
var avgLineData = data.filter(function(d) {
return !d.disabled && !!average(d);
});
var avgLines = g.select(".nv-avgLinesWrap").selectAll("line")
.data(avgLineData, function(d) { return d.key; });
var getAvgLineY = function(d) {
//If average lines go off the svg element, clamp them to the svg bounds.
var yVal = y(average(d));
if (yVal < 0) return 0;
if (yVal > availableHeight) return availableHeight;
return yVal;
};
avgLines.enter()
.append('line')
.style('stroke-width',2)
.style('stroke-dasharray','10,10')
.style('stroke',function (d,i) {
return lines.color()(d,d.seriesIndex);
})
.attr('x1',0)
.attr('x2',availableWidth)
.attr('y1', getAvgLineY)
.attr('y2', getAvgLineY);
avgLines
.style('stroke-opacity',function(d){
//If average lines go offscreen, make them transparent
var yVal = y(average(d));
if (yVal < 0 || yVal > availableHeight) return 0;
return 1;
})
.attr('x1',0)
.attr('x2',availableWidth)
.attr('y1', getAvgLineY)
.attr('y2', getAvgLineY);
avgLines.exit().remove();
//Create index line -----------------------------------------
var indexLine = linesWrap.selectAll('.nv-indexLine')
.data([index]);
indexLine.enter().append('rect').attr('class', 'nv-indexLine')
.attr('width', 3)
.attr('x', -2)
.attr('fill', 'red')
.attr('fill-opacity', .5)
.style("pointer-events","all")
.call(indexDrag)
indexLine
.attr('transform', function(d) { return 'translate(' + dx(d.i) + ',0)' })
.attr('height', availableHeight)
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
//Suggest how many ticks based on the chart width and D3 should listen (70 is the optimal number for MM/DD/YY dates)
.ticks( Math.min(data[0].values.length,availableWidth/70) )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
d3.transition(g.select('.nv-x.nv-axis'))
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
.ticks( availableHeight / 36 )
.tickSize( -availableWidth, 0);
d3.transition(g.select('.nv-y.nv-axis'))
.call(yAxis);
}
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
function updateZero() {
indexLine
.data([index]);
//When dragging the index line, turn off line transitions.
// Then turn them back on when done dragging.
var oldDuration = chart.transitionDuration();
chart.transitionDuration(0);
chart.update();
chart.transitionDuration(oldDuration);
}
g.select('.nv-background rect')
.on('click', function() {
index.x = d3.mouse(this)[0];
index.i = Math.round(dx.invert(index.x));
// update state and send stateChange with new index
state.index = index.i;
dispatch.stateChange(state);
updateZero();
});
lines.dispatch.on('elementClick', function(e) {
index.i = e.pointIndex;
index.x = dx(index.i);
// update state and send stateChange with new index
state.index = index.i;
dispatch.stateChange(state);
updateZero();
});
controls.dispatch.on('legendClick', function(d,i) {
d.disabled = !d.disabled;
rescaleY = !d.disabled;
state.rescaleY = rescaleY;
dispatch.stateChange(state);
chart.update();
});
legend.dispatch.on('stateChange', function(newState) {
state.disabled = newState.disabled;
dispatch.stateChange(state);
chart.update();
});
interactiveLayer.dispatch.on('elementMousemove', function(e) {
lines.clearHighlights();
var singlePoint, pointIndex, pointXLocation, allData = [];
data
.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled;
})
.forEach(function(series,i) {
pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
lines.highlightPoint(i, pointIndex, true);
var point = series.values[pointIndex];
if (typeof point === 'undefined') return;
if (typeof singlePoint === 'undefined') singlePoint = point;
if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
allData.push({
key: series.key,
value: chart.y()(point, pointIndex),
color: color(series,series.seriesIndex)
});
});
//Highlight the tooltip entry based on which point the mouse is closest to.
if (allData.length > 2) {
var yValue = chart.yScale().invert(e.mouseY);
var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]);
var threshold = 0.03 * domainExtent;
var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold);
if (indexToHighlight !== null)
allData[indexToHighlight].highlight = true;
}
var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex), pointIndex);
interactiveLayer.tooltip
.position({left: pointXLocation + margin.left, top: e.mouseY + margin.top})
.chartContainer(that.parentNode)
.enabled(tooltips)
.valueFormatter(function(d,i) {
return yAxis.tickFormat()(d);
})
.data(
{
value: xValue,
series: allData
}
)();
interactiveLayer.renderGuideLine(pointXLocation);
});
interactiveLayer.dispatch.on("elementMouseout",function(e) {
dispatch.tooltipHide();
lines.clearHighlights();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
if (typeof e.index !== 'undefined') {
index.i = e.index;
index.x = dx(index.i);
state.index = e.index;
indexLine
.data([index]);
}
if (typeof e.rescaleY !== 'undefined') {
rescaleY = e.rescaleY;
}
chart.update();
});
//============================================================
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
lines.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
lines.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.lines = lines;
chart.legend = legend;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.interactiveLayer = interactiveLayer;
d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'xScale','yScale', 'size', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi','useVoronoi', 'id');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
return chart;
};
chart.rescaleY = function(_) {
if (!arguments.length) return rescaleY;
rescaleY = _;
return chart;
};
chart.showControls = function(_) {
if (!arguments.length) return showControls;
showControls = _;
return chart;
};
chart.useInteractiveGuideline = function(_) {
if(!arguments.length) return useInteractiveGuideline;
useInteractiveGuideline = _;
if (_ === true) {
chart.interactive(false);
chart.useVoronoi(false);
}
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.showXAxis = function(_) {
if (!arguments.length) return showXAxis;
showXAxis = _;
return chart;
};
chart.showYAxis = function(_) {
if (!arguments.length) return showYAxis;
showYAxis = _;
return chart;
};
chart.rightAlignYAxis = function(_) {
if(!arguments.length) return rightAlignYAxis;
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.average = function(_) {
if(!arguments.length) return average;
average = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
chart.noErrorCheck = function(_) {
if (!arguments.length) return noErrorCheck;
noErrorCheck = _;
return chart;
};
//============================================================
//============================================================
// Functions
//------------------------------------------------------------
/* Normalize the data according to an index point. */
function indexify(idx, data) {
return data.map(function(line, i) {
if (!line.values) {
return line;
}
var indexValue = line.values[idx];
if (indexValue == null) {
return line;
}
var v = lines.y()(indexValue, idx);
//TODO: implement check below, and disable series if series loses 100% or more cause divide by 0 issue
if (v < -.95 && !noErrorCheck) {
//if a series loses more than 100%, calculations fail.. anything close can cause major distortion (but is mathematically correct till it hits 100)
line.tempDisabled = true;
return line;
}
line.tempDisabled = false;
line.values = line.values.map(function(point, pointIndex) {
point.display = {'y': (lines.y()(point, pointIndex) - v) / (1 + v) };
return point;
})
return line;
})
}
//============================================================
return chart;
}
//TODO: consider deprecating by adding necessary features to multiBar model
nv.models.discreteBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, x = d3.scale.ordinal()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
, color = nv.utils.defaultColor()
, showValues = false
, valueFormat = d3.format(',.2f')
, xDomain
, yDomain
, xRange
, yRange
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
, rectClass = 'discreteBar'
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
//add series index to each data point for reference
data.forEach(function(series, i) {
series.values.forEach(function(point) {
point.series = i;
});
});
//------------------------------------------------------------
// Setup Scales
// remap and flatten the data for use in calculating the scales' domains
var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
data.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i), y0: d.y0 }
})
});
x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
.rangeBands(xRange || [0, availableWidth], .1);
y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y }).concat(forceY)));
// If showValues, pad the Y axis range to account for label height
if (showValues) y.range(yRange || [availableHeight - (y.domain()[0] < 0 ? 12 : 0), y.domain()[1] > 0 ? 12 : 0]);
else y.range(yRange || [availableHeight, 0]);
//store old scales if they exist
x0 = x0 || x;
y0 = y0 || y.copy().range([y(0),y(0)]);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-discretebar').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discretebar');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-groups');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
//TODO: by definition, the discrete bar should not have multiple groups, will modify/remove later
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d) { return d.key });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6);
groups.exit()
.transition()
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6)
.remove();
groups
.attr('class', function(d,i) { return 'nv-group nv-series-' + i })
.classed('hover', function(d) { return d.hover });
groups
.transition()
.style('stroke-opacity', 1)
.style('fill-opacity', .75);
var bars = groups.selectAll('g.nv-bar')
.data(function(d) { return d.values });
bars.exit().remove();
var barsEnter = bars.enter().append('g')
.attr('transform', function(d,i,j) {
return 'translate(' + (x(getX(d,i)) + x.rangeBand() * .05 ) + ', ' + y(0) + ')'
})
.on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
value: getY(d,i),
point: d,
series: data[d.series],
pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
value: getY(d,i),
point: d,
series: data[d.series],
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
})
.on('click', function(d,i) {
dispatch.elementClick({
value: getY(d,i),
point: d,
series: data[d.series],
pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
dispatch.elementDblClick({
value: getY(d,i),
point: d,
series: data[d.series],
pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
d3.event.stopPropagation();
});
barsEnter.append('rect')
.attr('height', 0)
.attr('width', x.rangeBand() * .9 / data.length )
if (showValues) {
barsEnter.append('text')
.attr('text-anchor', 'middle')
;
bars.select('text')
.text(function(d,i) { return valueFormat(getY(d,i)) })
.transition()
.attr('x', x.rangeBand() * .9 / 2)
.attr('y', function(d,i) { return getY(d,i) < 0 ? y(getY(d,i)) - y(0) + 12 : -4 })
;
} else {
bars.selectAll('text').remove();
}
bars
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive' })
.style('fill', function(d,i) { return d.color || color(d,i) })
.style('stroke', function(d,i) { return d.color || color(d,i) })
.select('rect')
.attr('class', rectClass)
.transition()
.attr('width', x.rangeBand() * .9 / data.length);
bars.transition()
//.delay(function(d,i) { return i * 1200 / data[0].values.length })
.attr('transform', function(d,i) {
var left = x(getX(d,i)) + x.rangeBand() * .05,
top = getY(d,i) < 0 ?
y(0) :
y(0) - y(getY(d,i)) < 1 ?
y(0) - 1 : //make 1 px positive bars show up above y=0
y(getY(d,i));
return 'translate(' + left + ', ' + top + ')'
})
.select('rect')
.attr('height', function(d,i) {
return Math.max(Math.abs(y(getY(d,i)) - y((yDomain && yDomain[0]) || 0)) || 1)
});
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.xScale = function(_) {
if (!arguments.length) return x;
x = _;
return chart;
};
chart.yScale = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.xDomain = function(_) {
if (!arguments.length) return xDomain;
xDomain = _;
return chart;
};
chart.yDomain = function(_) {
if (!arguments.length) return yDomain;
yDomain = _;
return chart;
};
chart.xRange = function(_) {
if (!arguments.length) return xRange;
xRange = _;
return chart;
};
chart.yRange = function(_) {
if (!arguments.length) return yRange;
yRange = _;
return chart;
};
chart.forceY = function(_) {
if (!arguments.length) return forceY;
forceY = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.id = function(_) {
if (!arguments.length) return id;
id = _;
return chart;
};
chart.showValues = function(_) {
if (!arguments.length) return showValues;
showValues = _;
return chart;
};
chart.valueFormat= function(_) {
if (!arguments.length) return valueFormat;
valueFormat = _;
return chart;
};
chart.rectClass= function(_) {
if (!arguments.length) return rectClass;
rectClass = _;
return chart;
};
//============================================================
return chart;
}
nv.models.discreteBarChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var discretebar = nv.models.discreteBar()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
;
var margin = {top: 15, right: 10, bottom: 50, left: 60}
, width = null
, height = null
, color = nv.utils.getColor()
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, staggerLabels = false
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + x + '</h3>' +
'<p>' + y + '</p>'
}
, x
, y
, noData = "No Data Available."
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'beforeUpdate')
, transitionDuration = 250
;
xAxis
.orient('bottom')
.highlightZero(false)
.showMaxMin(false)
.tickFormat(function(d) { return d })
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
.tickFormat(d3.format(',.1f'))
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(discretebar.x()(e.point, e.pointIndex)),
y = yAxis.tickFormat()(discretebar.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() {
dispatch.beforeUpdate();
container.transition().duration(transitionDuration).call(chart);
};
chart.container = this;
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = discretebar.xScale();
y = discretebar.yScale().clamp(true);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-discreteBarWithAxes').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discreteBarWithAxes').append('g');
var defsEnter = gEnter.append('defs');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis')
.append('g').attr('class', 'nv-zeroLine')
.append('line');
gEnter.append('g').attr('class', 'nv-barsWrap');
g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//------------------------------------------------------------
//------------------------------------------------------------
// Main Chart Component(s)
discretebar
.width(availableWidth)
.height(availableHeight);
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d) { return !d.disabled }))
barsWrap.transition().call(discretebar);
//------------------------------------------------------------
defsEnter.append('clipPath')
.attr('id', 'nv-x-label-clip-' + discretebar.id())
.append('rect');
g.select('#nv-x-label-clip-' + discretebar.id() + ' rect')
.attr('width', x.rangeBand() * (staggerLabels ? 2 : 1))
.attr('height', 16)
.attr('x', -x.rangeBand() / (staggerLabels ? 1 : 2 ));
//------------------------------------------------------------
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
.ticks( availableWidth / 100 )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + (y.range()[0] + ((discretebar.showValues() && y.domain()[0] < 0) ? 16 : 0)) + ')');
//d3.transition(g.select('.nv-x.nv-axis'))
g.select('.nv-x.nv-axis').transition()
.call(xAxis);
var xTicks = g.select('.nv-x.nv-axis').selectAll('g');
if (staggerLabels) {
xTicks
.selectAll('text')
.attr('transform', function(d,i,j) { return 'translate(0,' + (j % 2 == 0 ? '5' : '17') + ')' })
}
}
if (showYAxis) {
yAxis
.scale(y)
.ticks( availableHeight / 36 )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis').transition()
.call(yAxis);
}
// Zero line
g.select(".nv-zeroLine line")
.attr("x1",0)
.attr("x2",availableWidth)
.attr("y1", y(0))
.attr("y2", y(0))
;
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
//============================================================
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
discretebar.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
discretebar.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.discretebar = discretebar;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
d3.rebind(chart, discretebar, 'x', 'y', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'id', 'showValues', 'valueFormat');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
discretebar.color(color);
return chart;
};
chart.showXAxis = function(_) {
if (!arguments.length) return showXAxis;
showXAxis = _;
return chart;
};
chart.showYAxis = function(_) {
if (!arguments.length) return showYAxis;
showYAxis = _;
return chart;
};
chart.rightAlignYAxis = function(_) {
if(!arguments.length) return rightAlignYAxis;
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
return chart;
};
chart.staggerLabels = function(_) {
if (!arguments.length) return staggerLabels;
staggerLabels = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
//============================================================
return chart;
}
nv.models.distribution = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 400 //technically width or height depending on x or y....
, size = 8
, axis = 'x' // 'x' or 'y'... horizontal or vertical
, getData = function(d) { return d[axis] } // defaults d.x or d.y
, color = nv.utils.defaultColor()
, scale = d3.scale.linear()
, domain
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var scale0;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableLength = width - (axis === 'x' ? margin.left + margin.right : margin.top + margin.bottom),
naxis = axis == 'x' ? 'y' : 'x',
container = d3.select(this);
//------------------------------------------------------------
// Setup Scales
scale0 = scale0 || scale;
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-distribution').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-distribution');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
//------------------------------------------------------------
var distWrap = g.selectAll('g.nv-dist')
.data(function(d) { return d }, function(d) { return d.key });
distWrap.enter().append('g');
distWrap
.attr('class', function(d,i) { return 'nv-dist nv-series-' + i })
.style('stroke', function(d,i) { return color(d, i) });
var dist = distWrap.selectAll('line.nv-dist' + axis)
.data(function(d) { return d.values })
dist.enter().append('line')
.attr(axis + '1', function(d,i) { return scale0(getData(d,i)) })
.attr(axis + '2', function(d,i) { return scale0(getData(d,i)) })
distWrap.exit().selectAll('line.nv-dist' + axis)
.transition()
.attr(axis + '1', function(d,i) { return scale(getData(d,i)) })
.attr(axis + '2', function(d,i) { return scale(getData(d,i)) })
.style('stroke-opacity', 0)
.remove();
dist
.attr('class', function(d,i) { return 'nv-dist' + axis + ' nv-dist' + axis + '-' + i })
.attr(naxis + '1', 0)
.attr(naxis + '2', size);
dist
.transition()
.attr(axis + '1', function(d,i) { return scale(getData(d,i)) })
.attr(axis + '2', function(d,i) { return scale(getData(d,i)) })
scale0 = scale.copy();
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.axis = function(_) {
if (!arguments.length) return axis;
axis = _;
return chart;
};
chart.size = function(_) {
if (!arguments.length) return size;
size = _;
return chart;
};
chart.getData = function(_) {
if (!arguments.length) return getData;
getData = d3.functor(_);
return chart;
};
chart.scale = function(_) {
if (!arguments.length) return scale;
scale = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
//============================================================
return chart;
}
nv.models.historicalBarChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var bars = nv.models.historicalBar()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
;
var margin = {top: 30, right: 90, bottom: 50, left: 90}
, color = nv.utils.defaultColor()
, width = null
, height = null
, showLegend = false
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' at ' + x + '</p>'
}
, x
, y
, state = {}
, defaultState = null
, noData = 'No Data Available.'
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
, transitionDuration = 250
;
xAxis
.orient('bottom')
.tickPadding(7)
;
yAxis
.orient( (rightAlignYAxis) ? 'right' : 'left')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
// New addition to calculate position if SVG is scaled with viewBox, may move TODO: consider implementing everywhere else
if (offsetElement) {
var svg = d3.select(offsetElement).select('svg');
var viewBox = (svg.node()) ? svg.attr('viewBox') : null;
if (viewBox) {
viewBox = viewBox.split(' ');
var ratio = parseInt(svg.style('width')) / viewBox[2];
e.pos[0] = e.pos[0] * ratio;
e.pos[1] = e.pos[1] * ratio;
}
}
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(bars.x()(e.point, e.pointIndex)),
y = yAxis.tickFormat()(bars.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, null, null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
//------------------------------------------------------------
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = bars.xScale();
y = bars.yScale();
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-historicalBarChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-historicalBarChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-barsWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width(availableWidth);
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')')
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//------------------------------------------------------------
// Main Chart Component(s)
bars
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d) { return !d.disabled }))
barsWrap.transition().call(bars);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
g.select('.nv-x.nv-axis')
.transition()
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
.ticks( availableHeight / 36 )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis')
.transition()
.call(yAxis);
}
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('legendClick', function(d,i) {
d.disabled = !d.disabled;
if (!data.filter(function(d) { return !d.disabled }).length) {
data.map(function(d) {
d.disabled = false;
wrap.selectAll('.nv-series').classed('disabled', false);
return d;
});
}
state.disabled = data.map(function(d) { return !!d.disabled });
dispatch.stateChange(state);
selection.transition().call(chart);
});
legend.dispatch.on('legendDblclick', function(d) {
//Double clicking should always enable current series, and disabled all others.
data.forEach(function(d) {
d.disabled = true;
});
d.disabled = false;
state.disabled = data.map(function(d) { return !!d.disabled });
dispatch.stateChange(state);
chart.update();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
//============================================================
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
bars.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
bars.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.bars = bars;
chart.legend = legend;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
d3.rebind(chart, bars, 'defined', 'isArea', 'x', 'y', 'size', 'xScale', 'yScale',
'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id', 'interpolate','highlightPoint','clearHighlights', 'interactive');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.showXAxis = function(_) {
if (!arguments.length) return showXAxis;
showXAxis = _;
return chart;
};
chart.showYAxis = function(_) {
if (!arguments.length) return showYAxis;
showYAxis = _;
return chart;
};
chart.rightAlignYAxis = function(_) {
if(!arguments.length) return rightAlignYAxis;
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
//============================================================
return chart;
}
nv.models.indentedTree = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0} //TODO: implement, maybe as margin on the containing div
, width = 960
, height = 500
, color = nv.utils.defaultColor()
, id = Math.floor(Math.random() * 10000)
, header = true
, filterZero = false
, noData = "No Data Available."
, childIndent = 20
, columns = [{key:'key', label: 'Name', type:'text'}] //TODO: consider functions like chart.addColumn, chart.removeColumn, instead of a block like this
, tableClass = null
, iconOpen = 'images/grey-plus.png' //TODO: consider removing this and replacing with a '+' or '-' unless user defines images
, iconClose = 'images/grey-minus.png'
, dispatch = d3.dispatch('elementClick', 'elementDblclick', 'elementMouseover', 'elementMouseout')
, getUrl = function(d) { return d.url }
;
//============================================================
var idx = 0;
function chart(selection) {
selection.each(function(data) {
var depth = 1,
container = d3.select(this);
var tree = d3.layout.tree()
.children(function(d) { return d.values })
.size([height, childIndent]); //Not sure if this is needed now that the result is HTML
chart.update = function() { container.transition().duration(600).call(chart) };
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data[0]) data[0] = {key: noData};
//------------------------------------------------------------
var nodes = tree.nodes(data[0]);
// nodes.map(function(d) {
// d.id = i++;
// })
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = d3.select(this).selectAll('div').data([[nodes]]);
var wrapEnter = wrap.enter().append('div').attr('class', 'nvd3 nv-wrap nv-indentedtree');
var tableEnter = wrapEnter.append('table');
var table = wrap.select('table').attr('width', '100%').attr('class', tableClass);
//------------------------------------------------------------
if (header) {
var thead = tableEnter.append('thead');
var theadRow1 = thead.append('tr');
columns.forEach(function(column) {
theadRow1
.append('th')
.attr('width', column.width ? column.width : '10%')
.style('text-align', column.type == 'numeric' ? 'right' : 'left')
.append('span')
.text(column.label);
});
}
var tbody = table.selectAll('tbody')
.data(function(d) { return d });
tbody.enter().append('tbody');
//compute max generations
depth = d3.max(nodes, function(node) { return node.depth });
tree.size([height, depth * childIndent]); //TODO: see if this is necessary at all
// Update the nodes…
var node = tbody.selectAll('tr')
// .data(function(d) { return d; }, function(d) { return d.id || (d.id == ++i)});
.data(function(d) { return d.filter(function(d) { return (filterZero && !d.children) ? filterZero(d) : true; } )}, function(d,i) { return d.id || (d.id || ++idx)});
//.style('display', 'table-row'); //TODO: see if this does anything
node.exit().remove();
node.select('img.nv-treeicon')
.attr('src', icon)
.classed('folded', folded);
var nodeEnter = node.enter().append('tr');
columns.forEach(function(column, index) {
var nodeName = nodeEnter.append('td')
.style('padding-left', function(d) { return (index ? 0 : d.depth * childIndent + 12 + (icon(d) ? 0 : 16)) + 'px' }, 'important') //TODO: check why I did the ternary here
.style('text-align', column.type == 'numeric' ? 'right' : 'left');
if (index == 0) {
nodeName.append('img')
.classed('nv-treeicon', true)
.classed('nv-folded', folded)
.attr('src', icon)
.style('width', '14px')
.style('height', '14px')
.style('padding', '0 1px')
.style('display', function(d) { return icon(d) ? 'inline-block' : 'none'; })
.on('click', click);
}
nodeName.each(function(d) {
if (!index && getUrl(d))
d3.select(this)
.append('a')
.attr('href',getUrl)
.attr('class', d3.functor(column.classes))
.append('span')
else
d3.select(this)
.append('span')
d3.select(this).select('span')
.attr('class', d3.functor(column.classes) )
.text(function(d) { return column.format ? (d[column.key] ? column.format(d[column.key]) : '-') : (d[column.key] || '-'); });
});
if (column.showCount) {
nodeName.append('span')
.attr('class', 'nv-childrenCount');
node.selectAll('span.nv-childrenCount').text(function(d) {
return ((d.values && d.values.length) || (d._values && d._values.length)) ? //If this is a parent
'(' + ((d.values && (d.values.filter(function(d) { return filterZero ? filterZero(d) : true; }).length)) //If children are in values check its children and filter
|| (d._values && d._values.filter(function(d) { return filterZero ? filterZero(d) : true; }).length) //Otherwise, do the same, but with the other name, _values...
|| 0) + ')' //This is the catch-all in case there are no children after a filter
: '' //If this is not a parent, just give an empty string
});
}
// if (column.click)
// nodeName.select('span').on('click', column.click);
});
node
.order()
.on('click', function(d) {
dispatch.elementClick({
row: this, //TODO: decide whether or not this should be consistent with scatter/line events or should be an html link (a href)
data: d,
pos: [d.x, d.y]
});
})
.on('dblclick', function(d) {
dispatch.elementDblclick({
row: this,
data: d,
pos: [d.x, d.y]
});
})
.on('mouseover', function(d) {
dispatch.elementMouseover({
row: this,
data: d,
pos: [d.x, d.y]
});
})
.on('mouseout', function(d) {
dispatch.elementMouseout({
row: this,
data: d,
pos: [d.x, d.y]
});
});
// Toggle children on click.
function click(d, _, unshift) {
d3.event.stopPropagation();
if(d3.event.shiftKey && !unshift) {
//If you shift-click, it'll toggle fold all the children, instead of itself
d3.event.shiftKey = false;
d.values && d.values.forEach(function(node){
if (node.values || node._values) {
click(node, 0, true);
}
});
return true;
}
if(!hasChildren(d)) {
//download file
//window.location.href = d.url;
return true;
}
if (d.values) {
d._values = d.values;
d.values = null;
} else {
d.values = d._values;
d._values = null;
}
chart.update();
}
function icon(d) {
return (d._values && d._values.length) ? iconOpen : (d.values && d.values.length) ? iconClose : '';
}
function folded(d) {
return (d._values && d._values.length);
}
function hasChildren(d) {
var values = d.values || d._values;
return (values && values.length);
}
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
scatter.color(color);
return chart;
};
chart.id = function(_) {
if (!arguments.length) return id;
id = _;
return chart;
};
chart.header = function(_) {
if (!arguments.length) return header;
header = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.filterZero = function(_) {
if (!arguments.length) return filterZero;
filterZero = _;
return chart;
};
chart.columns = function(_) {
if (!arguments.length) return columns;
columns = _;
return chart;
};
chart.tableClass = function(_) {
if (!arguments.length) return tableClass;
tableClass = _;
return chart;
};
chart.iconOpen = function(_){
if (!arguments.length) return iconOpen;
iconOpen = _;
return chart;
}
chart.iconClose = function(_){
if (!arguments.length) return iconClose;
iconClose = _;
return chart;
}
chart.getUrl = function(_){
if (!arguments.length) return getUrl;
getUrl = _;
return chart;
}
//============================================================
return chart;
};nv.models.legend = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 5, right: 0, bottom: 5, left: 0}
, width = 400
, height = 20
, getKey = function(d) { return d.key }
, color = nv.utils.defaultColor()
, align = true
, rightAlign = true
, updateState = true //If true, legend will update data.disabled and trigger a 'stateChange' dispatch.
, radioButtonMode = false //If true, clicking legend items will cause it to behave like a radio button. (only one can be selected at a time)
, dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout', 'stateChange')
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
container = d3.select(this);
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-legend').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g');
var g = wrap.select('g');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
var series = g.selectAll('.nv-series')
.data(function(d) { return d });
var seriesEnter = series.enter().append('g').attr('class', 'nv-series')
.on('mouseover', function(d,i) {
dispatch.legendMouseover(d,i); //TODO: Make consistent with other event objects
})
.on('mouseout', function(d,i) {
dispatch.legendMouseout(d,i);
})
.on('click', function(d,i) {
dispatch.legendClick(d,i);
if (updateState) {
if (radioButtonMode) {
//Radio button mode: set every series to disabled,
// and enable the clicked series.
data.forEach(function(series) { series.disabled = true});
d.disabled = false;
}
else {
d.disabled = !d.disabled;
if (data.every(function(series) { return series.disabled})) {
//the default behavior of NVD3 legends is, if every single series
// is disabled, turn all series' back on.
data.forEach(function(series) { series.disabled = false});
}
}
dispatch.stateChange({
disabled: data.map(function(d) { return !!d.disabled })
});
}
})
.on('dblclick', function(d,i) {
dispatch.legendDblclick(d,i);
if (updateState) {
//the default behavior of NVD3 legends, when double clicking one,
// is to set all other series' to false, and make the double clicked series enabled.
data.forEach(function(series) {
series.disabled = true;
});
d.disabled = false;
dispatch.stateChange({
disabled: data.map(function(d) { return !!d.disabled })
});
}
});
seriesEnter.append('circle')
.style('stroke-width', 2)
.attr('class','nv-legend-symbol')
.attr('r', 5);
seriesEnter.append('text')
.attr('text-anchor', 'start')
.attr('class','nv-legend-text')
.attr('dy', '.32em')
.attr('dx', '8');
series.classed('disabled', function(d) { return d.disabled });
series.exit().remove();
series.select('circle')
.style('fill', function(d,i) { return d.color || color(d,i)})
.style('stroke', function(d,i) { return d.color || color(d, i) });
series.select('text').text(getKey);
//TODO: implement fixed-width and max-width options (max-width is especially useful with the align option)
// NEW ALIGNING CODE, TODO: clean up
if (align) {
var seriesWidths = [];
series.each(function(d,i) {
var legendText = d3.select(this).select('text');
var nodeTextLength;
try {
nodeTextLength = legendText.getComputedTextLength();
// If the legendText is display:none'd (nodeTextLength == 0), simulate an error so we approximate, instead
if(nodeTextLength <= 0) throw Error();
}
catch(e) {
nodeTextLength = nv.utils.calcApproxTextWidth(legendText);
}
seriesWidths.push(nodeTextLength + 28); // 28 is ~ the width of the circle plus some padding
});
var seriesPerRow = 0;
var legendWidth = 0;
var columnWidths = [];
while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) {
columnWidths[seriesPerRow] = seriesWidths[seriesPerRow];
legendWidth += seriesWidths[seriesPerRow++];
}
if (seriesPerRow === 0) seriesPerRow = 1; //minimum of one series per row
while ( legendWidth > availableWidth && seriesPerRow > 1 ) {
columnWidths = [];
seriesPerRow--;
for (var k = 0; k < seriesWidths.length; k++) {
if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) )
columnWidths[k % seriesPerRow] = seriesWidths[k];
}
legendWidth = columnWidths.reduce(function(prev, cur, index, array) {
return prev + cur;
});
}
var xPositions = [];
for (var i = 0, curX = 0; i < seriesPerRow; i++) {
xPositions[i] = curX;
curX += columnWidths[i];
}
series
.attr('transform', function(d, i) {
return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * 20) + ')';
});
//position legend as far right as possible within the total width
if (rightAlign) {
g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')');
}
else {
g.attr('transform', 'translate(0' + ',' + margin.top + ')');
}
height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * 20);
} else {
var ypos = 5,
newxpos = 5,
maxwidth = 0,
xpos;
series
.attr('transform', function(d, i) {
var length = d3.select(this).select('text').node().getComputedTextLength() + 28;
xpos = newxpos;
if (width < margin.left + margin.right + xpos + length) {
newxpos = xpos = 5;
ypos += 20;
}
newxpos += length;
if (newxpos > maxwidth) maxwidth = newxpos;
return 'translate(' + xpos + ',' + ypos + ')';
});
//position legend as far right as possible within the total width
g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')');
height = margin.top + margin.bottom + ypos + 15;
}
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.key = function(_) {
if (!arguments.length) return getKey;
getKey = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.align = function(_) {
if (!arguments.length) return align;
align = _;
return chart;
};
chart.rightAlign = function(_) {
if (!arguments.length) return rightAlign;
rightAlign = _;
return chart;
};
chart.updateState = function(_) {
if (!arguments.length) return updateState;
updateState = _;
return chart;
};
chart.radioButtonMode = function(_) {
if (!arguments.length) return radioButtonMode;
radioButtonMode = _;
return chart;
};
//============================================================
return chart;
}
nv.models.line = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var scatter = nv.models.scatter()
;
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, color = nv.utils.defaultColor() // a function that returns a color
, getX = function(d) { return d.x } // accessor to get the x value from a data point
, getY = function(d) { return d.y } // accessor to get the y value from a data point
, defined = function(d,i) { return !isNaN(getY(d,i)) && getY(d,i) !== null } // allows a line to be not continuous when it is not defined
, isArea = function(d) { return d.area } // decides if a line is an area or just a line
, clipEdge = false // if true, masks lines within x and y scale
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, interpolate = "linear" // controls the line interpolation
;
scatter
.size(16) // default size
.sizeDomain([16,256]) //set to speed up calculation, needs to be unset if there is a custom size accessor
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0 //used to store previous scales
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
//------------------------------------------------------------
// Setup Scales
x = scatter.xScale();
y = scatter.yScale();
x0 = x0 || x;
y0 = y0 || y;
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-line').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-line');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g')
gEnter.append('g').attr('class', 'nv-groups');
gEnter.append('g').attr('class', 'nv-scatterWrap');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
scatter
.width(availableWidth)
.height(availableHeight)
var scatterWrap = wrap.select('.nv-scatterWrap');
//.datum(data); // Data automatically trickles down from the wrap
scatterWrap.transition().call(scatter);
defsEnter.append('clipPath')
.attr('id', 'nv-edge-clip-' + scatter.id())
.append('rect');
wrap.select('#nv-edge-clip-' + scatter.id() + ' rect')
.attr('width', availableWidth)
.attr('height', (availableHeight > 0) ? availableHeight : 0);
g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : '');
scatterWrap
.attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : '');
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d) { return d.key });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6);
groups.exit().remove();
groups
.attr('class', function(d,i) { return 'nv-group nv-series-' + i })
.classed('hover', function(d) { return d.hover })
.style('fill', function(d,i){ return color(d, i) })
.style('stroke', function(d,i){ return color(d, i)});
groups
.transition()
.style('stroke-opacity', 1)
.style('fill-opacity', .5);
var areaPaths = groups.selectAll('path.nv-area')
.data(function(d) { return isArea(d) ? [d] : [] }); // this is done differently than lines because I need to check if series is an area
areaPaths.enter().append('path')
.attr('class', 'nv-area')
.attr('d', function(d) {
return d3.svg.area()
.interpolate(interpolate)
.defined(defined)
.x(function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) })
.y0(function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) })
.y1(function(d,i) { return y0( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) })
//.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this
.apply(this, [d.values])
});
groups.exit().selectAll('path.nv-area')
.remove();
areaPaths
.transition()
.attr('d', function(d) {
return d3.svg.area()
.interpolate(interpolate)
.defined(defined)
.x(function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
.y0(function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
.y1(function(d,i) { return y( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) })
//.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this
.apply(this, [d.values])
});
var linePaths = groups.selectAll('path.nv-line')
.data(function(d) { return [d.values] });
linePaths.enter().append('path')
.attr('class', 'nv-line')
.attr('d',
d3.svg.line()
.interpolate(interpolate)
.defined(defined)
.x(function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) })
.y(function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) })
);
linePaths
.transition()
.attr('d',
d3.svg.line()
.interpolate(interpolate)
.defined(defined)
.x(function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
.y(function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
);
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = scatter.dispatch;
chart.scatter = scatter;
d3.rebind(chart, scatter, 'id', 'interactive', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'xRange', 'yRange',
'sizeDomain', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'useVoronoi', 'clipRadius', 'padData','highlightPoint','clearHighlights');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
scatter.x(_);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
scatter.y(_);
return chart;
};
chart.clipEdge = function(_) {
if (!arguments.length) return clipEdge;
clipEdge = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
scatter.color(color);
return chart;
};
chart.interpolate = function(_) {
if (!arguments.length) return interpolate;
interpolate = _;
return chart;
};
chart.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return chart;
};
chart.isArea = function(_) {
if (!arguments.length) return isArea;
isArea = d3.functor(_);
return chart;
};
//============================================================
return chart;
}
nv.models.lineChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var lines = nv.models.line()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, interactiveLayer = nv.interactiveGuideline()
;
var margin = {top: 30, right: 20, bottom: 50, left: 60}
, color = nv.utils.defaultColor()
, width = null
, height = null
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, useInteractiveGuideline = false
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' at ' + x + '</p>'
}
, x
, y
, state = {}
, defaultState = null
, noData = 'No Data Available.'
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
, transitionDuration = 250
;
xAxis
.orient('bottom')
.tickPadding(7)
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)),
y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, null, null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
//------------------------------------------------------------
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = lines.xScale();
y = lines.yScale();
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-lineChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineChart').append('g');
var g = wrap.select('g');
gEnter.append("rect").style("opacity",0);
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-linesWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-interactive');
g.select("rect")
.attr("width",availableWidth)
.attr("height",(availableHeight > 0) ? availableHeight : 0);
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width(availableWidth);
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')')
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//------------------------------------------------------------
// Main Chart Component(s)
//------------------------------------------------------------
//Set up interactive layer
if (useInteractiveGuideline) {
interactiveLayer
.width(availableWidth)
.height(availableHeight)
.margin({left:margin.left, top:margin.top})
.svgContainer(container)
.xScale(x);
wrap.select(".nv-interactive").call(interactiveLayer);
}
lines
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
var linesWrap = g.select('.nv-linesWrap')
.datum(data.filter(function(d) { return !d.disabled }))
linesWrap.transition().call(lines);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
.ticks( availableWidth / 100 )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
g.select('.nv-x.nv-axis')
.transition()
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
.ticks( availableHeight / 36 )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis')
.transition()
.call(yAxis);
}
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
state = newState;
dispatch.stateChange(state);
chart.update();
});
interactiveLayer.dispatch.on('elementMousemove', function(e) {
lines.clearHighlights();
var singlePoint, pointIndex, pointXLocation, allData = [];
data
.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled;
})
.forEach(function(series,i) {
pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
lines.highlightPoint(i, pointIndex, true);
var point = series.values[pointIndex];
if (typeof point === 'undefined') return;
if (typeof singlePoint === 'undefined') singlePoint = point;
if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
allData.push({
key: series.key,
value: chart.y()(point, pointIndex),
color: color(series,series.seriesIndex)
});
});
//Highlight the tooltip entry based on which point the mouse is closest to.
if (allData.length > 2) {
var yValue = chart.yScale().invert(e.mouseY);
var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]);
var threshold = 0.03 * domainExtent;
var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold);
if (indexToHighlight !== null)
allData[indexToHighlight].highlight = true;
}
var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex));
interactiveLayer.tooltip
.position({left: pointXLocation + margin.left, top: e.mouseY + margin.top})
.chartContainer(that.parentNode)
.enabled(tooltips)
.valueFormatter(function(d,i) {
return yAxis.tickFormat()(d);
})
.data(
{
value: xValue,
series: allData
}
)();
interactiveLayer.renderGuideLine(pointXLocation);
});
interactiveLayer.dispatch.on("elementMouseout",function(e) {
dispatch.tooltipHide();
lines.clearHighlights();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined' && data.length === e.disabled.length) {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
//============================================================
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
lines.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
lines.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.lines = lines;
chart.legend = legend;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.interactiveLayer = interactiveLayer;
d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'xRange', 'yRange'
, 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'useVoronoi','id', 'interpolate');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.showXAxis = function(_) {
if (!arguments.length) return showXAxis;
showXAxis = _;
return chart;
};
chart.showYAxis = function(_) {
if (!arguments.length) return showYAxis;
showYAxis = _;
return chart;
};
chart.rightAlignYAxis = function(_) {
if(!arguments.length) return rightAlignYAxis;
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
return chart;
};
chart.useInteractiveGuideline = function(_) {
if(!arguments.length) return useInteractiveGuideline;
useInteractiveGuideline = _;
if (_ === true) {
chart.interactive(false);
chart.useVoronoi(false);
}
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
//============================================================
return chart;
}
nv.models.linePlusBarChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var lines = nv.models.line()
, bars = nv.models.historicalBar()
, xAxis = nv.models.axis()
, y1Axis = nv.models.axis()
, y2Axis = nv.models.axis()
, legend = nv.models.legend()
;
var margin = {top: 30, right: 60, bottom: 50, left: 60}
, width = null
, height = null
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, color = nv.utils.defaultColor()
, showLegend = true
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' at ' + x + '</p>';
}
, x
, y1
, y2
, state = {}
, defaultState = null
, noData = "No Data Available."
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
;
bars
.padData(true)
;
lines
.clipEdge(false)
.padData(true)
;
xAxis
.orient('bottom')
.tickPadding(7)
.highlightZero(false)
;
y1Axis
.orient('left')
;
y2Axis
.orient('right')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)),
y = (e.series.bar ? y1Axis : y2Axis).tickFormat()(lines.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement);
}
;
//------------------------------------------------------------
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().call(chart); };
// chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
var dataBars = data.filter(function(d) { return !d.disabled && d.bar });
var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240
//x = xAxis.scale();
x = dataLines.filter(function(d) { return !d.disabled; }).length && dataLines.filter(function(d) { return !d.disabled; })[0].values.length ? lines.xScale() : bars.xScale();
//x = dataLines.filter(function(d) { return !d.disabled; }).length ? lines.xScale() : bars.xScale(); //old code before change above
y1 = bars.yScale();
y2 = lines.yScale();
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-linePlusBar').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y1 nv-axis');
gEnter.append('g').attr('class', 'nv-y2 nv-axis');
gEnter.append('g').attr('class', 'nv-barsWrap');
gEnter.append('g').attr('class', 'nv-linesWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width( availableWidth / 2 );
g.select('.nv-legendWrap')
.datum(data.map(function(series) {
series.originalKey = series.originalKey === undefined ? series.key : series.originalKey;
series.key = series.originalKey + (series.bar ? ' (left axis)' : ' (right axis)');
return series;
}))
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')');
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
// Main Chart Component(s)
lines
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && !data[i].bar }))
bars
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && data[i].bar }))
var barsWrap = g.select('.nv-barsWrap')
.datum(dataBars.length ? dataBars : [{values:[]}])
var linesWrap = g.select('.nv-linesWrap')
.datum(dataLines[0] && !dataLines[0].disabled ? dataLines : [{values:[]}] );
//.datum(!dataLines[0].disabled ? dataLines : [{values:dataLines[0].values.map(function(d) { return [d[0], null] }) }] );
d3.transition(barsWrap).call(bars);
d3.transition(linesWrap).call(lines);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
xAxis
.scale(x)
.ticks( availableWidth / 100 )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y1.range()[0] + ')');
d3.transition(g.select('.nv-x.nv-axis'))
.call(xAxis);
y1Axis
.scale(y1)
.ticks( availableHeight / 36 )
.tickSize(-availableWidth, 0);
d3.transition(g.select('.nv-y1.nv-axis'))
.style('opacity', dataBars.length ? 1 : 0)
.call(y1Axis);
y2Axis
.scale(y2)
.ticks( availableHeight / 36 )
.tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none
g.select('.nv-y2.nv-axis')
.style('opacity', dataLines.length ? 1 : 0)
.attr('transform', 'translate(' + availableWidth + ',0)');
//.attr('transform', 'translate(' + x.range()[1] + ',0)');
d3.transition(g.select('.nv-y2.nv-axis'))
.call(y2Axis);
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
state = newState;
dispatch.stateChange(state);
chart.update();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
//============================================================
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
lines.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
lines.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
bars.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
bars.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.legend = legend;
chart.lines = lines;
chart.bars = bars;
chart.xAxis = xAxis;
chart.y1Axis = y1Axis;
chart.y2Axis = y2Axis;
d3.rebind(chart, lines, 'defined', 'size', 'clipVoronoi', 'interpolate');
//TODO: consider rebinding x, y and some other stuff, and simply do soemthign lile bars.x(lines.x()), etc.
//d3.rebind(chart, lines, 'x', 'y', 'size', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
lines.x(_);
bars.x(_);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
lines.y(_);
bars.y(_);
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
//============================================================
return chart;
}
nv.models.lineWithFocusChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var lines = nv.models.line()
, lines2 = nv.models.line()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, x2Axis = nv.models.axis()
, y2Axis = nv.models.axis()
, legend = nv.models.legend()
, brush = d3.svg.brush()
;
var margin = {top: 30, right: 30, bottom: 30, left: 60}
, margin2 = {top: 0, right: 30, bottom: 20, left: 60}
, color = nv.utils.defaultColor()
, width = null
, height = null
, height2 = 100
, x
, y
, x2
, y2
, showLegend = true
, brushExtent = null
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' at ' + x + '</p>'
}
, noData = "No Data Available."
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'brush')
, transitionDuration = 250
;
lines
.clipEdge(true)
;
lines2
.interactive(false)
;
xAxis
.orient('bottom')
.tickPadding(5)
;
yAxis
.orient('left')
;
x2Axis
.orient('bottom')
.tickPadding(5)
;
y2Axis
.orient('left')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)),
y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, null, null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight1 = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom - height2,
availableHeight2 = height2 - margin2.top - margin2.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
chart.container = this;
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight1 / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = lines.xScale();
y = lines.yScale();
x2 = lines2.xScale();
y2 = lines2.yScale();
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-lineWithFocusChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineWithFocusChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-legendWrap');
var focusEnter = gEnter.append('g').attr('class', 'nv-focus');
focusEnter.append('g').attr('class', 'nv-x nv-axis');
focusEnter.append('g').attr('class', 'nv-y nv-axis');
focusEnter.append('g').attr('class', 'nv-linesWrap');
var contextEnter = gEnter.append('g').attr('class', 'nv-context');
contextEnter.append('g').attr('class', 'nv-x nv-axis');
contextEnter.append('g').attr('class', 'nv-y nv-axis');
contextEnter.append('g').attr('class', 'nv-linesWrap');
contextEnter.append('g').attr('class', 'nv-brushBackground');
contextEnter.append('g').attr('class', 'nv-x nv-brush');
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width(availableWidth);
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight1 = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom - height2;
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')')
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
// Main Chart Component(s)
lines
.width(availableWidth)
.height(availableHeight1)
.color(
data
.map(function(d,i) {
return d.color || color(d, i);
})
.filter(function(d,i) {
return !data[i].disabled;
})
);
lines2
.defined(lines.defined())
.width(availableWidth)
.height(availableHeight2)
.color(
data
.map(function(d,i) {
return d.color || color(d, i);
})
.filter(function(d,i) {
return !data[i].disabled;
})
);
g.select('.nv-context')
.attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')')
var contextLinesWrap = g.select('.nv-context .nv-linesWrap')
.datum(data.filter(function(d) { return !d.disabled }))
d3.transition(contextLinesWrap).call(lines2);
//------------------------------------------------------------
/*
var focusLinesWrap = g.select('.nv-focus .nv-linesWrap')
.datum(data.filter(function(d) { return !d.disabled }))
d3.transition(focusLinesWrap).call(lines);
*/
//------------------------------------------------------------
// Setup Main (Focus) Axes
xAxis
.scale(x)
.ticks( availableWidth / 100 )
.tickSize(-availableHeight1, 0);
yAxis
.scale(y)
.ticks( availableHeight1 / 36 )
.tickSize( -availableWidth, 0);
g.select('.nv-focus .nv-x.nv-axis')
.attr('transform', 'translate(0,' + availableHeight1 + ')');
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Brush
brush
.x(x2)
.on('brush', function() {
//When brushing, turn off transitions because chart needs to change immediately.
var oldTransition = chart.transitionDuration();
chart.transitionDuration(0);
onBrush();
chart.transitionDuration(oldTransition);
});
if (brushExtent) brush.extent(brushExtent);
var brushBG = g.select('.nv-brushBackground').selectAll('g')
.data([brushExtent || brush.extent()])
var brushBGenter = brushBG.enter()
.append('g');
brushBGenter.append('rect')
.attr('class', 'left')
.attr('x', 0)
.attr('y', 0)
.attr('height', availableHeight2);
brushBGenter.append('rect')
.attr('class', 'right')
.attr('x', 0)
.attr('y', 0)
.attr('height', availableHeight2);
var gBrush = g.select('.nv-x.nv-brush')
.call(brush);
gBrush.selectAll('rect')
//.attr('y', -5)
.attr('height', availableHeight2);
gBrush.selectAll('.resize').append('path').attr('d', resizePath);
onBrush();
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Secondary (Context) Axes
x2Axis
.scale(x2)
.ticks( availableWidth / 100 )
.tickSize(-availableHeight2, 0);
g.select('.nv-context .nv-x.nv-axis')
.attr('transform', 'translate(0,' + y2.range()[0] + ')');
d3.transition(g.select('.nv-context .nv-x.nv-axis'))
.call(x2Axis);
y2Axis
.scale(y2)
.ticks( availableHeight2 / 36 )
.tickSize( -availableWidth, 0);
d3.transition(g.select('.nv-context .nv-y.nv-axis'))
.call(y2Axis);
g.select('.nv-context .nv-x.nv-axis')
.attr('transform', 'translate(0,' + y2.range()[0] + ')');
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
chart.update();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
//============================================================
//============================================================
// Functions
//------------------------------------------------------------
// Taken from crossfilter (http://square.github.com/crossfilter/)
function resizePath(d) {
var e = +(d == 'e'),
x = e ? 1 : -1,
y = availableHeight2 / 3;
return 'M' + (.5 * x) + ',' + y
+ 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6)
+ 'V' + (2 * y - 6)
+ 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y)
+ 'Z'
+ 'M' + (2.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8)
+ 'M' + (4.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8);
}
function updateBrushBG() {
if (!brush.empty()) brush.extent(brushExtent);
brushBG
.data([brush.empty() ? x2.domain() : brushExtent])
.each(function(d,i) {
var leftWidth = x2(d[0]) - x.range()[0],
rightWidth = x.range()[1] - x2(d[1]);
d3.select(this).select('.left')
.attr('width', leftWidth < 0 ? 0 : leftWidth);
d3.select(this).select('.right')
.attr('x', x2(d[1]))
.attr('width', rightWidth < 0 ? 0 : rightWidth);
});
}
function onBrush() {
brushExtent = brush.empty() ? null : brush.extent();
var extent = brush.empty() ? x2.domain() : brush.extent();
//The brush extent cannot be less than one. If it is, don't update the line chart.
if (Math.abs(extent[0] - extent[1]) <= 1) {
return;
}
dispatch.brush({extent: extent, brush: brush});
updateBrushBG();
// Update Main (Focus)
var focusLinesWrap = g.select('.nv-focus .nv-linesWrap')
.datum(
data
.filter(function(d) { return !d.disabled })
.map(function(d,i) {
return {
key: d.key,
values: d.values.filter(function(d,i) {
return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1];
})
}
})
);
focusLinesWrap.transition().duration(transitionDuration).call(lines);
// Update Main (Focus) Axes
g.select('.nv-focus .nv-x.nv-axis').transition().duration(transitionDuration)
.call(xAxis);
g.select('.nv-focus .nv-y.nv-axis').transition().duration(transitionDuration)
.call(yAxis);
}
//============================================================
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
lines.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
lines.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.legend = legend;
chart.lines = lines;
chart.lines2 = lines2;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.x2Axis = x2Axis;
chart.y2Axis = y2Axis;
d3.rebind(chart, lines, 'defined', 'isArea', 'size', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return lines.x;
lines.x(_);
lines2.x(_);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return lines.y;
lines.y(_);
lines2.y(_);
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.margin2 = function(_) {
if (!arguments.length) return margin2;
margin2 = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.height2 = function(_) {
if (!arguments.length) return height2;
height2 = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color =nv.utils.getColor(_);
legend.color(color);
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.interpolate = function(_) {
if (!arguments.length) return lines.interpolate();
lines.interpolate(_);
lines2.interpolate(_);
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
// Chart has multiple similar Axes, to prevent code duplication, probably need to link all axis functions manually like below
chart.xTickFormat = function(_) {
if (!arguments.length) return xAxis.tickFormat();
xAxis.tickFormat(_);
x2Axis.tickFormat(_);
return chart;
};
chart.yTickFormat = function(_) {
if (!arguments.length) return yAxis.tickFormat();
yAxis.tickFormat(_);
y2Axis.tickFormat(_);
return chart;
};
chart.brushExtent = function(_) {
if (!arguments.length) return brushExtent;
brushExtent = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
//============================================================
return chart;
}
nv.models.linePlusBarWithFocusChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var lines = nv.models.line()
, lines2 = nv.models.line()
, bars = nv.models.historicalBar()
, bars2 = nv.models.historicalBar()
, xAxis = nv.models.axis()
, x2Axis = nv.models.axis()
, y1Axis = nv.models.axis()
, y2Axis = nv.models.axis()
, y3Axis = nv.models.axis()
, y4Axis = nv.models.axis()
, legend = nv.models.legend()
, brush = d3.svg.brush()
;
var margin = {top: 30, right: 30, bottom: 30, left: 60}
, margin2 = {top: 0, right: 30, bottom: 20, left: 60}
, width = null
, height = null
, height2 = 100
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, color = nv.utils.defaultColor()
, showLegend = true
, extent
, brushExtent = null
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' at ' + x + '</p>';
}
, x
, x2
, y1
, y2
, y3
, y4
, noData = "No Data Available."
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'brush')
, transitionDuration = 0
;
lines
.clipEdge(true)
;
lines2
.interactive(false)
;
xAxis
.orient('bottom')
.tickPadding(5)
;
y1Axis
.orient('left')
;
y2Axis
.orient('right')
;
x2Axis
.orient('bottom')
.tickPadding(5)
;
y3Axis
.orient('left')
;
y4Axis
.orient('right')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
if (extent) {
e.pointIndex += Math.ceil(extent[0]);
}
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)),
y = (e.series.bar ? y1Axis : y2Axis).tickFormat()(lines.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement);
};
//------------------------------------------------------------
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight1 = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom - height2,
availableHeight2 = height2 - margin2.top - margin2.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart); };
chart.container = this;
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight1 / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
var dataBars = data.filter(function(d) { return !d.disabled && d.bar });
var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240
x = bars.xScale();
x2 = x2Axis.scale();
y1 = bars.yScale();
y2 = lines.yScale();
y3 = bars2.yScale();
y4 = lines2.yScale();
var series1 = data
.filter(function(d) { return !d.disabled && d.bar })
.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i) }
})
});
var series2 = data
.filter(function(d) { return !d.disabled && !d.bar })
.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i) }
})
});
x .range([0, availableWidth]);
x2 .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } ))
.range([0, availableWidth]);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-linePlusBar').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-legendWrap');
var focusEnter = gEnter.append('g').attr('class', 'nv-focus');
focusEnter.append('g').attr('class', 'nv-x nv-axis');
focusEnter.append('g').attr('class', 'nv-y1 nv-axis');
focusEnter.append('g').attr('class', 'nv-y2 nv-axis');
focusEnter.append('g').attr('class', 'nv-barsWrap');
focusEnter.append('g').attr('class', 'nv-linesWrap');
var contextEnter = gEnter.append('g').attr('class', 'nv-context');
contextEnter.append('g').attr('class', 'nv-x nv-axis');
contextEnter.append('g').attr('class', 'nv-y1 nv-axis');
contextEnter.append('g').attr('class', 'nv-y2 nv-axis');
contextEnter.append('g').attr('class', 'nv-barsWrap');
contextEnter.append('g').attr('class', 'nv-linesWrap');
contextEnter.append('g').attr('class', 'nv-brushBackground');
contextEnter.append('g').attr('class', 'nv-x nv-brush');
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width( availableWidth / 2 );
g.select('.nv-legendWrap')
.datum(data.map(function(series) {
series.originalKey = series.originalKey === undefined ? series.key : series.originalKey;
series.key = series.originalKey + (series.bar ? ' (left axis)' : ' (right axis)');
return series;
}))
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight1 = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom - height2;
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')');
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
// Context Components
bars2
.width(availableWidth)
.height(availableHeight2)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && data[i].bar }));
lines2
.width(availableWidth)
.height(availableHeight2)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && !data[i].bar }));
var bars2Wrap = g.select('.nv-context .nv-barsWrap')
.datum(dataBars.length ? dataBars : [{values:[]}]);
var lines2Wrap = g.select('.nv-context .nv-linesWrap')
.datum(!dataLines[0].disabled ? dataLines : [{values:[]}]);
g.select('.nv-context')
.attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')')
bars2Wrap.transition().call(bars2);
lines2Wrap.transition().call(lines2);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Brush
brush
.x(x2)
.on('brush', onBrush);
if (brushExtent) brush.extent(brushExtent);
var brushBG = g.select('.nv-brushBackground').selectAll('g')
.data([brushExtent || brush.extent()])
var brushBGenter = brushBG.enter()
.append('g');
brushBGenter.append('rect')
.attr('class', 'left')
.attr('x', 0)
.attr('y', 0)
.attr('height', availableHeight2);
brushBGenter.append('rect')
.attr('class', 'right')
.attr('x', 0)
.attr('y', 0)
.attr('height', availableHeight2);
var gBrush = g.select('.nv-x.nv-brush')
.call(brush);
gBrush.selectAll('rect')
//.attr('y', -5)
.attr('height', availableHeight2);
gBrush.selectAll('.resize').append('path').attr('d', resizePath);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Secondary (Context) Axes
x2Axis
.ticks( availableWidth / 100 )
.tickSize(-availableHeight2, 0);
g.select('.nv-context .nv-x.nv-axis')
.attr('transform', 'translate(0,' + y3.range()[0] + ')');
g.select('.nv-context .nv-x.nv-axis').transition()
.call(x2Axis);
y3Axis
.scale(y3)
.ticks( availableHeight2 / 36 )
.tickSize( -availableWidth, 0);
g.select('.nv-context .nv-y1.nv-axis')
.style('opacity', dataBars.length ? 1 : 0)
.attr('transform', 'translate(0,' + x2.range()[0] + ')');
g.select('.nv-context .nv-y1.nv-axis').transition()
.call(y3Axis);
y4Axis
.scale(y4)
.ticks( availableHeight2 / 36 )
.tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none
g.select('.nv-context .nv-y2.nv-axis')
.style('opacity', dataLines.length ? 1 : 0)
.attr('transform', 'translate(' + x2.range()[1] + ',0)');
g.select('.nv-context .nv-y2.nv-axis').transition()
.call(y4Axis);
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
chart.update();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
//============================================================
//============================================================
// Functions
//------------------------------------------------------------
// Taken from crossfilter (http://square.github.com/crossfilter/)
function resizePath(d) {
var e = +(d == 'e'),
x = e ? 1 : -1,
y = availableHeight2 / 3;
return 'M' + (.5 * x) + ',' + y
+ 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6)
+ 'V' + (2 * y - 6)
+ 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y)
+ 'Z'
+ 'M' + (2.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8)
+ 'M' + (4.5 * x) + ',' + (y + 8)
+ 'V' + (2 * y - 8);
}
function updateBrushBG() {
if (!brush.empty()) brush.extent(brushExtent);
brushBG
.data([brush.empty() ? x2.domain() : brushExtent])
.each(function(d,i) {
var leftWidth = x2(d[0]) - x2.range()[0],
rightWidth = x2.range()[1] - x2(d[1]);
d3.select(this).select('.left')
.attr('width', leftWidth < 0 ? 0 : leftWidth);
d3.select(this).select('.right')
.attr('x', x2(d[1]))
.attr('width', rightWidth < 0 ? 0 : rightWidth);
});
}
function onBrush() {
brushExtent = brush.empty() ? null : brush.extent();
extent = brush.empty() ? x2.domain() : brush.extent();
dispatch.brush({extent: extent, brush: brush});
updateBrushBG();
//------------------------------------------------------------
// Prepare Main (Focus) Bars and Lines
bars
.width(availableWidth)
.height(availableHeight1)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && data[i].bar }));
lines
.width(availableWidth)
.height(availableHeight1)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled && !data[i].bar }));
var focusBarsWrap = g.select('.nv-focus .nv-barsWrap')
.datum(!dataBars.length ? [{values:[]}] :
dataBars
.map(function(d,i) {
return {
key: d.key,
values: d.values.filter(function(d,i) {
return bars.x()(d,i) >= extent[0] && bars.x()(d,i) <= extent[1];
})
}
})
);
var focusLinesWrap = g.select('.nv-focus .nv-linesWrap')
.datum(dataLines[0].disabled ? [{values:[]}] :
dataLines
.map(function(d,i) {
return {
key: d.key,
values: d.values.filter(function(d,i) {
return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1];
})
}
})
);
//------------------------------------------------------------
//------------------------------------------------------------
// Update Main (Focus) X Axis
if (dataBars.length) {
x = bars.xScale();
} else {
x = lines.xScale();
}
xAxis
.scale(x)
.ticks( availableWidth / 100 )
.tickSize(-availableHeight1, 0);
xAxis.domain([Math.ceil(extent[0]), Math.floor(extent[1])]);
g.select('.nv-x.nv-axis').transition().duration(transitionDuration)
.call(xAxis);
//------------------------------------------------------------
//------------------------------------------------------------
// Update Main (Focus) Bars and Lines
focusBarsWrap.transition().duration(transitionDuration).call(bars);
focusLinesWrap.transition().duration(transitionDuration).call(lines);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup and Update Main (Focus) Y Axes
g.select('.nv-focus .nv-x.nv-axis')
.attr('transform', 'translate(0,' + y1.range()[0] + ')');
y1Axis
.scale(y1)
.ticks( availableHeight1 / 36 )
.tickSize(-availableWidth, 0);
g.select('.nv-focus .nv-y1.nv-axis')
.style('opacity', dataBars.length ? 1 : 0);
y2Axis
.scale(y2)
.ticks( availableHeight1 / 36 )
.tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none
g.select('.nv-focus .nv-y2.nv-axis')
.style('opacity', dataLines.length ? 1 : 0)
.attr('transform', 'translate(' + x.range()[1] + ',0)');
g.select('.nv-focus .nv-y1.nv-axis').transition().duration(transitionDuration)
.call(y1Axis);
g.select('.nv-focus .nv-y2.nv-axis').transition().duration(transitionDuration)
.call(y2Axis);
}
//============================================================
onBrush();
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
lines.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
lines.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
bars.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
bars.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.legend = legend;
chart.lines = lines;
chart.lines2 = lines2;
chart.bars = bars;
chart.bars2 = bars2;
chart.xAxis = xAxis;
chart.x2Axis = x2Axis;
chart.y1Axis = y1Axis;
chart.y2Axis = y2Axis;
chart.y3Axis = y3Axis;
chart.y4Axis = y4Axis;
d3.rebind(chart, lines, 'defined', 'size', 'clipVoronoi', 'interpolate');
//TODO: consider rebinding x, y and some other stuff, and simply do soemthign lile bars.x(lines.x()), etc.
//d3.rebind(chart, lines, 'x', 'y', 'size', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
lines.x(_);
bars.x(_);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
lines.y(_);
bars.y(_);
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.brushExtent = function(_) {
if (!arguments.length) return brushExtent;
brushExtent = _;
return chart;
};
//============================================================
return chart;
}
nv.models.multiBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, x = d3.scale.ordinal()
, y = d3.scale.linear()
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
, clipEdge = true
, stacked = false
, stackOffset = 'zero' // options include 'silhouette', 'wiggle', 'expand', 'zero', or a custom function
, color = nv.utils.defaultColor()
, hideable = false
, barColor = null // adding the ability to set the color for each rather than the whole group
, disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled
, delay = 1200
, xDomain
, yDomain
, xRange
, yRange
, groupSpacing = 0.1
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0 //used to store previous scales
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
if(hideable && data.length) hideable = [{
values: data[0].values.map(function(d) {
return {
x: d.x,
y: 0,
series: d.series,
size: 0.01
};}
)}];
if (stacked)
data = d3.layout.stack()
.offset(stackOffset)
.values(function(d){ return d.values })
.y(getY)
(!data.length && hideable ? hideable : data);
//add series index to each data point for reference
data.forEach(function(series, i) {
series.values.forEach(function(point) {
point.series = i;
});
});
//------------------------------------------------------------
// HACK for negative value stacking
if (stacked)
data[0].values.map(function(d,i) {
var posBase = 0, negBase = 0;
data.map(function(d) {
var f = d.values[i]
f.size = Math.abs(f.y);
if (f.y<0) {
f.y1 = negBase;
negBase = negBase - f.size;
} else
{
f.y1 = f.size + posBase;
posBase = posBase + f.size;
}
});
});
//------------------------------------------------------------
// Setup Scales
// remap and flatten the data for use in calculating the scales' domains
var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
data.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1 }
})
});
x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
.rangeBands(xRange || [0, availableWidth], groupSpacing);
//y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y + (stacked ? d.y1 : 0) }).concat(forceY)))
y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return stacked ? (d.y > 0 ? d.y1 : d.y1 + d.y ) : d.y }).concat(forceY)))
.range(yRange || [availableHeight, 0]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
: y.domain([-1,1]);
x0 = x0 || x;
y0 = y0 || y;
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-multibar').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibar');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g')
gEnter.append('g').attr('class', 'nv-groups');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
defsEnter.append('clipPath')
.attr('id', 'nv-edge-clip-' + id)
.append('rect');
wrap.select('#nv-edge-clip-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d,i) { return i });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6);
groups.exit()
.transition()
.selectAll('rect.nv-bar')
.delay(function(d,i) {
return i * delay/ data[0].values.length;
})
.attr('y', function(d) { return stacked ? y0(d.y0) : y0(0) })
.attr('height', 0)
.remove();
groups
.attr('class', function(d,i) { return 'nv-group nv-series-' + i })
.classed('hover', function(d) { return d.hover })
.style('fill', function(d,i){ return color(d, i) })
.style('stroke', function(d,i){ return color(d, i) });
groups
.transition()
.style('stroke-opacity', 1)
.style('fill-opacity', .75);
var bars = groups.selectAll('rect.nv-bar')
.data(function(d) { return (hideable && !data.length) ? hideable.values : d.values });
bars.exit().remove();
var barsEnter = bars.enter().append('rect')
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'})
.attr('x', function(d,i,j) {
return stacked ? 0 : (j * x.rangeBand() / data.length )
})
.attr('y', function(d) { return y0(stacked ? d.y0 : 0) })
.attr('height', 0)
.attr('width', x.rangeBand() / (stacked ? 1 : data.length) )
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',0)'; })
;
bars
.style('fill', function(d,i,j){ return color(d, j, i); })
.style('stroke', function(d,i,j){ return color(d, j, i); })
.on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
value: getY(d,i),
point: d,
series: data[d.series],
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
value: getY(d,i),
point: d,
series: data[d.series],
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
})
.on('click', function(d,i) {
dispatch.elementClick({
value: getY(d,i),
point: d,
series: data[d.series],
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
dispatch.elementDblClick({
value: getY(d,i),
point: d,
series: data[d.series],
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
d3.event.stopPropagation();
});
bars
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'})
.transition()
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',0)'; })
if (barColor) {
if (!disabled) disabled = data.map(function() { return true });
bars
.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); })
.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); });
}
if (stacked)
bars.transition()
.delay(function(d,i) {
return i * delay / data[0].values.length;
})
.attr('y', function(d,i) {
return y((stacked ? d.y1 : 0));
})
.attr('height', function(d,i) {
return Math.max(Math.abs(y(d.y + (stacked ? d.y0 : 0)) - y((stacked ? d.y0 : 0))),1);
})
.attr('x', function(d,i) {
return stacked ? 0 : (d.series * x.rangeBand() / data.length )
})
.attr('width', x.rangeBand() / (stacked ? 1 : data.length) );
else
bars.transition()
.delay(function(d,i) {
return i * delay/ data[0].values.length;
})
.attr('x', function(d,i) {
return d.series * x.rangeBand() / data.length
})
.attr('width', x.rangeBand() / data.length)
.attr('y', function(d,i) {
return getY(d,i) < 0 ?
y(0) :
y(0) - y(getY(d,i)) < 1 ?
y(0) - 1 :
y(getY(d,i)) || 0;
})
.attr('height', function(d,i) {
return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) || 0;
});
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.xScale = function(_) {
if (!arguments.length) return x;
x = _;
return chart;
};
chart.yScale = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.xDomain = function(_) {
if (!arguments.length) return xDomain;
xDomain = _;
return chart;
};
chart.yDomain = function(_) {
if (!arguments.length) return yDomain;
yDomain = _;
return chart;
};
chart.xRange = function(_) {
if (!arguments.length) return xRange;
xRange = _;
return chart;
};
chart.yRange = function(_) {
if (!arguments.length) return yRange;
yRange = _;
return chart;
};
chart.forceY = function(_) {
if (!arguments.length) return forceY;
forceY = _;
return chart;
};
chart.stacked = function(_) {
if (!arguments.length) return stacked;
stacked = _;
return chart;
};
chart.stackOffset = function(_) {
if (!arguments.length) return stackOffset;
stackOffset = _;
return chart;
};
chart.clipEdge = function(_) {
if (!arguments.length) return clipEdge;
clipEdge = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.barColor = function(_) {
if (!arguments.length) return barColor;
barColor = nv.utils.getColor(_);
return chart;
};
chart.disabled = function(_) {
if (!arguments.length) return disabled;
disabled = _;
return chart;
};
chart.id = function(_) {
if (!arguments.length) return id;
id = _;
return chart;
};
chart.hideable = function(_) {
if (!arguments.length) return hideable;
hideable = _;
return chart;
};
chart.delay = function(_) {
if (!arguments.length) return delay;
delay = _;
return chart;
};
chart.groupSpacing = function(_) {
if (!arguments.length) return groupSpacing;
groupSpacing = _;
return chart;
};
//============================================================
return chart;
}
nv.models.multiBarChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var multibar = nv.models.multiBar()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, controls = nv.models.legend()
;
var margin = {top: 30, right: 20, bottom: 50, left: 60}
, width = null
, height = null
, color = nv.utils.defaultColor()
, showControls = true
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, reduceXTicks = true // if false a tick will show for every data point
, staggerLabels = false
, rotateLabels = 0
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' on ' + x + '</p>'
}
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, state = { stacked: false }
, defaultState = null
, noData = "No Data Available."
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
, controlWidth = function() { return showControls ? 180 : 0 }
, transitionDuration = 250
;
multibar
.stacked(false)
;
xAxis
.orient('bottom')
.tickPadding(7)
.highlightZero(true)
.showMaxMin(false)
.tickFormat(function(d) { return d })
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
.tickFormat(d3.format(',.1f'))
;
controls.updateState(false);
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(multibar.x()(e.point, e.pointIndex)),
y = yAxis.tickFormat()(multibar.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
//------------------------------------------------------------
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = multibar.xScale();
y = multibar.yScale();
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-multiBarWithLegend').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarWithLegend').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-barsWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width(availableWidth - controlWidth());
if (multibar.barColor())
data.forEach(function(series,i) {
series.color = d3.rgb('#ccc').darker(i * 1.5).toString();
})
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')');
}
//------------------------------------------------------------
//------------------------------------------------------------
// Controls
if (showControls) {
var controlsData = [
{ key: 'Grouped', disabled: multibar.stacked() },
{ key: 'Stacked', disabled: !multibar.stacked() }
];
controls.width(controlWidth()).color(['#444', '#444', '#444']);
g.select('.nv-controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//------------------------------------------------------------
// Main Chart Component(s)
multibar
.disabled(data.map(function(series) { return series.disabled }))
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }))
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d) { return !d.disabled }))
barsWrap.transition().call(multibar);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
.ticks( availableWidth / 100 )
.tickSize(-availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
g.select('.nv-x.nv-axis').transition()
.call(xAxis);
var xTicks = g.select('.nv-x.nv-axis > g').selectAll('g');
xTicks
.selectAll('line, text')
.style('opacity', 1)
if (staggerLabels) {
var getTranslate = function(x,y) {
return "translate(" + x + "," + y + ")";
};
var staggerUp = 5, staggerDown = 17; //pixels to stagger by
// Issue #140
xTicks
.selectAll("text")
.attr('transform', function(d,i,j) {
return getTranslate(0, (j % 2 == 0 ? staggerUp : staggerDown));
});
var totalInBetweenTicks = d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length;
g.selectAll(".nv-x.nv-axis .nv-axisMaxMin text")
.attr("transform", function(d,i) {
return getTranslate(0, (i === 0 || totalInBetweenTicks % 2 !== 0) ? staggerDown : staggerUp);
});
}
if (reduceXTicks)
xTicks
.filter(function(d,i) {
return i % Math.ceil(data[0].values.length / (availableWidth / 100)) !== 0;
})
.selectAll('text, line')
.style('opacity', 0);
if(rotateLabels)
xTicks
.selectAll('.tick text')
.attr('transform', 'rotate(' + rotateLabels + ' 0,0)')
.style('text-anchor', rotateLabels > 0 ? 'start' : 'end');
g.select('.nv-x.nv-axis').selectAll('g.nv-axisMaxMin text')
.style('opacity', 1);
}
if (showYAxis) {
yAxis
.scale(y)
.ticks( availableHeight / 36 )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis').transition()
.call(yAxis);
}
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
state = newState;
dispatch.stateChange(state);
chart.update();
});
controls.dispatch.on('legendClick', function(d,i) {
if (!d.disabled) return;
controlsData = controlsData.map(function(s) {
s.disabled = true;
return s;
});
d.disabled = false;
switch (d.key) {
case 'Grouped':
multibar.stacked(false);
break;
case 'Stacked':
multibar.stacked(true);
break;
}
state.stacked = multibar.stacked();
dispatch.stateChange(state);
chart.update();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode)
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
if (typeof e.stacked !== 'undefined') {
multibar.stacked(e.stacked);
state.stacked = e.stacked;
}
chart.update();
});
//============================================================
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
multibar.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
multibar.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.multibar = multibar;
chart.legend = legend;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'clipEdge',
'id', 'stacked', 'stackOffset', 'delay', 'barColor','groupSpacing');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
return chart;
};
chart.showControls = function(_) {
if (!arguments.length) return showControls;
showControls = _;
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.showXAxis = function(_) {
if (!arguments.length) return showXAxis;
showXAxis = _;
return chart;
};
chart.showYAxis = function(_) {
if (!arguments.length) return showYAxis;
showYAxis = _;
return chart;
};
chart.rightAlignYAxis = function(_) {
if(!arguments.length) return rightAlignYAxis;
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
return chart;
};
chart.reduceXTicks= function(_) {
if (!arguments.length) return reduceXTicks;
reduceXTicks = _;
return chart;
};
chart.rotateLabels = function(_) {
if (!arguments.length) return rotateLabels;
rotateLabels = _;
return chart;
}
chart.staggerLabels = function(_) {
if (!arguments.length) return staggerLabels;
staggerLabels = _;
return chart;
};
chart.tooltip = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
//============================================================
return chart;
}
nv.models.multiBarHorizontal = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, x = d3.scale.ordinal()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
, color = nv.utils.defaultColor()
, barColor = null // adding the ability to set the color for each rather than the whole group
, disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled
, stacked = false
, showValues = false
, showBarLabels = false
, valuePadding = 60
, valueFormat = d3.format(',.2f')
, delay = 1200
, xDomain
, yDomain
, xRange
, yRange
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0 //used to store previous scales
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
if (stacked)
data = d3.layout.stack()
.offset('zero')
.values(function(d){ return d.values })
.y(getY)
(data);
//add series index to each data point for reference
data.forEach(function(series, i) {
series.values.forEach(function(point) {
point.series = i;
});
});
//------------------------------------------------------------
// HACK for negative value stacking
if (stacked)
data[0].values.map(function(d,i) {
var posBase = 0, negBase = 0;
data.map(function(d) {
var f = d.values[i]
f.size = Math.abs(f.y);
if (f.y<0) {
f.y1 = negBase - f.size;
negBase = negBase - f.size;
} else
{
f.y1 = posBase;
posBase = posBase + f.size;
}
});
});
//------------------------------------------------------------
// Setup Scales
// remap and flatten the data for use in calculating the scales' domains
var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
data.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1 }
})
});
x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
.rangeBands(xRange || [0, availableHeight], .1);
//y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y + (stacked ? d.y0 : 0) }).concat(forceY)))
y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return stacked ? (d.y > 0 ? d.y1 + d.y : d.y1 ) : d.y }).concat(forceY)))
if (showValues && !stacked)
y.range(yRange || [(y.domain()[0] < 0 ? valuePadding : 0), availableWidth - (y.domain()[1] > 0 ? valuePadding : 0) ]);
else
y.range(yRange || [0, availableWidth]);
x0 = x0 || x;
y0 = y0 || d3.scale.linear().domain(y.domain()).range([y(0),y(0)]);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-multibarHorizontal').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibarHorizontal');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-groups');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d,i) { return i });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6);
groups.exit().transition()
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6)
.remove();
groups
.attr('class', function(d,i) { return 'nv-group nv-series-' + i })
.classed('hover', function(d) { return d.hover })
.style('fill', function(d,i){ return color(d, i) })
.style('stroke', function(d,i){ return color(d, i) });
groups.transition()
.style('stroke-opacity', 1)
.style('fill-opacity', .75);
var bars = groups.selectAll('g.nv-bar')
.data(function(d) { return d.values });
bars.exit().remove();
var barsEnter = bars.enter().append('g')
.attr('transform', function(d,i,j) {
return 'translate(' + y0(stacked ? d.y0 : 0) + ',' + (stacked ? 0 : (j * x.rangeBand() / data.length ) + x(getX(d,i))) + ')'
});
barsEnter.append('rect')
.attr('width', 0)
.attr('height', x.rangeBand() / (stacked ? 1 : data.length) )
bars
.on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
value: getY(d,i),
point: d,
series: data[d.series],
pos: [ y(getY(d,i) + (stacked ? d.y0 : 0)), x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length) ],
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
value: getY(d,i),
point: d,
series: data[d.series],
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
})
.on('click', function(d,i) {
dispatch.elementClick({
value: getY(d,i),
point: d,
series: data[d.series],
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
dispatch.elementDblClick({
value: getY(d,i),
point: d,
series: data[d.series],
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: d.series,
e: d3.event
});
d3.event.stopPropagation();
});
barsEnter.append('text');
if (showValues && !stacked) {
bars.select('text')
.attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'end' : 'start' })
.attr('y', x.rangeBand() / (data.length * 2))
.attr('dy', '.32em')
.text(function(d,i) { return valueFormat(getY(d,i)) })
bars.transition()
.select('text')
.attr('x', function(d,i) { return getY(d,i) < 0 ? -4 : y(getY(d,i)) - y(0) + 4 })
} else {
bars.selectAll('text').text('');
}
if (showBarLabels && !stacked) {
barsEnter.append('text').classed('nv-bar-label',true);
bars.select('text.nv-bar-label')
.attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'start' : 'end' })
.attr('y', x.rangeBand() / (data.length * 2))
.attr('dy', '.32em')
.text(function(d,i) { return getX(d,i) });
bars.transition()
.select('text.nv-bar-label')
.attr('x', function(d,i) { return getY(d,i) < 0 ? y(0) - y(getY(d,i)) + 4 : -4 });
}
else {
bars.selectAll('text.nv-bar-label').text('');
}
bars
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'})
if (barColor) {
if (!disabled) disabled = data.map(function() { return true });
bars
.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); })
.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); });
}
if (stacked)
bars.transition()
.attr('transform', function(d,i) {
return 'translate(' + y(d.y1) + ',' + x(getX(d,i)) + ')'
})
.select('rect')
.attr('width', function(d,i) {
return Math.abs(y(getY(d,i) + d.y0) - y(d.y0))
})
.attr('height', x.rangeBand() );
else
bars.transition()
.attr('transform', function(d,i) {
//TODO: stacked must be all positive or all negative, not both?
return 'translate(' +
(getY(d,i) < 0 ? y(getY(d,i)) : y(0))
+ ',' +
(d.series * x.rangeBand() / data.length
+
x(getX(d,i)) )
+ ')'
})
.select('rect')
.attr('height', x.rangeBand() / data.length )
.attr('width', function(d,i) {
return Math.max(Math.abs(y(getY(d,i)) - y(0)),1)
});
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.xScale = function(_) {
if (!arguments.length) return x;
x = _;
return chart;
};
chart.yScale = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.xDomain = function(_) {
if (!arguments.length) return xDomain;
xDomain = _;
return chart;
};
chart.yDomain = function(_) {
if (!arguments.length) return yDomain;
yDomain = _;
return chart;
};
chart.xRange = function(_) {
if (!arguments.length) return xRange;
xRange = _;
return chart;
};
chart.yRange = function(_) {
if (!arguments.length) return yRange;
yRange = _;
return chart;
};
chart.forceY = function(_) {
if (!arguments.length) return forceY;
forceY = _;
return chart;
};
chart.stacked = function(_) {
if (!arguments.length) return stacked;
stacked = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.barColor = function(_) {
if (!arguments.length) return barColor;
barColor = nv.utils.getColor(_);
return chart;
};
chart.disabled = function(_) {
if (!arguments.length) return disabled;
disabled = _;
return chart;
};
chart.id = function(_) {
if (!arguments.length) return id;
id = _;
return chart;
};
chart.delay = function(_) {
if (!arguments.length) return delay;
delay = _;
return chart;
};
chart.showValues = function(_) {
if (!arguments.length) return showValues;
showValues = _;
return chart;
};
chart.showBarLabels = function(_) {
if (!arguments.length) return showBarLabels;
showBarLabels = _;
return chart;
};
chart.valueFormat= function(_) {
if (!arguments.length) return valueFormat;
valueFormat = _;
return chart;
};
chart.valuePadding = function(_) {
if (!arguments.length) return valuePadding;
valuePadding = _;
return chart;
};
//============================================================
return chart;
}
nv.models.multiBarHorizontalChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var multibar = nv.models.multiBarHorizontal()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend().height(30)
, controls = nv.models.legend().height(30)
;
var margin = {top: 30, right: 20, bottom: 50, left: 60}
, width = null
, height = null
, color = nv.utils.defaultColor()
, showControls = true
, showLegend = true
, showXAxis = true
, showYAxis = true
, stacked = false
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + ' - ' + x + '</h3>' +
'<p>' + y + '</p>'
}
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, state = { stacked: stacked }
, defaultState = null
, noData = 'No Data Available.'
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
, controlWidth = function() { return showControls ? 180 : 0 }
, transitionDuration = 250
;
multibar
.stacked(stacked)
;
xAxis
.orient('left')
.tickPadding(5)
.highlightZero(false)
.showMaxMin(false)
.tickFormat(function(d) { return d })
;
yAxis
.orient('bottom')
.tickFormat(d3.format(',.1f'))
;
controls.updateState(false);
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(multibar.x()(e.point, e.pointIndex)),
y = yAxis.tickFormat()(multibar.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = multibar.xScale();
y = multibar.yScale();
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-multiBarHorizontalChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarHorizontalChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis')
.append('g').attr('class', 'nv-zeroLine')
.append('line');
gEnter.append('g').attr('class', 'nv-barsWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width(availableWidth - controlWidth());
if (multibar.barColor())
data.forEach(function(series,i) {
series.color = d3.rgb('#ccc').darker(i * 1.5).toString();
})
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')');
}
//------------------------------------------------------------
//------------------------------------------------------------
// Controls
if (showControls) {
var controlsData = [
{ key: 'Grouped', disabled: multibar.stacked() },
{ key: 'Stacked', disabled: !multibar.stacked() }
];
controls.width(controlWidth()).color(['#444', '#444', '#444']);
g.select('.nv-controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
// Main Chart Component(s)
multibar
.disabled(data.map(function(series) { return series.disabled }))
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }))
var barsWrap = g.select('.nv-barsWrap')
.datum(data.filter(function(d) { return !d.disabled }))
barsWrap.transition().call(multibar);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
.ticks( availableHeight / 24 )
.tickSize(-availableWidth, 0);
g.select('.nv-x.nv-axis').transition()
.call(xAxis);
var xTicks = g.select('.nv-x.nv-axis').selectAll('g');
xTicks
.selectAll('line, text');
}
if (showYAxis) {
yAxis
.scale(y)
.ticks( availableWidth / 100 )
.tickSize( -availableHeight, 0);
g.select('.nv-y.nv-axis')
.attr('transform', 'translate(0,' + availableHeight + ')');
g.select('.nv-y.nv-axis').transition()
.call(yAxis);
}
// Zero line
g.select(".nv-zeroLine line")
.attr("x1", y(0))
.attr("x2", y(0))
.attr("y1", 0)
.attr("y2", -availableHeight)
;
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
state = newState;
dispatch.stateChange(state);
chart.update();
});
controls.dispatch.on('legendClick', function(d,i) {
if (!d.disabled) return;
controlsData = controlsData.map(function(s) {
s.disabled = true;
return s;
});
d.disabled = false;
switch (d.key) {
case 'Grouped':
multibar.stacked(false);
break;
case 'Stacked':
multibar.stacked(true);
break;
}
state.stacked = multibar.stacked();
dispatch.stateChange(state);
chart.update();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
if (typeof e.stacked !== 'undefined') {
multibar.stacked(e.stacked);
state.stacked = e.stacked;
}
chart.update();
});
//============================================================
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
multibar.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
multibar.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.multibar = multibar;
chart.legend = legend;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY',
'clipEdge', 'id', 'delay', 'showValues','showBarLabels', 'valueFormat', 'stacked', 'barColor');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
return chart;
};
chart.showControls = function(_) {
if (!arguments.length) return showControls;
showControls = _;
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.showXAxis = function(_) {
if (!arguments.length) return showXAxis;
showXAxis = _;
return chart;
};
chart.showYAxis = function(_) {
if (!arguments.length) return showYAxis;
showYAxis = _;
return chart;
};
chart.tooltip = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
//============================================================
return chart;
}
nv.models.multiChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 30, right: 20, bottom: 50, left: 60},
color = d3.scale.category20().range(),
width = null,
height = null,
showLegend = true,
tooltips = true,
tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' at ' + x + '</p>'
},
x,
y,
yDomain1,
yDomain2
; //can be accessed via chart.lines.[x/y]Scale()
//============================================================
// Private Variables
//------------------------------------------------------------
var x = d3.scale.linear(),
yScale1 = d3.scale.linear(),
yScale2 = d3.scale.linear(),
lines1 = nv.models.line().yScale(yScale1),
lines2 = nv.models.line().yScale(yScale2),
bars1 = nv.models.multiBar().stacked(false).yScale(yScale1),
bars2 = nv.models.multiBar().stacked(false).yScale(yScale2),
stack1 = nv.models.stackedArea().yScale(yScale1),
stack2 = nv.models.stackedArea().yScale(yScale2),
xAxis = nv.models.axis().scale(x).orient('bottom').tickPadding(5),
yAxis1 = nv.models.axis().scale(yScale1).orient('left'),
yAxis2 = nv.models.axis().scale(yScale2).orient('right'),
legend = nv.models.legend().height(30),
dispatch = d3.dispatch('tooltipShow', 'tooltipHide');
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(lines1.x()(e.point, e.pointIndex)),
y = ((e.series.yAxis == 2) ? yAxis2 : yAxis1).tickFormat()(lines1.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, undefined, undefined, offsetElement.offsetParent);
};
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
chart.update = function() { container.transition().call(chart); };
chart.container = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
var dataLines1 = data.filter(function(d) {return !d.disabled && d.type == 'line' && d.yAxis == 1})
var dataLines2 = data.filter(function(d) {return !d.disabled && d.type == 'line' && d.yAxis == 2})
var dataBars1 = data.filter(function(d) {return !d.disabled && d.type == 'bar' && d.yAxis == 1})
var dataBars2 = data.filter(function(d) {return !d.disabled && d.type == 'bar' && d.yAxis == 2})
var dataStack1 = data.filter(function(d) {return !d.disabled && d.type == 'area' && d.yAxis == 1})
var dataStack2 = data.filter(function(d) {return !d.disabled && d.type == 'area' && d.yAxis == 2})
var series1 = data.filter(function(d) {return !d.disabled && d.yAxis == 1})
.map(function(d) {
return d.values.map(function(d,i) {
return { x: d.x, y: d.y }
})
})
var series2 = data.filter(function(d) {return !d.disabled && d.yAxis == 2})
.map(function(d) {
return d.values.map(function(d,i) {
return { x: d.x, y: d.y }
})
})
x .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } ))
.range([0, availableWidth]);
var wrap = container.selectAll('g.wrap.multiChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'wrap nvd3 multiChart').append('g');
gEnter.append('g').attr('class', 'x axis');
gEnter.append('g').attr('class', 'y1 axis');
gEnter.append('g').attr('class', 'y2 axis');
gEnter.append('g').attr('class', 'lines1Wrap');
gEnter.append('g').attr('class', 'lines2Wrap');
gEnter.append('g').attr('class', 'bars1Wrap');
gEnter.append('g').attr('class', 'bars2Wrap');
gEnter.append('g').attr('class', 'stack1Wrap');
gEnter.append('g').attr('class', 'stack2Wrap');
gEnter.append('g').attr('class', 'legendWrap');
var g = wrap.select('g');
if (showLegend) {
legend.width( availableWidth / 2 );
g.select('.legendWrap')
.datum(data.map(function(series) {
series.originalKey = series.originalKey === undefined ? series.key : series.originalKey;
series.key = series.originalKey + (series.yAxis == 1 ? '' : ' (right axis)');
return series;
}))
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
g.select('.legendWrap')
.attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')');
}
lines1
.width(availableWidth)
.height(availableHeight)
.interpolate("monotone")
.color(data.map(function(d,i) {
return d.color || color[i % color.length];
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'line'}));
lines2
.width(availableWidth)
.height(availableHeight)
.interpolate("monotone")
.color(data.map(function(d,i) {
return d.color || color[i % color.length];
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'line'}));
bars1
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color[i % color.length];
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'bar'}));
bars2
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color[i % color.length];
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'bar'}));
stack1
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color[i % color.length];
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'area'}));
stack2
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color[i % color.length];
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'area'}));
g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var lines1Wrap = g.select('.lines1Wrap')
.datum(dataLines1)
var bars1Wrap = g.select('.bars1Wrap')
.datum(dataBars1)
var stack1Wrap = g.select('.stack1Wrap')
.datum(dataStack1)
var lines2Wrap = g.select('.lines2Wrap')
.datum(dataLines2)
var bars2Wrap = g.select('.bars2Wrap')
.datum(dataBars2)
var stack2Wrap = g.select('.stack2Wrap')
.datum(dataStack2)
var extraValue1 = dataStack1.length ? dataStack1.map(function(a){return a.values}).reduce(function(a,b){
return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}})
}).concat([{x:0, y:0}]) : []
var extraValue2 = dataStack2.length ? dataStack2.map(function(a){return a.values}).reduce(function(a,b){
return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}})
}).concat([{x:0, y:0}]) : []
yScale1 .domain(yDomain1 || d3.extent(d3.merge(series1).concat(extraValue1), function(d) { return d.y } ))
.range([0, availableHeight])
yScale2 .domain(yDomain2 || d3.extent(d3.merge(series2).concat(extraValue2), function(d) { return d.y } ))
.range([0, availableHeight])
lines1.yDomain(yScale1.domain())
bars1.yDomain(yScale1.domain())
stack1.yDomain(yScale1.domain())
lines2.yDomain(yScale2.domain())
bars2.yDomain(yScale2.domain())
stack2.yDomain(yScale2.domain())
if(dataStack1.length){d3.transition(stack1Wrap).call(stack1);}
if(dataStack2.length){d3.transition(stack2Wrap).call(stack2);}
if(dataBars1.length){d3.transition(bars1Wrap).call(bars1);}
if(dataBars2.length){d3.transition(bars2Wrap).call(bars2);}
if(dataLines1.length){d3.transition(lines1Wrap).call(lines1);}
if(dataLines2.length){d3.transition(lines2Wrap).call(lines2);}
xAxis
.ticks( availableWidth / 100 )
.tickSize(-availableHeight, 0);
g.select('.x.axis')
.attr('transform', 'translate(0,' + availableHeight + ')');
d3.transition(g.select('.x.axis'))
.call(xAxis);
yAxis1
.ticks( availableHeight / 36 )
.tickSize( -availableWidth, 0);
d3.transition(g.select('.y1.axis'))
.call(yAxis1);
yAxis2
.ticks( availableHeight / 36 )
.tickSize( -availableWidth, 0);
d3.transition(g.select('.y2.axis'))
.call(yAxis2);
g.select('.y2.axis')
.style('opacity', series2.length ? 1 : 0)
.attr('transform', 'translate(' + x.range()[1] + ',0)');
legend.dispatch.on('stateChange', function(newState) {
chart.update();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
lines1.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
lines1.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
lines2.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
lines2.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
bars1.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
bars1.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
bars2.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
bars2.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
stack1.dispatch.on('tooltipShow', function(e) {
//disable tooltips when value ~= 0
//// TODO: consider removing points from voronoi that have 0 value instead of this hack
if (!Math.round(stack1.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range
setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0);
return false;
}
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top],
dispatch.tooltipShow(e);
});
stack1.dispatch.on('tooltipHide', function(e) {
dispatch.tooltipHide(e);
});
stack2.dispatch.on('tooltipShow', function(e) {
//disable tooltips when value ~= 0
//// TODO: consider removing points from voronoi that have 0 value instead of this hack
if (!Math.round(stack2.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range
setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0);
return false;
}
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top],
dispatch.tooltipShow(e);
});
stack2.dispatch.on('tooltipHide', function(e) {
dispatch.tooltipHide(e);
});
lines1.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
lines1.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
lines2.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
lines2.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
// Global getters and setters
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.lines1 = lines1;
chart.lines2 = lines2;
chart.bars1 = bars1;
chart.bars2 = bars2;
chart.stack1 = stack1;
chart.stack2 = stack2;
chart.xAxis = xAxis;
chart.yAxis1 = yAxis1;
chart.yAxis2 = yAxis2;
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
lines1.x(_);
bars1.x(_);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
lines1.y(_);
bars1.y(_);
return chart;
};
chart.yDomain1 = function(_) {
if (!arguments.length) return yDomain1;
yDomain1 = _;
return chart;
};
chart.yDomain2 = function(_) {
if (!arguments.length) return yDomain2;
yDomain2 = _;
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = _;
legend.color(_);
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
return chart;
}
nv.models.ohlcBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, x = d3.scale.linear()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, getOpen = function(d) { return d.open }
, getClose = function(d) { return d.close }
, getHigh = function(d) { return d.high }
, getLow = function(d) { return d.low }
, forceX = []
, forceY = []
, padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
, clipEdge = true
, color = nv.utils.defaultColor()
, xDomain
, yDomain
, xRange
, yRange
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
//TODO: store old scales for transitions
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
//------------------------------------------------------------
// Setup Scales
x .domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ));
if (padData)
x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
else
x.range(xRange || [0, availableWidth]);
y .domain(yDomain || [
d3.min(data[0].values.map(getLow).concat(forceY)),
d3.max(data[0].values.map(getHigh).concat(forceY))
])
.range(yRange || [availableHeight, 0]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
: y.domain([-1,1]);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-ohlcBar').data([data[0].values]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-ohlcBar');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-ticks');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
container
.on('click', function(d,i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
defsEnter.append('clipPath')
.attr('id', 'nv-chart-clip-path-' + id)
.append('rect');
wrap.select('#nv-chart-clip-path-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
var ticks = wrap.select('.nv-ticks').selectAll('.nv-tick')
.data(function(d) { return d });
ticks.exit().remove();
var ticksEnter = ticks.enter().append('path')
.attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i })
.attr('d', function(d,i) {
var w = (availableWidth / data[0].values.length) * .9;
return 'm0,0l0,'
+ (y(getOpen(d,i))
- y(getHigh(d,i)))
+ 'l'
+ (-w/2)
+ ',0l'
+ (w/2)
+ ',0l0,'
+ (y(getLow(d,i)) - y(getOpen(d,i)))
+ 'l0,'
+ (y(getClose(d,i))
- y(getLow(d,i)))
+ 'l'
+ (w/2)
+ ',0l'
+ (-w/2)
+ ',0z';
})
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; })
//.attr('fill', function(d,i) { return color[0]; })
//.attr('stroke', function(d,i) { return color[0]; })
//.attr('x', 0 )
//.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) })
//.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) })
.on('mouseover', function(d,i) {
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
point: d,
series: data[0],
pos: [x(getX(d,i)), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: 0,
e: d3.event
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
point: d,
series: data[0],
pointIndex: i,
seriesIndex: 0,
e: d3.event
});
})
.on('click', function(d,i) {
dispatch.elementClick({
//label: d[label],
value: getY(d,i),
data: d,
index: i,
pos: [x(getX(d,i)), y(getY(d,i))],
e: d3.event,
id: id
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
dispatch.elementDblClick({
//label: d[label],
value: getY(d,i),
data: d,
index: i,
pos: [x(getX(d,i)), y(getY(d,i))],
e: d3.event,
id: id
});
d3.event.stopPropagation();
});
ticks
.attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i })
d3.transition(ticks)
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; })
.attr('d', function(d,i) {
var w = (availableWidth / data[0].values.length) * .9;
return 'm0,0l0,'
+ (y(getOpen(d,i))
- y(getHigh(d,i)))
+ 'l'
+ (-w/2)
+ ',0l'
+ (w/2)
+ ',0l0,'
+ (y(getLow(d,i))
- y(getOpen(d,i)))
+ 'l0,'
+ (y(getClose(d,i))
- y(getLow(d,i)))
+ 'l'
+ (w/2)
+ ',0l'
+ (-w/2)
+ ',0z';
})
//.attr('width', (availableWidth / data[0].values.length) * .9 )
//d3.transition(ticks)
//.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) })
//.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) });
//.order(); // not sure if this makes any sense for this model
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
return chart;
};
chart.open = function(_) {
if (!arguments.length) return getOpen;
getOpen = _;
return chart;
};
chart.close = function(_) {
if (!arguments.length) return getClose;
getClose = _;
return chart;
};
chart.high = function(_) {
if (!arguments.length) return getHigh;
getHigh = _;
return chart;
};
chart.low = function(_) {
if (!arguments.length) return getLow;
getLow = _;
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.xScale = function(_) {
if (!arguments.length) return x;
x = _;
return chart;
};
chart.yScale = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.xDomain = function(_) {
if (!arguments.length) return xDomain;
xDomain = _;
return chart;
};
chart.yDomain = function(_) {
if (!arguments.length) return yDomain;
yDomain = _;
return chart;
};
chart.xRange = function(_) {
if (!arguments.length) return xRange;
xRange = _;
return chart;
};
chart.yRange = function(_) {
if (!arguments.length) return yRange;
yRange = _;
return chart;
};
chart.forceX = function(_) {
if (!arguments.length) return forceX;
forceX = _;
return chart;
};
chart.forceY = function(_) {
if (!arguments.length) return forceY;
forceY = _;
return chart;
};
chart.padData = function(_) {
if (!arguments.length) return padData;
padData = _;
return chart;
};
chart.clipEdge = function(_) {
if (!arguments.length) return clipEdge;
clipEdge = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.id = function(_) {
if (!arguments.length) return id;
id = _;
return chart;
};
//============================================================
return chart;
}
nv.models.pie = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 500
, height = 500
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, getDescription = function(d) { return d.description }
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, color = nv.utils.defaultColor()
, valueFormat = d3.format(',.2f')
, showLabels = true
, pieLabelsOutside = true
, donutLabelsOutside = false
, labelType = "key"
, labelThreshold = .02 //if slice percentage is under this, don't show label
, donut = false
, labelSunbeamLayout = false
, startAngle = false
, endAngle = false
, donutRatio = 0.5
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
radius = Math.min(availableWidth, availableHeight) / 2,
arcRadius = radius-(radius / 5),
container = d3.select(this);
//------------------------------------------------------------
// Setup containers and skeleton of chart
//var wrap = container.selectAll('.nv-wrap.nv-pie').data([data]);
var wrap = container.selectAll('.nv-wrap.nv-pie').data(data);
var wrapEnter = wrap.enter().append('g').attr('class','nvd3 nv-wrap nv-pie nv-chart-' + id);
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-pie');
gEnter.append('g').attr('class', 'nv-pieLabels');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
g.select('.nv-pie').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
g.select('.nv-pieLabels').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
//------------------------------------------------------------
container
.on('click', function(d,i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
var arc = d3.svg.arc()
.outerRadius(arcRadius);
if (startAngle) arc.startAngle(startAngle)
if (endAngle) arc.endAngle(endAngle);
if (donut) arc.innerRadius(radius * donutRatio);
// Setup the Pie chart and choose the data element
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.disabled ? 0 : getY(d) });
var slices = wrap.select('.nv-pie').selectAll('.nv-slice')
.data(pie);
var pieLabels = wrap.select('.nv-pieLabels').selectAll('.nv-label')
.data(pie);
slices.exit().remove();
pieLabels.exit().remove();
var ae = slices.enter().append('g')
.attr('class', 'nv-slice')
.on('mouseover', function(d,i){
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
label: getX(d.data),
value: getY(d.data),
point: d.data,
pointIndex: i,
pos: [d3.event.pageX, d3.event.pageY],
id: id
});
})
.on('mouseout', function(d,i){
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
label: getX(d.data),
value: getY(d.data),
point: d.data,
index: i,
id: id
});
})
.on('click', function(d,i) {
dispatch.elementClick({
label: getX(d.data),
value: getY(d.data),
point: d.data,
index: i,
pos: d3.event,
id: id
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
dispatch.elementDblClick({
label: getX(d.data),
value: getY(d.data),
point: d.data,
index: i,
pos: d3.event,
id: id
});
d3.event.stopPropagation();
});
slices
.attr('fill', function(d,i) { return color(d, i); })
.attr('stroke', function(d,i) { return color(d, i); });
var paths = ae.append('path')
.each(function(d) { this._current = d; });
//.attr('d', arc);
slices.select('path')
.transition()
.attr('d', arc)
.attrTween('d', arcTween);
if (showLabels) {
// This does the normal label
var labelsArc = d3.svg.arc().innerRadius(0);
if (pieLabelsOutside){ labelsArc = arc; }
if (donutLabelsOutside) { labelsArc = d3.svg.arc().outerRadius(arc.outerRadius()); }
pieLabels.enter().append("g").classed("nv-label",true)
.each(function(d,i) {
var group = d3.select(this);
group
.attr('transform', function(d) {
if (labelSunbeamLayout) {
d.outerRadius = arcRadius + 10; // Set Outer Coordinate
d.innerRadius = arcRadius + 15; // Set Inner Coordinate
var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
if ((d.startAngle+d.endAngle)/2 < Math.PI) {
rotateAngle -= 90;
} else {
rotateAngle += 90;
}
return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
} else {
d.outerRadius = radius + 10; // Set Outer Coordinate
d.innerRadius = radius + 15; // Set Inner Coordinate
return 'translate(' + labelsArc.centroid(d) + ')'
}
});
group.append('rect')
.style('stroke', '#fff')
.style('fill', '#fff')
.attr("rx", 3)
.attr("ry", 3);
group.append('text')
.style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned
.style('fill', '#000')
});
var labelLocationHash = {};
var avgHeight = 14;
var avgWidth = 140;
var createHashKey = function(coordinates) {
return Math.floor(coordinates[0]/avgWidth) * avgWidth + ',' + Math.floor(coordinates[1]/avgHeight) * avgHeight;
};
pieLabels.transition()
.attr('transform', function(d) {
if (labelSunbeamLayout) {
d.outerRadius = arcRadius + 10; // Set Outer Coordinate
d.innerRadius = arcRadius + 15; // Set Inner Coordinate
var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
if ((d.startAngle+d.endAngle)/2 < Math.PI) {
rotateAngle -= 90;
} else {
rotateAngle += 90;
}
return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
} else {
d.outerRadius = radius + 10; // Set Outer Coordinate
d.innerRadius = radius + 15; // Set Inner Coordinate
/*
Overlapping pie labels are not good. What this attempts to do is, prevent overlapping.
Each label location is hashed, and if a hash collision occurs, we assume an overlap.
Adjust the label's y-position to remove the overlap.
*/
var center = labelsArc.centroid(d);
var hashKey = createHashKey(center);
if (labelLocationHash[hashKey]) {
center[1] -= avgHeight;
}
labelLocationHash[createHashKey(center)] = true;
return 'translate(' + center + ')'
}
});
pieLabels.select(".nv-label text")
.style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned
.text(function(d, i) {
var percent = (d.endAngle - d.startAngle) / (2 * Math.PI);
var labelTypes = {
"key" : getX(d.data),
"value": getY(d.data),
"percent": d3.format('%')(percent)
};
return (d.value && percent > labelThreshold) ? labelTypes[labelType] : '';
});
}
// Computes the angle of an arc, converting from radians to degrees.
function angle(d) {
var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
return a > 90 ? a - 180 : a;
}
function arcTween(a) {
a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle;
a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle;
if (!donut) a.innerRadius = 0;
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
function tweenPie(b) {
b.innerRadius = 0;
var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
return function(t) {
return arc(i(t));
};
}
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.values = function(_) {
nv.log("pie.values() is no longer supported.");
return chart;
};
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = d3.functor(_);
return chart;
};
chart.description = function(_) {
if (!arguments.length) return getDescription;
getDescription = _;
return chart;
};
chart.showLabels = function(_) {
if (!arguments.length) return showLabels;
showLabels = _;
return chart;
};
chart.labelSunbeamLayout = function(_) {
if (!arguments.length) return labelSunbeamLayout;
labelSunbeamLayout = _;
return chart;
};
chart.donutLabelsOutside = function(_) {
if (!arguments.length) return donutLabelsOutside;
donutLabelsOutside = _;
return chart;
};
chart.pieLabelsOutside = function(_) {
if (!arguments.length) return pieLabelsOutside;
pieLabelsOutside = _;
return chart;
};
chart.labelType = function(_) {
if (!arguments.length) return labelType;
labelType = _;
labelType = labelType || "key";
return chart;
};
chart.donut = function(_) {
if (!arguments.length) return donut;
donut = _;
return chart;
};
chart.donutRatio = function(_) {
if (!arguments.length) return donutRatio;
donutRatio = _;
return chart;
};
chart.startAngle = function(_) {
if (!arguments.length) return startAngle;
startAngle = _;
return chart;
};
chart.endAngle = function(_) {
if (!arguments.length) return endAngle;
endAngle = _;
return chart;
};
chart.id = function(_) {
if (!arguments.length) return id;
id = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.valueFormat = function(_) {
if (!arguments.length) return valueFormat;
valueFormat = _;
return chart;
};
chart.labelThreshold = function(_) {
if (!arguments.length) return labelThreshold;
labelThreshold = _;
return chart;
};
//============================================================
return chart;
}
nv.models.pieChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var pie = nv.models.pie()
, legend = nv.models.legend()
;
var margin = {top: 30, right: 20, bottom: 20, left: 20}
, width = null
, height = null
, showLegend = true
, color = nv.utils.defaultColor()
, tooltips = true
, tooltip = function(key, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + '</p>'
}
, state = {}
, defaultState = null
, noData = "No Data Available."
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
var tooltipLabel = pie.description()(e.point) || pie.x()(e.point)
var left = e.pos[0] + ( (offsetElement && offsetElement.offsetLeft) || 0 ),
top = e.pos[1] + ( (offsetElement && offsetElement.offsetTop) || 0),
y = pie.valueFormat()(pie.y()(e.point)),
content = tooltip(tooltipLabel, y, e, chart);
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().call(chart); };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data || !data.length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-pieChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-pieChart').append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-pieWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
legend
.width( availableWidth )
.key(pie.x());
wrap.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')');
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
// Main Chart Component(s)
pie
.width(availableWidth)
.height(availableHeight);
var pieWrap = g.select('.nv-pieWrap')
.datum([data]);
d3.transition(pieWrap).call(pie);
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
legend.dispatch.on('stateChange', function(newState) {
state = newState;
dispatch.stateChange(state);
chart.update();
});
pie.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
//============================================================
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
pie.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.legend = legend;
chart.dispatch = dispatch;
chart.pie = pie;
d3.rebind(chart, pie, 'valueFormat', 'values', 'x', 'y', 'description', 'id', 'showLabels', 'donutLabelsOutside', 'pieLabelsOutside', 'labelType', 'donut', 'donutRatio', 'labelThreshold');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
pie.color(color);
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
//============================================================
return chart;
}
nv.models.scatter = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, color = nv.utils.defaultColor() // chooses color
, id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't select one
, x = d3.scale.linear()
, y = d3.scale.linear()
, z = d3.scale.linear() //linear because d3.svg.shape.size is treated as area
, getX = function(d) { return d.x } // accessor to get the x value
, getY = function(d) { return d.y } // accessor to get the y value
, getSize = function(d) { return d.size || 1} // accessor to get the point size
, getShape = function(d) { return d.shape || 'circle' } // accessor to get point shape
, onlyCircles = true // Set to false to use shapes
, forceX = [] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
, forceY = [] // List of numbers to Force into the Y scale
, forceSize = [] // List of numbers to Force into the Size scale
, interactive = true // If true, plots a voronoi overlay for advanced point intersection
, pointKey = null
, pointActive = function(d) { return !d.notActive } // any points that return false will be filtered out
, padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
, padDataOuter = .1 //outerPadding to imitate ordinal scale outer padding
, clipEdge = false // if true, masks points within x and y scale
, clipVoronoi = true // if true, masks each point with a circle... can turn off to slightly increase performance
, clipRadius = function() { return 25 } // function to get the radius for voronoi point clips
, xDomain = null // Override x domain (skips the calculation from data)
, yDomain = null // Override y domain
, xRange = null // Override x range
, yRange = null // Override y range
, sizeDomain = null // Override point size domain
, sizeRange = null
, singlePoint = false
, dispatch = d3.dispatch('elementClick', 'elementMouseover', 'elementMouseout')
, useVoronoi = true
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0, z0 // used to store previous scales
, timeoutID
, needsUpdate = false // Flag for when the points are visually updating, but the interactive layer is behind, to disable tooltips
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
//add series index to each data point for reference
data.forEach(function(series, i) {
series.values.forEach(function(point) {
point.series = i;
});
});
//------------------------------------------------------------
// Setup Scales
// remap and flatten the data for use in calculating the scales' domains
var seriesData = (xDomain && yDomain && sizeDomain) ? [] : // if we know xDomain and yDomain and sizeDomain, no need to calculate.... if Size is constant remember to set sizeDomain to speed up performance
d3.merge(
data.map(function(d) {
return d.values.map(function(d,i) {
return { x: getX(d,i), y: getY(d,i), size: getSize(d,i) }
})
})
);
x .domain(xDomain || d3.extent(seriesData.map(function(d) { return d.x; }).concat(forceX)))
if (padData && data[0])
x.range(xRange || [(availableWidth * padDataOuter + availableWidth) / (2 *data[0].values.length), availableWidth - availableWidth * (1 + padDataOuter) / (2 * data[0].values.length) ]);
//x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
else
x.range(xRange || [0, availableWidth]);
y .domain(yDomain || d3.extent(seriesData.map(function(d) { return d.y }).concat(forceY)))
.range(yRange || [availableHeight, 0]);
z .domain(sizeDomain || d3.extent(seriesData.map(function(d) { return d.size }).concat(forceSize)))
.range(sizeRange || [16, 256]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true;
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] - y.domain()[0] * 0.01, y.domain()[1] + y.domain()[1] * 0.01])
: y.domain([-1,1]);
if ( isNaN(x.domain()[0])) {
x.domain([-1,1]);
}
if ( isNaN(y.domain()[0])) {
y.domain([-1,1]);
}
x0 = x0 || x;
y0 = y0 || y;
z0 = z0 || z;
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-scatter').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatter nv-chart-' + id + (singlePoint ? ' nv-single-point' : ''));
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-groups');
gEnter.append('g').attr('class', 'nv-point-paths');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
defsEnter.append('clipPath')
.attr('id', 'nv-edge-clip-' + id)
.append('rect');
wrap.select('#nv-edge-clip-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', (availableHeight > 0) ? availableHeight : 0);
g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
function updateInteractiveLayer() {
if (!interactive) return false;
var eventElements;
var vertices = d3.merge(data.map(function(group, groupIndex) {
return group.values
.map(function(point, pointIndex) {
// *Adding noise to make duplicates very unlikely
// *Injecting series and point index for reference
/* *Adding a 'jitter' to the points, because there's an issue in d3.geom.voronoi.
*/
var pX = getX(point,pointIndex);
var pY = getY(point,pointIndex);
return [x(pX)+ Math.random() * 1e-7,
y(pY)+ Math.random() * 1e-7,
groupIndex,
pointIndex, point]; //temp hack to add noise untill I think of a better way so there are no duplicates
})
.filter(function(pointArray, pointIndex) {
return pointActive(pointArray[4], pointIndex); // Issue #237.. move filter to after map, so pointIndex is correct!
})
})
);
//inject series and point index for reference into voronoi
if (useVoronoi === true) {
if (clipVoronoi) {
var pointClipsEnter = wrap.select('defs').selectAll('.nv-point-clips')
.data([id])
.enter();
pointClipsEnter.append('clipPath')
.attr('class', 'nv-point-clips')
.attr('id', 'nv-points-clip-' + id);
var pointClips = wrap.select('#nv-points-clip-' + id).selectAll('circle')
.data(vertices);
pointClips.enter().append('circle')
.attr('r', clipRadius);
pointClips.exit().remove();
pointClips
.attr('cx', function(d) { return d[0] })
.attr('cy', function(d) { return d[1] });
wrap.select('.nv-point-paths')
.attr('clip-path', 'url(#nv-points-clip-' + id + ')');
}
if(vertices.length) {
// Issue #283 - Adding 2 dummy points to the voronoi b/c voronoi requires min 3 points to work
vertices.push([x.range()[0] - 20, y.range()[0] - 20, null, null]);
vertices.push([x.range()[1] + 20, y.range()[1] + 20, null, null]);
vertices.push([x.range()[0] - 20, y.range()[0] + 20, null, null]);
vertices.push([x.range()[1] + 20, y.range()[1] - 20, null, null]);
}
var bounds = d3.geom.polygon([
[-10,-10],
[-10,height + 10],
[width + 10,height + 10],
[width + 10,-10]
]);
var voronoi = d3.geom.voronoi(vertices).map(function(d, i) {
return {
'data': bounds.clip(d),
'series': vertices[i][2],
'point': vertices[i][3]
}
});
var pointPaths = wrap.select('.nv-point-paths').selectAll('path')
.data(voronoi);
pointPaths.enter().append('path')
.attr('class', function(d,i) { return 'nv-path-'+i; });
pointPaths.exit().remove();
pointPaths
.attr('d', function(d) {
if (d.data.length === 0)
return 'M 0 0'
else
return 'M' + d.data.join('L') + 'Z';
});
var mouseEventCallback = function(d,mDispatch) {
if (needsUpdate) return 0;
var series = data[d.series];
if (typeof series === 'undefined') return;
var point = series.values[d.point];
mDispatch({
point: point,
series: series,
pos: [x(getX(point, d.point)) + margin.left, y(getY(point, d.point)) + margin.top],
seriesIndex: d.series,
pointIndex: d.point
});
};
pointPaths
.on('click', function(d) {
mouseEventCallback(d, dispatch.elementClick);
})
.on('mouseover', function(d) {
mouseEventCallback(d, dispatch.elementMouseover);
})
.on('mouseout', function(d, i) {
mouseEventCallback(d, dispatch.elementMouseout);
});
} else {
/*
// bring data in form needed for click handlers
var dataWithPoints = vertices.map(function(d, i) {
return {
'data': d,
'series': vertices[i][2],
'point': vertices[i][3]
}
});
*/
// add event handlers to points instead voronoi paths
wrap.select('.nv-groups').selectAll('.nv-group')
.selectAll('.nv-point')
//.data(dataWithPoints)
//.style('pointer-events', 'auto') // recativate events, disabled by css
.on('click', function(d,i) {
//nv.log('test', d, i);
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
var series = data[d.series],
point = series.values[i];
dispatch.elementClick({
point: point,
series: series,
pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
seriesIndex: d.series,
pointIndex: i
});
})
.on('mouseover', function(d,i) {
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
var series = data[d.series],
point = series.values[i];
dispatch.elementMouseover({
point: point,
series: series,
pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
seriesIndex: d.series,
pointIndex: i
});
})
.on('mouseout', function(d,i) {
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
var series = data[d.series],
point = series.values[i];
dispatch.elementMouseout({
point: point,
series: series,
seriesIndex: d.series,
pointIndex: i
});
});
}
needsUpdate = false;
}
needsUpdate = true;
var groups = wrap.select('.nv-groups').selectAll('.nv-group')
.data(function(d) { return d }, function(d) { return d.key });
groups.enter().append('g')
.style('stroke-opacity', 1e-6)
.style('fill-opacity', 1e-6);
groups.exit()
.remove();
groups
.attr('class', function(d,i) { return 'nv-group nv-series-' + i })
.classed('hover', function(d) { return d.hover });
groups
.transition()
.style('fill', function(d,i) { return color(d, i) })
.style('stroke', function(d,i) { return color(d, i) })
.style('stroke-opacity', 1)
.style('fill-opacity', .5);
if (onlyCircles) {
var points = groups.selectAll('circle.nv-point')
.data(function(d) { return d.values }, pointKey);
points.enter().append('circle')
.style('fill', function (d,i) { return d.color })
.style('stroke', function (d,i) { return d.color })
.attr('cx', function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) })
.attr('cy', function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) })
.attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) });
points.exit().remove();
groups.exit().selectAll('path.nv-point').transition()
.attr('cx', function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
.attr('cy', function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
.remove();
points.each(function(d,i) {
d3.select(this)
.classed('nv-point', true)
.classed('nv-point-' + i, true)
.classed('hover',false)
;
});
points.transition()
.attr('cx', function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
.attr('cy', function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
.attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) });
} else {
var points = groups.selectAll('path.nv-point')
.data(function(d) { return d.values });
points.enter().append('path')
.style('fill', function (d,i) { return d.color })
.style('stroke', function (d,i) { return d.color })
.attr('transform', function(d,i) {
return 'translate(' + x0(getX(d,i)) + ',' + y0(getY(d,i)) + ')'
})
.attr('d',
d3.svg.symbol()
.type(getShape)
.size(function(d,i) { return z(getSize(d,i)) })
);
points.exit().remove();
groups.exit().selectAll('path.nv-point')
.transition()
.attr('transform', function(d,i) {
return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')'
})
.remove();
points.each(function(d,i) {
d3.select(this)
.classed('nv-point', true)
.classed('nv-point-' + i, true)
.classed('hover',false)
;
});
points.transition()
.attr('transform', function(d,i) {
//nv.log(d,i,getX(d,i), x(getX(d,i)));
return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')'
})
.attr('d',
d3.svg.symbol()
.type(getShape)
.size(function(d,i) { return z(getSize(d,i)) })
);
}
// Delay updating the invisible interactive layer for smoother animation
clearTimeout(timeoutID); // stop repeat calls to updateInteractiveLayer
timeoutID = setTimeout(updateInteractiveLayer, 300);
//updateInteractiveLayer();
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
z0 = z.copy();
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
chart.clearHighlights = function() {
//Remove the 'hover' class from all highlighted points.
d3.selectAll(".nv-chart-" + id + " .nv-point.hover").classed("hover",false);
};
chart.highlightPoint = function(seriesIndex,pointIndex,isHoverOver) {
d3.select(".nv-chart-" + id + " .nv-series-" + seriesIndex + " .nv-point-" + pointIndex)
.classed("hover",isHoverOver);
};
dispatch.on('elementMouseover.point', function(d) {
if (interactive) chart.highlightPoint(d.seriesIndex,d.pointIndex,true);
});
dispatch.on('elementMouseout.point', function(d) {
if (interactive) chart.highlightPoint(d.seriesIndex,d.pointIndex,false);
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = d3.functor(_);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = d3.functor(_);
return chart;
};
chart.size = function(_) {
if (!arguments.length) return getSize;
getSize = d3.functor(_);
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.xScale = function(_) {
if (!arguments.length) return x;
x = _;
return chart;
};
chart.yScale = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.zScale = function(_) {
if (!arguments.length) return z;
z = _;
return chart;
};
chart.xDomain = function(_) {
if (!arguments.length) return xDomain;
xDomain = _;
return chart;
};
chart.yDomain = function(_) {
if (!arguments.length) return yDomain;
yDomain = _;
return chart;
};
chart.sizeDomain = function(_) {
if (!arguments.length) return sizeDomain;
sizeDomain = _;
return chart;
};
chart.xRange = function(_) {
if (!arguments.length) return xRange;
xRange = _;
return chart;
};
chart.yRange = function(_) {
if (!arguments.length) return yRange;
yRange = _;
return chart;
};
chart.sizeRange = function(_) {
if (!arguments.length) return sizeRange;
sizeRange = _;
return chart;
};
chart.forceX = function(_) {
if (!arguments.length) return forceX;
forceX = _;
return chart;
};
chart.forceY = function(_) {
if (!arguments.length) return forceY;
forceY = _;
return chart;
};
chart.forceSize = function(_) {
if (!arguments.length) return forceSize;
forceSize = _;
return chart;
};
chart.interactive = function(_) {
if (!arguments.length) return interactive;
interactive = _;
return chart;
};
chart.pointKey = function(_) {
if (!arguments.length) return pointKey;
pointKey = _;
return chart;
};
chart.pointActive = function(_) {
if (!arguments.length) return pointActive;
pointActive = _;
return chart;
};
chart.padData = function(_) {
if (!arguments.length) return padData;
padData = _;
return chart;
};
chart.padDataOuter = function(_) {
if (!arguments.length) return padDataOuter;
padDataOuter = _;
return chart;
};
chart.clipEdge = function(_) {
if (!arguments.length) return clipEdge;
clipEdge = _;
return chart;
};
chart.clipVoronoi= function(_) {
if (!arguments.length) return clipVoronoi;
clipVoronoi = _;
return chart;
};
chart.useVoronoi= function(_) {
if (!arguments.length) return useVoronoi;
useVoronoi = _;
if (useVoronoi === false) {
clipVoronoi = false;
}
return chart;
};
chart.clipRadius = function(_) {
if (!arguments.length) return clipRadius;
clipRadius = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.shape = function(_) {
if (!arguments.length) return getShape;
getShape = _;
return chart;
};
chart.onlyCircles = function(_) {
if (!arguments.length) return onlyCircles;
onlyCircles = _;
return chart;
};
chart.id = function(_) {
if (!arguments.length) return id;
id = _;
return chart;
};
chart.singlePoint = function(_) {
if (!arguments.length) return singlePoint;
singlePoint = _;
return chart;
};
//============================================================
return chart;
}
nv.models.scatterChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var scatter = nv.models.scatter()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, controls = nv.models.legend()
, distX = nv.models.distribution()
, distY = nv.models.distribution()
;
var margin = {top: 30, right: 20, bottom: 50, left: 75}
, width = null
, height = null
, color = nv.utils.defaultColor()
, x = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.xScale()
, y = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.yScale()
, xPadding = 0
, yPadding = 0
, showDistX = false
, showDistY = false
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, showControls = !!d3.fisheye
, fisheye = 0
, pauseFisheye = false
, tooltips = true
, tooltipX = function(key, x, y) { return '<strong>' + x + '</strong>' }
, tooltipY = function(key, x, y) { return '<strong>' + y + '</strong>' }
, tooltip = null
, state = {}
, defaultState = null
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
, noData = "No Data Available."
, transitionDuration = 250
;
scatter
.xScale(x)
.yScale(y)
;
xAxis
.orient('bottom')
.tickPadding(10)
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
.tickPadding(10)
;
distX
.axis('x')
;
distY
.axis('y')
;
controls.updateState(false);
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0;
var showTooltip = function(e, offsetElement) {
//TODO: make tooltip style an option between single or dual on axes (maybe on all charts with axes?)
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
leftX = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
topX = y.range()[0] + margin.top + ( offsetElement.offsetTop || 0),
leftY = x.range()[0] + margin.left + ( offsetElement.offsetLeft || 0 ),
topY = e.pos[1] + ( offsetElement.offsetTop || 0),
xVal = xAxis.tickFormat()(scatter.x()(e.point, e.pointIndex)),
yVal = yAxis.tickFormat()(scatter.y()(e.point, e.pointIndex));
if( tooltipX != null )
nv.tooltip.show([leftX, topX], tooltipX(e.series.key, xVal, yVal, e, chart), 'n', 1, offsetElement, 'x-nvtooltip');
if( tooltipY != null )
nv.tooltip.show([leftY, topY], tooltipY(e.series.key, xVal, yVal, e, chart), 'e', 1, offsetElement, 'y-nvtooltip');
if( tooltip != null )
nv.tooltip.show([left, top], tooltip(e.series.key, xVal, yVal, e, chart), e.value < 0 ? 'n' : 's', null, offsetElement);
};
var controlsData = [
{ key: 'Magnify', disabled: true }
];
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart); };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
//------------------------------------------------------------
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x0 = x0 || x;
y0 = y0 || y;
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id());
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
// background for pointer events
gEnter.append('rect').attr('class', 'nvd3 nv-background');
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-scatterWrap');
gEnter.append('g').attr('class', 'nv-distWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
var legendWidth = (showControls) ? availableWidth / 2 : availableWidth;
legend.width(legendWidth);
wrap.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(' + (availableWidth - legendWidth) + ',' + (-margin.top) +')');
}
//------------------------------------------------------------
//------------------------------------------------------------
// Controls
if (showControls) {
controls.width(180).color(['#444']);
g.select('.nv-controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//------------------------------------------------------------
// Main Chart Component(s)
scatter
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
if (xPadding !== 0)
scatter.xDomain(null);
if (yPadding !== 0)
scatter.yDomain(null);
wrap.select('.nv-scatterWrap')
.datum(data.filter(function(d) { return !d.disabled }))
.call(scatter);
//Adjust for x and y padding
if (xPadding !== 0) {
var xRange = x.domain()[1] - x.domain()[0];
scatter.xDomain([x.domain()[0] - (xPadding * xRange), x.domain()[1] + (xPadding * xRange)]);
}
if (yPadding !== 0) {
var yRange = y.domain()[1] - y.domain()[0];
scatter.yDomain([y.domain()[0] - (yPadding * yRange), y.domain()[1] + (yPadding * yRange)]);
}
//Only need to update the scatter again if x/yPadding changed the domain.
if (yPadding !== 0 || xPadding !== 0) {
wrap.select('.nv-scatterWrap')
.datum(data.filter(function(d) { return !d.disabled }))
.call(scatter);
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
.ticks( xAxis.ticks() && xAxis.ticks().length ? xAxis.ticks() : availableWidth / 100 )
.tickSize( -availableHeight , 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')')
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
.ticks( yAxis.ticks() && yAxis.ticks().length ? yAxis.ticks() : availableHeight / 36 )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis')
.call(yAxis);
}
if (showDistX) {
distX
.getData(scatter.x())
.scale(x)
.width(availableWidth)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
gEnter.select('.nv-distWrap').append('g')
.attr('class', 'nv-distributionX');
g.select('.nv-distributionX')
.attr('transform', 'translate(0,' + y.range()[0] + ')')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distX);
}
if (showDistY) {
distY
.getData(scatter.y())
.scale(y)
.width(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
gEnter.select('.nv-distWrap').append('g')
.attr('class', 'nv-distributionY');
g.select('.nv-distributionY')
.attr('transform',
'translate(' + (rightAlignYAxis ? availableWidth : -distY.size() ) + ',0)')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distY);
}
//------------------------------------------------------------
if (d3.fisheye) {
g.select('.nv-background')
.attr('width', availableWidth)
.attr('height', availableHeight);
g.select('.nv-background').on('mousemove', updateFisheye);
g.select('.nv-background').on('click', function() { pauseFisheye = !pauseFisheye;});
scatter.dispatch.on('elementClick.freezeFisheye', function() {
pauseFisheye = !pauseFisheye;
});
}
function updateFisheye() {
if (pauseFisheye) {
g.select('.nv-point-paths').style('pointer-events', 'all');
return false;
}
g.select('.nv-point-paths').style('pointer-events', 'none' );
var mouse = d3.mouse(this);
x.distortion(fisheye).focus(mouse[0]);
y.distortion(fisheye).focus(mouse[1]);
g.select('.nv-scatterWrap')
.call(scatter);
if (showXAxis)
g.select('.nv-x.nv-axis').call(xAxis);
if (showYAxis)
g.select('.nv-y.nv-axis').call(yAxis);
g.select('.nv-distributionX')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distX);
g.select('.nv-distributionY')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distY);
}
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
controls.dispatch.on('legendClick', function(d,i) {
d.disabled = !d.disabled;
fisheye = d.disabled ? 0 : 2.5;
g.select('.nv-background') .style('pointer-events', d.disabled ? 'none' : 'all');
g.select('.nv-point-paths').style('pointer-events', d.disabled ? 'all' : 'none' );
if (d.disabled) {
x.distortion(fisheye).focus(0);
y.distortion(fisheye).focus(0);
g.select('.nv-scatterWrap').call(scatter);
g.select('.nv-x.nv-axis').call(xAxis);
g.select('.nv-y.nv-axis').call(yAxis);
} else {
pauseFisheye = false;
}
chart.update();
});
legend.dispatch.on('stateChange', function(newState) {
state.disabled = newState.disabled;
dispatch.stateChange(state);
chart.update();
});
scatter.dispatch.on('elementMouseover.tooltip', function(e) {
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex)
.attr('y1', function(d,i) { return e.pos[1] - availableHeight;});
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex)
.attr('x2', e.pos[0] + distX.size());
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
//============================================================
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
scatter.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex)
.attr('y1', 0);
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex)
.attr('x2', distY.size());
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.scatter = scatter;
chart.legend = legend;
chart.controls = controls;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.distX = distX;
chart.distY = distY;
d3.rebind(chart, scatter, 'id', 'interactive', 'pointActive', 'x', 'y', 'shape', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'xRange', 'yRange', 'sizeDomain', 'sizeRange', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'useVoronoi');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
distX.color(color);
distY.color(color);
return chart;
};
chart.showDistX = function(_) {
if (!arguments.length) return showDistX;
showDistX = _;
return chart;
};
chart.showDistY = function(_) {
if (!arguments.length) return showDistY;
showDistY = _;
return chart;
};
chart.showControls = function(_) {
if (!arguments.length) return showControls;
showControls = _;
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.showXAxis = function(_) {
if (!arguments.length) return showXAxis;
showXAxis = _;
return chart;
};
chart.showYAxis = function(_) {
if (!arguments.length) return showYAxis;
showYAxis = _;
return chart;
};
chart.rightAlignYAxis = function(_) {
if(!arguments.length) return rightAlignYAxis;
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
return chart;
};
chart.fisheye = function(_) {
if (!arguments.length) return fisheye;
fisheye = _;
return chart;
};
chart.xPadding = function(_) {
if (!arguments.length) return xPadding;
xPadding = _;
return chart;
};
chart.yPadding = function(_) {
if (!arguments.length) return yPadding;
yPadding = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.tooltipXContent = function(_) {
if (!arguments.length) return tooltipX;
tooltipX = _;
return chart;
};
chart.tooltipYContent = function(_) {
if (!arguments.length) return tooltipY;
tooltipY = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
//============================================================
return chart;
}
nv.models.scatterPlusLineChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var scatter = nv.models.scatter()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, controls = nv.models.legend()
, distX = nv.models.distribution()
, distY = nv.models.distribution()
;
var margin = {top: 30, right: 20, bottom: 50, left: 75}
, width = null
, height = null
, color = nv.utils.defaultColor()
, x = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.xScale()
, y = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.yScale()
, showDistX = false
, showDistY = false
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, showControls = !!d3.fisheye
, fisheye = 0
, pauseFisheye = false
, tooltips = true
, tooltipX = function(key, x, y) { return '<strong>' + x + '</strong>' }
, tooltipY = function(key, x, y) { return '<strong>' + y + '</strong>' }
, tooltip = function(key, x, y, date) { return '<h3>' + key + '</h3>'
+ '<p>' + date + '</p>' }
, state = {}
, defaultState = null
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
, noData = "No Data Available."
, transitionDuration = 250
;
scatter
.xScale(x)
.yScale(y)
;
xAxis
.orient('bottom')
.tickPadding(10)
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
.tickPadding(10)
;
distX
.axis('x')
;
distY
.axis('y')
;
controls.updateState(false);
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var x0, y0;
var showTooltip = function(e, offsetElement) {
//TODO: make tooltip style an option between single or dual on axes (maybe on all charts with axes?)
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
leftX = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
topX = y.range()[0] + margin.top + ( offsetElement.offsetTop || 0),
leftY = x.range()[0] + margin.left + ( offsetElement.offsetLeft || 0 ),
topY = e.pos[1] + ( offsetElement.offsetTop || 0),
xVal = xAxis.tickFormat()(scatter.x()(e.point, e.pointIndex)),
yVal = yAxis.tickFormat()(scatter.y()(e.point, e.pointIndex));
if( tooltipX != null )
nv.tooltip.show([leftX, topX], tooltipX(e.series.key, xVal, yVal, e, chart), 'n', 1, offsetElement, 'x-nvtooltip');
if( tooltipY != null )
nv.tooltip.show([leftY, topY], tooltipY(e.series.key, xVal, yVal, e, chart), 'e', 1, offsetElement, 'y-nvtooltip');
if( tooltip != null )
nv.tooltip.show([left, top], tooltip(e.series.key, xVal, yVal, e.point.tooltip, e, chart), e.value < 0 ? 'n' : 's', null, offsetElement);
};
var controlsData = [
{ key: 'Magnify', disabled: true }
];
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart); };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
//------------------------------------------------------------
// Display noData message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = scatter.xScale();
y = scatter.yScale();
x0 = x0 || x;
y0 = y0 || y;
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id());
var gEnter = wrapEnter.append('g');
var g = wrap.select('g')
// background for pointer events
gEnter.append('rect').attr('class', 'nvd3 nv-background').style("pointer-events","none");
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-scatterWrap');
gEnter.append('g').attr('class', 'nv-regressionLinesWrap');
gEnter.append('g').attr('class', 'nv-distWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//------------------------------------------------------------
//------------------------------------------------------------
// Legend
if (showLegend) {
legend.width( availableWidth / 2 );
wrap.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
wrap.select('.nv-legendWrap')
.attr('transform', 'translate(' + (availableWidth / 2) + ',' + (-margin.top) +')');
}
//------------------------------------------------------------
//------------------------------------------------------------
// Controls
if (showControls) {
controls.width(180).color(['#444']);
g.select('.nv-controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
}
//------------------------------------------------------------
//------------------------------------------------------------
// Main Chart Component(s)
scatter
.width(availableWidth)
.height(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }))
wrap.select('.nv-scatterWrap')
.datum(data.filter(function(d) { return !d.disabled }))
.call(scatter);
wrap.select('.nv-regressionLinesWrap')
.attr('clip-path', 'url(#nv-edge-clip-' + scatter.id() + ')');
var regWrap = wrap.select('.nv-regressionLinesWrap').selectAll('.nv-regLines')
.data(function(d) {return d });
regWrap.enter().append('g').attr('class', 'nv-regLines');
var regLine = regWrap.selectAll('.nv-regLine').data(function(d){return [d]});
var regLineEnter = regLine.enter()
.append('line').attr('class', 'nv-regLine')
.style('stroke-opacity', 0);
regLine
.transition()
.attr('x1', x.range()[0])
.attr('x2', x.range()[1])
.attr('y1', function(d,i) {return y(x.domain()[0] * d.slope + d.intercept) })
.attr('y2', function(d,i) { return y(x.domain()[1] * d.slope + d.intercept) })
.style('stroke', function(d,i,j) { return color(d,j) })
.style('stroke-opacity', function(d,i) {
return (d.disabled || typeof d.slope === 'undefined' || typeof d.intercept === 'undefined') ? 0 : 1
});
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
.ticks( xAxis.ticks() ? xAxis.ticks() : availableWidth / 100 )
.tickSize( -availableHeight , 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')')
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
.ticks( yAxis.ticks() ? yAxis.ticks() : availableHeight / 36 )
.tickSize( -availableWidth, 0);
g.select('.nv-y.nv-axis')
.call(yAxis);
}
if (showDistX) {
distX
.getData(scatter.x())
.scale(x)
.width(availableWidth)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
gEnter.select('.nv-distWrap').append('g')
.attr('class', 'nv-distributionX');
g.select('.nv-distributionX')
.attr('transform', 'translate(0,' + y.range()[0] + ')')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distX);
}
if (showDistY) {
distY
.getData(scatter.y())
.scale(y)
.width(availableHeight)
.color(data.map(function(d,i) {
return d.color || color(d, i);
}).filter(function(d,i) { return !data[i].disabled }));
gEnter.select('.nv-distWrap').append('g')
.attr('class', 'nv-distributionY');
g.select('.nv-distributionY')
.attr('transform', 'translate(' + (rightAlignYAxis ? availableWidth : -distY.size() ) + ',0)')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distY);
}
//------------------------------------------------------------
if (d3.fisheye) {
g.select('.nv-background')
.attr('width', availableWidth)
.attr('height', availableHeight)
;
g.select('.nv-background').on('mousemove', updateFisheye);
g.select('.nv-background').on('click', function() { pauseFisheye = !pauseFisheye;});
scatter.dispatch.on('elementClick.freezeFisheye', function() {
pauseFisheye = !pauseFisheye;
});
}
function updateFisheye() {
if (pauseFisheye) {
g.select('.nv-point-paths').style('pointer-events', 'all');
return false;
}
g.select('.nv-point-paths').style('pointer-events', 'none' );
var mouse = d3.mouse(this);
x.distortion(fisheye).focus(mouse[0]);
y.distortion(fisheye).focus(mouse[1]);
g.select('.nv-scatterWrap')
.datum(data.filter(function(d) { return !d.disabled }))
.call(scatter);
if (showXAxis)
g.select('.nv-x.nv-axis').call(xAxis);
if (showYAxis)
g.select('.nv-y.nv-axis').call(yAxis);
g.select('.nv-distributionX')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distX);
g.select('.nv-distributionY')
.datum(data.filter(function(d) { return !d.disabled }))
.call(distY);
}
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
controls.dispatch.on('legendClick', function(d,i) {
d.disabled = !d.disabled;
fisheye = d.disabled ? 0 : 2.5;
g.select('.nv-background') .style('pointer-events', d.disabled ? 'none' : 'all');
g.select('.nv-point-paths').style('pointer-events', d.disabled ? 'all' : 'none' );
if (d.disabled) {
x.distortion(fisheye).focus(0);
y.distortion(fisheye).focus(0);
g.select('.nv-scatterWrap').call(scatter);
g.select('.nv-x.nv-axis').call(xAxis);
g.select('.nv-y.nv-axis').call(yAxis);
} else {
pauseFisheye = false;
}
chart.update();
});
legend.dispatch.on('stateChange', function(newState) {
state = newState;
dispatch.stateChange(state);
chart.update();
});
scatter.dispatch.on('elementMouseover.tooltip', function(e) {
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex)
.attr('y1', e.pos[1] - availableHeight);
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex)
.attr('x2', e.pos[0] + distX.size());
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
dispatch.tooltipShow(e);
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined') {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
chart.update();
});
//============================================================
//store old scales for use in transitions on update
x0 = x.copy();
y0 = y.copy();
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
scatter.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex)
.attr('y1', 0);
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex)
.attr('x2', distY.size());
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.scatter = scatter;
chart.legend = legend;
chart.controls = controls;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.distX = distX;
chart.distY = distY;
d3.rebind(chart, scatter, 'id', 'interactive', 'pointActive', 'x', 'y', 'shape', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'xRange', 'yRange', 'sizeDomain', 'sizeRange', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'useVoronoi');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
distX.color(color);
distY.color(color);
return chart;
};
chart.showDistX = function(_) {
if (!arguments.length) return showDistX;
showDistX = _;
return chart;
};
chart.showDistY = function(_) {
if (!arguments.length) return showDistY;
showDistY = _;
return chart;
};
chart.showControls = function(_) {
if (!arguments.length) return showControls;
showControls = _;
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.showXAxis = function(_) {
if (!arguments.length) return showXAxis;
showXAxis = _;
return chart;
};
chart.showYAxis = function(_) {
if (!arguments.length) return showYAxis;
showYAxis = _;
return chart;
};
chart.rightAlignYAxis = function(_) {
if(!arguments.length) return rightAlignYAxis;
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
return chart;
};
chart.fisheye = function(_) {
if (!arguments.length) return fisheye;
fisheye = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.tooltipXContent = function(_) {
if (!arguments.length) return tooltipX;
tooltipX = _;
return chart;
};
chart.tooltipYContent = function(_) {
if (!arguments.length) return tooltipY;
tooltipY = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
//============================================================
return chart;
}
nv.models.sparkline = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 2, right: 0, bottom: 2, left: 0}
, width = 400
, height = 32
, animate = true
, x = d3.scale.linear()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, color = nv.utils.getColor(['#000'])
, xDomain
, yDomain
, xRange
, yRange
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
//------------------------------------------------------------
// Setup Scales
x .domain(xDomain || d3.extent(data, getX ))
.range(xRange || [0, availableWidth]);
y .domain(yDomain || d3.extent(data, getY ))
.range(yRange || [availableHeight, 0]);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-sparkline').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparkline');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
//------------------------------------------------------------
var paths = wrap.selectAll('path')
.data(function(d) { return [d] });
paths.enter().append('path');
paths.exit().remove();
paths
.style('stroke', function(d,i) { return d.color || color(d, i) })
.attr('d', d3.svg.line()
.x(function(d,i) { return x(getX(d,i)) })
.y(function(d,i) { return y(getY(d,i)) })
);
// TODO: Add CURRENT data point (Need Min, Mac, Current / Most recent)
var points = wrap.selectAll('circle.nv-point')
.data(function(data) {
var yValues = data.map(function(d, i) { return getY(d,i); });
function pointIndex(index) {
if (index != -1) {
var result = data[index];
result.pointIndex = index;
return result;
} else {
return null;
}
}
var maxPoint = pointIndex(yValues.lastIndexOf(y.domain()[1])),
minPoint = pointIndex(yValues.indexOf(y.domain()[0])),
currentPoint = pointIndex(yValues.length - 1);
return [minPoint, maxPoint, currentPoint].filter(function (d) {return d != null;});
});
points.enter().append('circle');
points.exit().remove();
points
.attr('cx', function(d,i) { return x(getX(d,d.pointIndex)) })
.attr('cy', function(d,i) { return y(getY(d,d.pointIndex)) })
.attr('r', 2)
.attr('class', function(d,i) {
return getX(d, d.pointIndex) == x.domain()[1] ? 'nv-point nv-currentValue' :
getY(d, d.pointIndex) == y.domain()[0] ? 'nv-point nv-minValue' : 'nv-point nv-maxValue'
});
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.x = function(_) {
if (!arguments.length) return getX;
getX = d3.functor(_);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = d3.functor(_);
return chart;
};
chart.xScale = function(_) {
if (!arguments.length) return x;
x = _;
return chart;
};
chart.yScale = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.xDomain = function(_) {
if (!arguments.length) return xDomain;
xDomain = _;
return chart;
};
chart.yDomain = function(_) {
if (!arguments.length) return yDomain;
yDomain = _;
return chart;
};
chart.xRange = function(_) {
if (!arguments.length) return xRange;
xRange = _;
return chart;
};
chart.yRange = function(_) {
if (!arguments.length) return yRange;
yRange = _;
return chart;
};
chart.animate = function(_) {
if (!arguments.length) return animate;
animate = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
//============================================================
return chart;
}
nv.models.sparklinePlus = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var sparkline = nv.models.sparkline();
var margin = {top: 15, right: 100, bottom: 10, left: 50}
, width = null
, height = null
, x
, y
, index = []
, paused = false
, xTickFormat = d3.format(',r')
, yTickFormat = d3.format(',.2f')
, showValue = true
, alignValue = true
, rightAlignValue = false
, noData = "No Data Available."
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this);
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { chart(selection) };
chart.container = this;
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data || !data.length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
var currentValue = sparkline.y()(data[data.length-1], data.length-1);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = sparkline.xScale();
y = sparkline.yScale();
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-sparklineplus').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparklineplus');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-sparklineWrap');
gEnter.append('g').attr('class', 'nv-valueWrap');
gEnter.append('g').attr('class', 'nv-hoverArea');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
//------------------------------------------------------------
// Main Chart Component(s)
var sparklineWrap = g.select('.nv-sparklineWrap');
sparkline
.width(availableWidth)
.height(availableHeight);
sparklineWrap
.call(sparkline);
//------------------------------------------------------------
var valueWrap = g.select('.nv-valueWrap');
var value = valueWrap.selectAll('.nv-currentValue')
.data([currentValue]);
value.enter().append('text').attr('class', 'nv-currentValue')
.attr('dx', rightAlignValue ? -8 : 8)
.attr('dy', '.9em')
.style('text-anchor', rightAlignValue ? 'end' : 'start');
value
.attr('x', availableWidth + (rightAlignValue ? margin.right : 0))
.attr('y', alignValue ? function(d) { return y(d) } : 0)
.style('fill', sparkline.color()(data[data.length-1], data.length-1))
.text(yTickFormat(currentValue));
gEnter.select('.nv-hoverArea').append('rect')
.on('mousemove', sparklineHover)
.on('click', function() { paused = !paused })
.on('mouseout', function() { index = []; updateValueLine(); });
//.on('mouseout', function() { index = null; updateValueLine(); });
g.select('.nv-hoverArea rect')
.attr('transform', function(d) { return 'translate(' + -margin.left + ',' + -margin.top + ')' })
.attr('width', availableWidth + margin.left + margin.right)
.attr('height', availableHeight + margin.top);
function updateValueLine() { //index is currently global (within the chart), may or may not keep it that way
if (paused) return;
var hoverValue = g.selectAll('.nv-hoverValue').data(index)
var hoverEnter = hoverValue.enter()
.append('g').attr('class', 'nv-hoverValue')
.style('stroke-opacity', 0)
.style('fill-opacity', 0);
hoverValue.exit()
.transition().duration(250)
.style('stroke-opacity', 0)
.style('fill-opacity', 0)
.remove();
hoverValue
.attr('transform', function(d) { return 'translate(' + x(sparkline.x()(data[d],d)) + ',0)' })
.transition().duration(250)
.style('stroke-opacity', 1)
.style('fill-opacity', 1);
if (!index.length) return;
hoverEnter.append('line')
.attr('x1', 0)
.attr('y1', -margin.top)
.attr('x2', 0)
.attr('y2', availableHeight);
hoverEnter.append('text').attr('class', 'nv-xValue')
.attr('x', -6)
.attr('y', -margin.top)
.attr('text-anchor', 'end')
.attr('dy', '.9em')
g.select('.nv-hoverValue .nv-xValue')
.text(xTickFormat(sparkline.x()(data[index[0]], index[0])));
hoverEnter.append('text').attr('class', 'nv-yValue')
.attr('x', 6)
.attr('y', -margin.top)
.attr('text-anchor', 'start')
.attr('dy', '.9em')
g.select('.nv-hoverValue .nv-yValue')
.text(yTickFormat(sparkline.y()(data[index[0]], index[0])));
}
function sparklineHover() {
if (paused) return;
var pos = d3.mouse(this)[0] - margin.left;
function getClosestIndex(data, x) {
var distance = Math.abs(sparkline.x()(data[0], 0) - x);
var closestIndex = 0;
for (var i = 0; i < data.length; i++){
if (Math.abs(sparkline.x()(data[i], i) - x) < distance) {
distance = Math.abs(sparkline.x()(data[i], i) - x);
closestIndex = i;
}
}
return closestIndex;
}
index = [getClosestIndex(data, Math.round(x.invert(pos)))];
updateValueLine();
}
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.sparkline = sparkline;
d3.rebind(chart, sparkline, 'x', 'y', 'xScale', 'yScale', 'color');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.xTickFormat = function(_) {
if (!arguments.length) return xTickFormat;
xTickFormat = _;
return chart;
};
chart.yTickFormat = function(_) {
if (!arguments.length) return yTickFormat;
yTickFormat = _;
return chart;
};
chart.showValue = function(_) {
if (!arguments.length) return showValue;
showValue = _;
return chart;
};
chart.alignValue = function(_) {
if (!arguments.length) return alignValue;
alignValue = _;
return chart;
};
chart.rightAlignValue = function(_) {
if (!arguments.length) return rightAlignValue;
rightAlignValue = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
//============================================================
return chart;
}
nv.models.stackedArea = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, color = nv.utils.defaultColor() // a function that computes the color
, id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't selet one
, getX = function(d) { return d.x } // accessor to get the x value from a data point
, getY = function(d) { return d.y } // accessor to get the y value from a data point
, style = 'stack'
, offset = 'zero'
, order = 'default'
, interpolate = 'linear' // controls the line interpolation
, clipEdge = false // if true, masks lines within x and y scale
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, scatter = nv.models.scatter()
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'areaClick', 'areaMouseover', 'areaMouseout')
;
scatter
.size(2.2) // default size
.sizeDomain([2.2,2.2]) // all the same size by default
;
/************************************
* offset:
* 'wiggle' (stream)
* 'zero' (stacked)
* 'expand' (normalize to 100%)
* 'silhouette' (simple centered)
*
* order:
* 'inside-out' (stream)
* 'default' (input order)
************************************/
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
//------------------------------------------------------------
// Setup Scales
x = scatter.xScale();
y = scatter.yScale();
//------------------------------------------------------------
var dataRaw = data;
// Injecting point index into each point because d3.layout.stack().out does not give index
data.forEach(function(aseries, i) {
aseries.seriesIndex = i;
aseries.values = aseries.values.map(function(d, j) {
d.index = j;
d.seriesIndex = i;
return d;
});
});
var dataFiltered = data.filter(function(series) {
return !series.disabled;
});
data = d3.layout.stack()
.order(order)
.offset(offset)
.values(function(d) { return d.values }) //TODO: make values customizeable in EVERY model in this fashion
.x(getX)
.y(getY)
.out(function(d, y0, y) {
var yHeight = (getY(d) === 0) ? 0 : y;
d.display = {
y: yHeight,
y0: y0
};
})
(dataFiltered);
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-stackedarea').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedarea');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-areaWrap');
gEnter.append('g').attr('class', 'nv-scatterWrap');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
scatter
.width(availableWidth)
.height(availableHeight)
.x(getX)
.y(function(d) { return d.display.y + d.display.y0 })
.forceY([0])
.color(data.map(function(d,i) {
return d.color || color(d, d.seriesIndex);
}));
var scatterWrap = g.select('.nv-scatterWrap')
.datum(data);
scatterWrap.call(scatter);
defsEnter.append('clipPath')
.attr('id', 'nv-edge-clip-' + id)
.append('rect');
wrap.select('#nv-edge-clip-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
var area = d3.svg.area()
.x(function(d,i) { return x(getX(d,i)) })
.y0(function(d) {
return y(d.display.y0)
})
.y1(function(d) {
return y(d.display.y + d.display.y0)
})
.interpolate(interpolate);
var zeroArea = d3.svg.area()
.x(function(d,i) { return x(getX(d,i)) })
.y0(function(d) { return y(d.display.y0) })
.y1(function(d) { return y(d.display.y0) });
var path = g.select('.nv-areaWrap').selectAll('path.nv-area')
.data(function(d) { return d });
path.enter().append('path').attr('class', function(d,i) { return 'nv-area nv-area-' + i })
.attr('d', function(d,i){
return zeroArea(d.values, d.seriesIndex);
})
.on('mouseover', function(d,i) {
d3.select(this).classed('hover', true);
dispatch.areaMouseover({
point: d,
series: d.key,
pos: [d3.event.pageX, d3.event.pageY],
seriesIndex: d.seriesIndex
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.areaMouseout({
point: d,
series: d.key,
pos: [d3.event.pageX, d3.event.pageY],
seriesIndex: d.seriesIndex
});
})
.on('click', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.areaClick({
point: d,
series: d.key,
pos: [d3.event.pageX, d3.event.pageY],
seriesIndex: d.seriesIndex
});
})
path.exit().remove();
path
.style('fill', function(d,i){
return d.color || color(d, d.seriesIndex)
})
.style('stroke', function(d,i){ return d.color || color(d, d.seriesIndex) });
path.transition()
.attr('d', function(d,i) {
return area(d.values,i)
});
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
scatter.dispatch.on('elementMouseover.area', function(e) {
g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', true);
});
scatter.dispatch.on('elementMouseout.area', function(e) {
g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', false);
});
//============================================================
//Special offset functions
chart.d3_stackedOffset_stackPercent = function(stackData) {
var n = stackData.length, //How many series
m = stackData[0].length, //how many points per series
k = 1 / n,
i,
j,
o,
y0 = [];
for (j = 0; j < m; ++j) { //Looping through all points
for (i = 0, o = 0; i < dataRaw.length; i++) //looping through series'
o += getY(dataRaw[i].values[j]) //total value of all points at a certian point in time.
if (o) for (i = 0; i < n; i++)
stackData[i][j][1] /= o;
else
for (i = 0; i < n; i++)
stackData[i][j][1] = k;
}
for (j = 0; j < m; ++j) y0[j] = 0;
return y0;
};
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
scatter.dispatch.on('elementClick.area', function(e) {
dispatch.areaClick(e);
})
scatter.dispatch.on('elementMouseover.tooltip', function(e) {
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top],
dispatch.tooltipShow(e);
});
scatter.dispatch.on('elementMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
//============================================================
//============================================================
// Global getters and setters
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.scatter = scatter;
d3.rebind(chart, scatter, 'interactive', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'xRange', 'yRange',
'sizeDomain', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'useVoronoi','clipRadius','highlightPoint','clearHighlights');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.x = function(_) {
if (!arguments.length) return getX;
getX = d3.functor(_);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = d3.functor(_);
return chart;
}
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.clipEdge = function(_) {
if (!arguments.length) return clipEdge;
clipEdge = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.offset = function(_) {
if (!arguments.length) return offset;
offset = _;
return chart;
};
chart.order = function(_) {
if (!arguments.length) return order;
order = _;
return chart;
};
//shortcut for offset + order
chart.style = function(_) {
if (!arguments.length) return style;
style = _;
switch (style) {
case 'stack':
chart.offset('zero');
chart.order('default');
break;
case 'stream':
chart.offset('wiggle');
chart.order('inside-out');
break;
case 'stream-center':
chart.offset('silhouette');
chart.order('inside-out');
break;
case 'expand':
chart.offset('expand');
chart.order('default');
break;
case 'stack_percent':
chart.offset(chart.d3_stackedOffset_stackPercent);
chart.order('default');
break;
}
return chart;
};
chart.interpolate = function(_) {
if (!arguments.length) return interpolate;
interpolate = _;
return chart;
};
//============================================================
return chart;
}
nv.models.stackedAreaChart = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var stacked = nv.models.stackedArea()
, xAxis = nv.models.axis()
, yAxis = nv.models.axis()
, legend = nv.models.legend()
, controls = nv.models.legend()
, interactiveLayer = nv.interactiveGuideline()
;
var margin = {top: 30, right: 25, bottom: 50, left: 60}
, width = null
, height = null
, color = nv.utils.defaultColor() // a function that takes in d, i and returns color
, showControls = true
, showLegend = true
, showXAxis = true
, showYAxis = true
, rightAlignYAxis = false
, useInteractiveGuideline = false
, tooltips = true
, tooltip = function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' on ' + x + '</p>'
}
, x //can be accessed via chart.xScale()
, y //can be accessed via chart.yScale()
, yAxisTickFormat = d3.format(',.2f')
, state = { style: stacked.style() }
, defaultState = null
, noData = 'No Data Available.'
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
, controlWidth = 250
, cData = ['Stacked','Stream','Expanded']
, controlLabels = {}
, transitionDuration = 250
;
xAxis
.orient('bottom')
.tickPadding(7)
;
yAxis
.orient((rightAlignYAxis) ? 'right' : 'left')
;
controls.updateState(false);
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var showTooltip = function(e, offsetElement) {
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
top = e.pos[1] + ( offsetElement.offsetTop || 0),
x = xAxis.tickFormat()(stacked.x()(e.point, e.pointIndex)),
y = yAxis.tickFormat()(stacked.y()(e.point, e.pointIndex)),
content = tooltip(e.series.key, x, y, e, chart);
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement);
};
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this),
that = this;
var availableWidth = (width || parseInt(container.style('width')) || 960)
- margin.left - margin.right,
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
chart.update = function() { container.transition().duration(transitionDuration).call(chart); };
chart.container = this;
//set state.disabled
state.disabled = data.map(function(d) { return !!d.disabled });
if (!defaultState) {
var key;
defaultState = {};
for (key in state) {
if (state[key] instanceof Array)
defaultState[key] = state[key].slice(0);
else
defaultState[key] = state[key];
}
}
//------------------------------------------------------------
// Display No Data message if there's nothing to show.
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
var noDataText = container.selectAll('.nv-noData').data([noData]);
noDataText.enter().append('text')
.attr('class', 'nvd3 nv-noData')
.attr('dy', '-.7em')
.style('text-anchor', 'middle');
noDataText
.attr('x', margin.left + availableWidth / 2)
.attr('y', margin.top + availableHeight / 2)
.text(function(d) { return d });
return chart;
} else {
container.selectAll('.nv-noData').remove();
}
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Scales
x = stacked.xScale();
y = stacked.yScale();
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-stackedAreaChart').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedAreaChart').append('g');
var g = wrap.select('g');
gEnter.append("rect").style("opacity",0);
gEnter.append('g').attr('class', 'nv-x nv-axis');
gEnter.append('g').attr('class', 'nv-y nv-axis');
gEnter.append('g').attr('class', 'nv-stackedWrap');
gEnter.append('g').attr('class', 'nv-legendWrap');
gEnter.append('g').attr('class', 'nv-controlsWrap');
gEnter.append('g').attr('class', 'nv-interactive');
g.select("rect").attr("width",availableWidth).attr("height",availableHeight);
//------------------------------------------------------------
// Legend
if (showLegend) {
var legendWidth = (showControls) ? availableWidth - controlWidth : availableWidth;
legend
.width(legendWidth);
g.select('.nv-legendWrap')
.datum(data)
.call(legend);
if ( margin.top != legend.height()) {
margin.top = legend.height();
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
g.select('.nv-legendWrap')
.attr('transform', 'translate(' + (availableWidth-legendWidth) + ',' + (-margin.top) +')');
}
//------------------------------------------------------------
//------------------------------------------------------------
// Controls
if (showControls) {
var controlsData = [
{
key: controlLabels.stacked || 'Stacked',
metaKey: 'Stacked',
disabled: stacked.style() != 'stack',
style: 'stack'
},
{
key: controlLabels.stream || 'Stream',
metaKey: 'Stream',
disabled: stacked.style() != 'stream',
style: 'stream'
},
{
key: controlLabels.expanded || 'Expanded',
metaKey: 'Expanded',
disabled: stacked.style() != 'expand',
style: 'expand'
},
{
key: controlLabels.stack_percent || 'Stack %',
metaKey: 'Stack_Percent',
disabled: stacked.style() != 'stack_percent',
style: 'stack_percent'
}
];
controlWidth = (cData.length/3) * 260;
controlsData = controlsData.filter(function(d) {
return cData.indexOf(d.metaKey) !== -1;
})
controls
.width( controlWidth )
.color(['#444', '#444', '#444']);
g.select('.nv-controlsWrap')
.datum(controlsData)
.call(controls);
if ( margin.top != Math.max(controls.height(), legend.height()) ) {
margin.top = Math.max(controls.height(), legend.height());
availableHeight = (height || parseInt(container.style('height')) || 400)
- margin.top - margin.bottom;
}
g.select('.nv-controlsWrap')
.attr('transform', 'translate(0,' + (-margin.top) +')');
}
//------------------------------------------------------------
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
if (rightAlignYAxis) {
g.select(".nv-y.nv-axis")
.attr("transform", "translate(" + availableWidth + ",0)");
}
//------------------------------------------------------------
// Main Chart Component(s)
//------------------------------------------------------------
//Set up interactive layer
if (useInteractiveGuideline) {
interactiveLayer
.width(availableWidth)
.height(availableHeight)
.margin({left: margin.left, top: margin.top})
.svgContainer(container)
.xScale(x);
wrap.select(".nv-interactive").call(interactiveLayer);
}
stacked
.width(availableWidth)
.height(availableHeight)
var stackedWrap = g.select('.nv-stackedWrap')
.datum(data);
stackedWrap.transition().call(stacked);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup Axes
if (showXAxis) {
xAxis
.scale(x)
.ticks( availableWidth / 100 )
.tickSize( -availableHeight, 0);
g.select('.nv-x.nv-axis')
.attr('transform', 'translate(0,' + availableHeight + ')');
g.select('.nv-x.nv-axis')
.transition().duration(0)
.call(xAxis);
}
if (showYAxis) {
yAxis
.scale(y)
.ticks(stacked.offset() == 'wiggle' ? 0 : availableHeight / 36)
.tickSize(-availableWidth, 0)
.setTickFormat( (stacked.style() == 'expand' || stacked.style() == 'stack_percent')
? d3.format('%') : yAxisTickFormat);
g.select('.nv-y.nv-axis')
.transition().duration(0)
.call(yAxis);
}
//------------------------------------------------------------
//============================================================
// Event Handling/Dispatching (in chart's scope)
//------------------------------------------------------------
stacked.dispatch.on('areaClick.toggle', function(e) {
if (data.filter(function(d) { return !d.disabled }).length === 1)
data.forEach(function(d) {
d.disabled = false;
});
else
data.forEach(function(d,i) {
d.disabled = (i != e.seriesIndex);
});
state.disabled = data.map(function(d) { return !!d.disabled });
dispatch.stateChange(state);
chart.update();
});
legend.dispatch.on('stateChange', function(newState) {
state.disabled = newState.disabled;
dispatch.stateChange(state);
chart.update();
});
controls.dispatch.on('legendClick', function(d,i) {
if (!d.disabled) return;
controlsData = controlsData.map(function(s) {
s.disabled = true;
return s;
});
d.disabled = false;
stacked.style(d.style);
state.style = stacked.style();
dispatch.stateChange(state);
chart.update();
});
interactiveLayer.dispatch.on('elementMousemove', function(e) {
stacked.clearHighlights();
var singlePoint, pointIndex, pointXLocation, allData = [];
data
.filter(function(series, i) {
series.seriesIndex = i;
return !series.disabled;
})
.forEach(function(series,i) {
pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
stacked.highlightPoint(i, pointIndex, true);
var point = series.values[pointIndex];
if (typeof point === 'undefined') return;
if (typeof singlePoint === 'undefined') singlePoint = point;
if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
//If we are in 'expand' mode, use the stacked percent value instead of raw value.
var tooltipValue = (stacked.style() == 'expand') ? point.display.y : chart.y()(point,pointIndex);
allData.push({
key: series.key,
value: tooltipValue,
color: color(series,series.seriesIndex),
stackedValue: point.display
});
});
allData.reverse();
//Highlight the tooltip entry based on which stack the mouse is closest to.
if (allData.length > 2) {
var yValue = chart.yScale().invert(e.mouseY);
var yDistMax = Infinity, indexToHighlight = null;
allData.forEach(function(series,i) {
//To handle situation where the stacked area chart is negative, we need to use absolute values
//when checking if the mouse Y value is within the stack area.
yValue = Math.abs(yValue);
var stackedY0 = Math.abs(series.stackedValue.y0);
var stackedY = Math.abs(series.stackedValue.y);
if ( yValue >= stackedY0 && yValue <= (stackedY + stackedY0))
{
indexToHighlight = i;
return;
}
});
if (indexToHighlight != null)
allData[indexToHighlight].highlight = true;
}
var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex));
//If we are in 'expand' mode, force the format to be a percentage.
var valueFormatter = (stacked.style() == 'expand') ?
function(d,i) {return d3.format(".1%")(d);} :
function(d,i) {return yAxis.tickFormat()(d); };
interactiveLayer.tooltip
.position({left: pointXLocation + margin.left, top: e.mouseY + margin.top})
.chartContainer(that.parentNode)
.enabled(tooltips)
.valueFormatter(valueFormatter)
.data(
{
value: xValue,
series: allData
}
)();
interactiveLayer.renderGuideLine(pointXLocation);
});
interactiveLayer.dispatch.on("elementMouseout",function(e) {
dispatch.tooltipHide();
stacked.clearHighlights();
});
dispatch.on('tooltipShow', function(e) {
if (tooltips) showTooltip(e, that.parentNode);
});
// Update chart from a state object passed to event handler
dispatch.on('changeState', function(e) {
if (typeof e.disabled !== 'undefined' && data.length === e.disabled.length) {
data.forEach(function(series,i) {
series.disabled = e.disabled[i];
});
state.disabled = e.disabled;
}
if (typeof e.style !== 'undefined') {
stacked.style(e.style);
}
chart.update();
});
});
return chart;
}
//============================================================
// Event Handling/Dispatching (out of chart's scope)
//------------------------------------------------------------
stacked.dispatch.on('tooltipShow', function(e) {
//disable tooltips when value ~= 0
//// TODO: consider removing points from voronoi that have 0 value instead of this hack
/*
if (!Math.round(stacked.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range
setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0);
return false;
}
*/
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top],
dispatch.tooltipShow(e);
});
stacked.dispatch.on('tooltipHide', function(e) {
dispatch.tooltipHide(e);
});
dispatch.on('tooltipHide', function() {
if (tooltips) nv.tooltip.cleanup();
});
//============================================================
//============================================================
// Expose Public Variables
//------------------------------------------------------------
// expose chart's sub-components
chart.dispatch = dispatch;
chart.stacked = stacked;
chart.legend = legend;
chart.controls = controls;
chart.xAxis = xAxis;
chart.yAxis = yAxis;
chart.interactiveLayer = interactiveLayer;
d3.rebind(chart, stacked, 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'xRange', 'yRange', 'sizeDomain', 'interactive', 'useVoronoi', 'offset', 'order', 'style', 'clipEdge', 'forceX', 'forceY', 'forceSize', 'interpolate');
chart.options = nv.utils.optionsFunc.bind(chart);
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
legend.color(color);
stacked.color(color);
return chart;
};
chart.showControls = function(_) {
if (!arguments.length) return showControls;
showControls = _;
return chart;
};
chart.showLegend = function(_) {
if (!arguments.length) return showLegend;
showLegend = _;
return chart;
};
chart.showXAxis = function(_) {
if (!arguments.length) return showXAxis;
showXAxis = _;
return chart;
};
chart.showYAxis = function(_) {
if (!arguments.length) return showYAxis;
showYAxis = _;
return chart;
};
chart.rightAlignYAxis = function(_) {
if(!arguments.length) return rightAlignYAxis;
rightAlignYAxis = _;
yAxis.orient( (_) ? 'right' : 'left');
return chart;
};
chart.useInteractiveGuideline = function(_) {
if(!arguments.length) return useInteractiveGuideline;
useInteractiveGuideline = _;
if (_ === true) {
chart.interactive(false);
chart.useVoronoi(false);
}
return chart;
};
chart.tooltip = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.tooltips = function(_) {
if (!arguments.length) return tooltips;
tooltips = _;
return chart;
};
chart.tooltipContent = function(_) {
if (!arguments.length) return tooltip;
tooltip = _;
return chart;
};
chart.state = function(_) {
if (!arguments.length) return state;
state = _;
return chart;
};
chart.defaultState = function(_) {
if (!arguments.length) return defaultState;
defaultState = _;
return chart;
};
chart.noData = function(_) {
if (!arguments.length) return noData;
noData = _;
return chart;
};
chart.transitionDuration = function(_) {
if (!arguments.length) return transitionDuration;
transitionDuration = _;
return chart;
};
chart.controlsData = function(_) {
if (!arguments.length) return cData;
cData = _;
return chart;
};
chart.controlLabels = function(_) {
if (!arguments.length) return controlLabels;
if (typeof _ !== 'object') return controlLabels;
controlLabels = _;
return chart;
};
yAxis.setTickFormat = yAxis.tickFormat;
yAxis.tickFormat = function(_) {
if (!arguments.length) return yAxisTickFormat;
yAxisTickFormat = _;
return yAxis;
};
//============================================================
return chart;
}
})(); |
module.exports = function (sequelize, DataTypes) {
var Play = sequelize.define(
"Play",
{
id: { type: DataTypes.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true },
site: { type: DataTypes.STRING },
positive: { type: DataTypes.INTEGER.UNSIGNED, defaultValue: 0 },
negative: { type: DataTypes.INTEGER.UNSIGNED, defaultValue: 0 },
grabs: { type: DataTypes.INTEGER.UNSIGNED, defaultValue: 0 },
listeners: { type: DataTypes.INTEGER.UNSIGNED, defaultValue: 0 },
skipped: { type: DataTypes.INTEGER.UNSIGNED, defaultValue: 0 },
},
{
underscored: true,
tableName: "plays",
}
);
Play.associate = function (models) {
Play.belongsTo(models.Song);
Play.belongsTo(models.User);
};
return Play;
};
|
// The integration test require the existence of a Team Projet named "TFS INTEGRATION"
// Or you can override that name using the VSO_TEST_PROJECT env name
// Agile process template and git
// It should have at least one bug assigned to the user that is executing the tests
// It should at least have a task (the first task requires at least 2 revisions)
var mocha = require( 'mocha' );
var should = require( 'should' );
var _ = require( 'lodash' );
var async = require( 'async' );
var Client = require( '../public/vso-client' );
var url = process.env.VSO_URL || 'https://your-account.visualstudio.com/';
var collection = process.env.VSO_COLLECTION || 'DefaultCollection';
var username = process.env.VSO_USER || 'your-username';
var password = process.env.VSO_PWD || 'your-password';
var serviceAccountUser = process.env.VSO_SERVICE_ACCOUNT_USER || 'your service account username';
var serviceAccountPassword = process.env.VSO_SERVICE_ACCOUNT_PWD || 'your service account password';
var oauthToken = process.env.VSO_OAUTH_TOKEN || 'dummyAccessToken';
var memberId = process.env.VSO_MEMBER_ID || '00000000-0000-0000-0000-000000000000';
var proxy = process.env.VSO_PROXY;
var testProjectName = process.env.VSO_TEST_PROJECT || 'TFS INTEGRATION';
function getOptions( overrideVersion ) {
options = {
apiVersion: overrideVersion || "1.0"
};
if ( typeof (proxy) !== "undefined" || proxy !== null ) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
options.clientOptions = {
proxy: proxy
};
}
return options;
}
describe( 'Versioning tests', function() {
before( function( done ) {
client = Client.createClient( url, collection, username, password, getOptions() );
done();
} );
it( 'equal version minimum met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.0", "1.0" );
minimumVersionMet.should.equal( true );
} );
it( 'equal version preview minimum met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.0-preview", "1.0-preview" );
minimumVersionMet.should.equal( true );
} );
it( 'greater version minimum met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.1", "1.0" );
minimumVersionMet.should.equal( true );
} );
it( 'greater version with preview minimum met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.1-preview", "1.0-preview" );
minimumVersionMet.should.equal( true );
} );
it( 'greater version with preview version minimum met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.1-preview", "1.0" );
minimumVersionMet.should.equal( true );
} );
it( 'greater version with preview version minimum not met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.0-preview", "1.1" );
minimumVersionMet.should.equal( false );
} );
it( 'equal version greater preview minimum met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.0-preview.2", "1.0-preview" );
minimumVersionMet.should.equal( true );
} );
it( 'equal version lower preview minimum not met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.0-preview", "1.0-preview.2" );
minimumVersionMet.should.equal( false );
} );
it( 'equal version lower non preview minimum met met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.0", "1.0-preview.2" );
minimumVersionMet.should.equal( true );
} );
it( 'equal version lower running preview required non preview minimum non met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.0-preview", "1.0" );
minimumVersionMet.should.equal( false );
} );
it( 'lower version minimum not met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.0", "1.2" );
minimumVersionMet.should.equal( false );
} );
it( 'lower version minimum preview not met', function() {
var minimumVersionMet = client.requireMinimumVersion( "1.0", "1.2-preview" );
minimumVersionMet.should.equal( false );
} );
} );
describe( 'User Agent Tests', function() {
it( 'has a default user agent string', function() {
var clientNoOptions = Client.createClient( url, collection, username, password );
should.exist( clientNoOptions );
clientNoOptions.should.have.property('userAgent');
clientNoOptions.userAgent.should.startWith('vso-client/1.0');
// console.log(clientNoOptions.userAgent);
} );
it( 'has a custom user agent string', function() {
var appName = 'My App 1.0';
var clientWithOptions = Client.createClient( url, collection, username, password, { userAgent: appName } );
should.exist( clientWithOptions );
clientWithOptions.should.have.property('userAgent');
clientWithOptions.userAgent.should.startWith(appName);
// console.log(clientWithOptions.userAgent);
} );
} );
describe( 'VSO API 1.0 Tests', function() {
this.timeout( 20000 );
var client = {};
before( function( done ) {
client = Client.createClient( url, collection, username, password, getOptions( "1.0" ) );
clientOAuth = Client.createOAuthClient( url, collection, oauthToken, getOptions( "1.0" ) );
// console.log(oauthToken);
done();
} );
describe( 'client tests', function() {
it( 'has a credential valid client', function() {
should.exist( client );
client.should.have.property( 'url' );
client.should.have.property( '_authType' );
client._authType.should.equal( 'Credential' );
should.exist( client.client );
should.not.exist( client.clientSPS );
} );
it( 'has a OAuth valid client', function() {
should.exist( clientOAuth );
clientOAuth.should.have.property( 'url' );
clientOAuth.should.have.property( '_authType' );
clientOAuth._authType.should.equal( 'OAuth' );
should.exist( clientOAuth.client );
should.exist( clientOAuth.clientSPS );
} );
it( 'has overriden version', function() {
var version = "1.0-preview-unitTest";
var clientWithVersion = Client.createClient( url, collection, username, password, { apiVersion: version } );
clientWithVersion.apiVersion.should.equal( version );
} );
it( 'has default version', function() {
var expectedVersion = "1.0";
var clientWithVersion = Client.createClient( url, collection, username, password );
clientWithVersion.apiVersion.should.equal( expectedVersion );
} );
describe( 'auth tests', function() {
it( 'fails authentication with error', function( done ) {
var clientWithWrongCredential = Client.createClient( url, collection, "DUMMY_USER_NAME", "DUMMY PASSWORD SET TO FAIL", getOptions() );
clientWithWrongCredential.getProjects( function( err, projects ) {
should.exist( err );
done();
} );
} );
} );
} );
describe( 'project tests', function() {
var testProject = null;
var testCollection = null;
var testTeam = null;
var tagName = null;
var testTag = null;
before( function( done ) {
tagName = 'testTag-' + ( Math.random() + 1 ).toString( 36 ).substring( 7 );
done();
} );
// ---------------------------------------
// Projects
// ---------------------------------------
it( 'returns a list of projects', function( done ) {
client.getProjects( function( err, projects ) {
should.not.exist( err );
should.exist( projects );
// console.log(projects);
projects.length.should.be.above( 0 );
var project = _.find( projects, function( p ) {
return p.name === testProjectName;
} );
should.exist( project );
// console.log(project);
project.should.have.property( 'id' );
project.should.have.property( 'name' );
project.should.have.property( 'url' );
project.should.have.property( 'state' );
testProject = project;
done();
} );
} );
it( 'returns only one project', function( done ) {
client.getProjects( null, 1, 0, function( err, projects ) {
should.not.exist( err );
should.exist( projects );
// console.log(projects);
projects.length.should.equal( 1 );
var project = projects[ 0 ];
project.should.have.property( 'id' );
project.should.have.property( 'name' );
project.should.have.property( 'url' );
done();
} );
} );
it( 'retrieves a project by id', function( done ) {
should.exist( testProject );
client.getProject( testProject.id, false, function( err, project ) {
if ( err ) {
console.log( err );
console.log( project );
}
should.not.exist( err );
should.exist( project );
// console.log(project);
project.should.have.property( 'id' );
project.should.have.property( 'name' );
project.should.have.property( 'url' );
should.exist( project._links );
should.exist( project._links.collection );
should.exist( project.defaultTeam );
done();
} );
} );
it( 'retrieves a project by id with capabilities', function( done ) {
should.exist( testProject );
client.getProject( testProject.id, true, function( err, project ) {
if ( err ) {
console.log( err );
console.log( project );
}
should.not.exist( err );
should.exist( project );
// console.log(project);
project.should.have.property( 'id' );
project.should.have.property( 'name' );
project.should.have.property( 'url' );
should.exist( project._links );
should.exist( project._links.collection );
should.exist( project.capabilities );
should.exist( project.capabilities.versioncontrol );
should.exist( project.capabilities.processTemplate );
should.exist( project.defaultTeam );
done();
} );
} );
// ---------------------------------------
// Project Teams
// ---------------------------------------
it( 'retrieves teams by project id', function( done ) {
should.exist( testProject );
client.getTeams( testProject.id, function( err, teams ) {
if ( err ) {
console.log( err );
console.log( teams );
}
should.not.exist( err );
should.exist( teams );
// console.log(teams);
teams.length.should.be.above( 0 );
var team = teams[ 0 ];
team.should.have.property( 'id' );
team.should.have.property( 'name' );
team.should.have.property( 'url' );
team.should.have.property( 'description' );
team.should.have.property( 'identityUrl' );
testTeam = team;
done();
} );
} );
it( 'retrieves a team by project and team id', function( done ) {
should.exist( testProject );
should.exist( testTeam );
client.getTeam( testProject.id, testTeam.id, function( err, team ) {
if ( err ) {
console.log( err );
console.log( team );
}
should.not.exist( err );
should.exist( team );
team.should.have.property( 'id' );
team.should.have.property( 'name' );
team.should.have.property( 'url' );
team.should.have.property( 'description' );
team.should.have.property( 'identityUrl' );
done();
} );
} );
it( 'retrieves team members by project and team id', function( done ) {
should.exist( testProject );
should.exist( testTeam );
client.getTeamMembers( testProject.id, testTeam.id, function( err, members ) {
if ( err ) {
console.log( err );
console.log( members );
}
should.not.exist( err );
should.exist( members );
// console.log(members);
members.length.should.be.above( 0 );
var member = members[ 0 ];
member.should.have.property( 'id' );
member.should.have.property( 'displayName' );
member.should.have.property( 'uniqueName' );
member.should.have.property( 'url' );
member.should.have.property( 'imageUrl' );
done();
} );
} );
// ---------------------------------------
// Collections
// ---------------------------------------
it( 'returns a list of project collections', function( done ) {
client.getProjectCollections( function( err, collections ) {
should.not.exist( err );
should.exist( collections );
// console.log(collections);
collections.length.should.be.above( 0 );
var collection = collections[ 0 ];
collection.should.have.property( 'id' );
collection.should.have.property( 'name' );
collection.should.have.property( 'url' );
collection.should.have.property( 'collectionUrl' );
collection.should.have.property( 'state' );
testCollection = collection;
done();
} );
} );
it( 'returns a project collection by id', function( done ) {
should.exist( testCollection );
client.getProjectCollection( testCollection.id, function( err, collection ) {
should.not.exist( err );
should.exist( collection );
collection.should.have.property( 'id' );
collection.should.have.property( 'name' );
collection.should.have.property( 'url' );
collection.should.have.property( 'collectionUrl' );
collection.should.have.property( 'state' );
done();
} );
} );
// ---------------------------------------
// Tags
// ---------------------------------------
it( 'creates a tag', function( done ) {
should.exist( testProject );
client.createTag( testProject.id, tagName, function( err, tag ) {
if ( err ) {
console.log( err );
console.log( tag );
}
should.not.exist( err );
should.exist( tag );
// console.log(tag);
testTag = tag;
done();
} );
} );
it( 'updates a tag', function( done ) {
should.exist( testProject );
should.exist( testTag );
client.updateTag( testProject.id, testTag.id, tagName + '-updated', true, function( err, tag ) {
if ( err ) {
console.log( err );
console.log( tag );
}
should.not.exist( err );
should.exist( tag );
// console.log(tag);
done();
} );
} );
it( 'retrieves tags by project id', function( done ) {
should.exist( testProject );
// Work-around, tags don't always immediately appear after being created
setTimeout( function( done ) {
client.getTags( testProject.id, true, function( err, tags ) {
if ( err ) {
console.log( err );
console.log( tags );
}
should.not.exist( err );
should.exist( tags );
// console.log(tags);
tags.length.should.be.above( 0 );
if ( tags.length > 0 ) {
var tag = tags[ 0 ];
tag.should.have.property( 'id' );
tag.should.have.property( 'name' );
tag.should.have.property( 'active' );
tag.should.have.property( 'url' );
}
done();
} );
}, 5000, done );
} );
it( 'deletes a tag', function( done ) {
should.exist( testProject );
should.exist( testTag );
client.deleteTag( testProject.id, testTag.id, function( err, tag ) {
if ( err ) {
console.log( err );
console.log( tag );
}
should.not.exist( err );
should.exist( tag );
// console.log(tag);
done();
} );
} );
} );
// ---------------------------------------
// Queries
// ---------------------------------------
describe( 'queries', function() {
var myQueries = null;
var testQuery = null;
var testFolder = null;
var myBugsQuery = null;
var testProject = null;
before( function( done ) {
client.getProjects( function( err, projects ) {
// console.log(err);
// console.log(projects);
testProject = _.find( projects, function( p ) {
return p.name === testProjectName;
} );
done();
} );
} );
it( 'returns a list of queries', function( done ) {
should.exist( testProject );
client.getQueries( testProject.name, 2, function( err, queries ) {
if ( err ) {
console.log( err );
console.log( queries );
}
should.not.exist( err );
should.exist( queries );
// console.log(queries);
queries.length.should.be.above( 0 );
var folder = _.find( queries, function( q ) {
return q.name === 'My Queries';
} );
should.exist( folder );
myQueries = folder;
var sharedFolder = _.find( queries, function( q ) {
return q.name === 'Shared Queries';
} );
should.exist( sharedFolder );
sharedFolder.children.should.be.instanceOf( Array );
sharedFolder.children.length.should.be.above( 0 );
// console.log(sharedFolder);
var query = _.find( sharedFolder.children, function( q ) {
return q.name === 'My Bugs';
} );
should.exist( query );
// console.log( query );
query.should.have.property( 'id' );
query.should.have.property( 'name' );
query.should.have.property( 'url' );
query.should.have.property( 'path' );
myBugsQuery = query;
done();
} );
} );
it( 'returns a list of work items from saved query', function( done ) {
should.exist( testProject );
should.exist( myBugsQuery );
client.getWorkItemIdsByQuery( myBugsQuery.id, testProject.name, function( err, ids ) {
if ( err ) {
console.log( err );
console.log( ids );
}
ids.should.be.instanceOf( Array );
ids.length.should.be.above( 0 );
// console.log(ids);
done();
} );
} );
it( 'returns a query by id', function( done ) {
should.exist( testProject );
should.exist( myBugsQuery );
client.getQuery( testProject.name, myBugsQuery.id, function( err, query ) {
if ( err ) {
console.log( err );
console.log( query );
}
should.not.exist( err );
should.exist( query );
//console.log(query);
query.should.have.property( 'id' );
query.should.have.property( 'name' );
query.should.have.property( 'url' );
done();
} );
} );
it( 'creates a query folder', function( done ) {
testFolder = null;
should.exist( testProject );
should.exist( myQueries );
client.createFolder( testProject.name, 'testFolder1', myQueries.id, function( err, folder ) {
should.not.exist( err );
should.exist( folder );
// console.log(folder);
folder.should.have.property( 'id' );
folder.should.have.property( 'url' );
testFolder = folder;
done();
} );
} );
it( 'creates a query', function( done ) {
testQuery = null;
should.exist( testProject );
should.exist( testFolder );
var wiql = 'Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = \'Bug\' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc';
client.createQuery( testProject.name, 'testQuery1', testFolder.id, wiql, function( err, query ) {
should.not.exist( err );
should.exist( query );
//console.log(query);
query.should.have.property( 'id' );
query.should.have.property( 'url' );
testQuery = query;
done();
} );
} );
it( 'updates a query by name', function( done ) {
should.exist( testProject );
should.exist( testFolder );
should.exist( testQuery );
var wiql = 'Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = \'Bug\' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] asc';
client.getQuery( testProject.name, testQuery.id, function( err, query ) {
should.exist( query );
// console.log(testFolder);
// console.log(query);
client.updateQuery( testProject.name, query.name, 'testQuery1-updated', testFolder.path, wiql, function( err, query2 ) {
should.not.exist( err );
should.exist( query2 );
// console.log(query);
query2.should.have.property( 'id' );
query2.should.have.property( 'url' );
testQuery = query2;
done();
} );
} );
} );
it( 'updates a query by id', function( done ) {
should.exist( testProject );
should.exist( testFolder );
should.exist( testQuery );
var wiql = 'Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = \'Bug\' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] asc';
client.getQuery( testProject.name, testQuery.id, function( err, query ) {
should.exist( query );
// console.log(testFolder);
// console.log(query);
client.updateQuery( testProject.name, query.id, 'testQuery1-updated2', null, wiql, function( err, query2 ) {
should.not.exist( err );
should.exist( query2 );
// console.log(query);
query2.should.have.property( 'id' );
query2.should.have.property( 'url' );
testQuery = query2;
done();
} );
} );
} );
it( 'deletes a query', function( done ) {
should.exist( testProject );
should.exist( testQuery );
client.deleteQuery( testProject.name, testQuery.id, function( err, query ) {
should.not.exist( err );
should.exist( query );
done();
} );
} );
it( 'deletes a query folder', function( done ) {
should.exist( testProject );
should.exist( testFolder );
client.deleteFolder( testProject.name, testFolder.id, function( err, folder ) {
should.not.exist( err );
should.exist( folder );
// console.log(folder);
done();
} );
} );
} );
describe( 'work items', function() {
var testItemIds = null;
var testItemIdArray = null;
var testItemId = null;
// ---------------------------------------
// Work Item Queries
// ---------------------------------------
it( 'returns a list of work items from wiql query', function( done ) {
var wiql = 'Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = \'Task\' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc';
client.getWorkItemIds( wiql, testProjectName, function( err, ids ) {
if ( err ) {
console.log( err );
console.log( ids );
}
should.not.exist( err );
should.exist( ids );
//console.log(ids);
ids.should.be.instanceOf( Array );
ids.length.should.be.above( 0 );
testItemIdArray = ids;
testItemIds = ids.join( ',' );
testItemId = ids[ 0 ];
done();
} );
} );
it( 'returns a list of work items by comma-separated id list', function( done ) {
client.getWorkItemsById( testItemIds, null, null, null, function( err, items ) {
if ( err ) {
console.log( err );
console.log( items );
}
should.not.exist( err );
should.exist( items );
items.length.should.be.above( 0 );
var item = items[ 0 ];
item.should.have.property( 'id' );
item.should.have.property( 'rev' );
item.should.have.property( 'url' );
should.exist( item.fields );
// console.log( item.fields );
item.fields.should.have.property( 'System.Title' );
item.fields.should.have.property( 'System.State' );
done();
} );
} );
it( 'returns a list of work items by array of ids', function( done ) {
client.getWorkItemsById( testItemIdArray, null, null, null, function( err, items ) {
if ( err ) {
console.log( err );
console.log( items );
}
should.not.exist( err );
should.exist( items );
items.length.should.equal( testItemIdArray.length );
var item = items[ 0 ];
item.should.have.property( 'id' );
item.should.have.property( 'rev' );
item.should.have.property( 'url' );
should.exist( item.fields );
// console.log( item.fields );
item.fields.should.have.property( 'System.Title' );
item.fields.should.have.property( 'System.State' );
done();
} );
} );
it( 'returns a list of work items by ids with expanded links', function( done ) {
client.getWorkItemsById( testItemIds, null, null, 'all', function( err, items ) {
if ( err ) {
console.log( err );
console.log( items );
}
should.not.exist( err );
should.exist( items );
// console.log(items);
items.length.should.be.above( 0 );
var item = items[ 0 ];
item.should.have.property( '_links' );
should.exist( item._links );
item._links.should.have.property( 'self' );
testItemId = item.id;
done();
} );
} );
it( 'returns a work item by id', function( done ) {
should.exist( testItemId );
client.getWorkItem( testItemId, 'all', function( err, item ) {
//client.getWorkItem(7, 'all', function(err, item) {
if ( err ) {
console.log( err );
console.log( item );
}
should.not.exist( err );
should.exist( item );
// console.log(item);
item.should.have.property( 'id' );
item.should.have.property( 'rev' );
item.should.have.property( 'url' );
should.exist( item.fields );
// console.log( item.fields );
item.fields.should.have.property( 'System.Id' );
item.fields.should.have.property( 'System.Title' );
item.fields.should.have.property( 'System.State' );
done();
} );
} );
it( 'returns work item updates', function( done ) {
client.getWorkItemUpdates( testItemId, function( err, updates ) {
if ( err ) {
console.log( err );
console.log( updates );
}
should.not.exist( err );
should.exist( updates );
//console.log(updates);
updates.length.should.be.above( 0 );
var update = updates[ updates.length - 1 ];
// console.log(update);
update.should.have.property( 'id' );
update.should.have.property( 'rev' );
should.exist( update.fields );
done();
} );
} );
it( 'returns a page of work item updates', function( done ) {
client.getWorkItemUpdates( testItemId, 2, 0, function( err, updates ) {
if ( err ) {
console.log( err );
console.log( updates );
}
should.not.exist( err );
should.exist( updates );
//console.log(updates);
updates.length.should.equal( 2 );
updates[ updates.length - 1 ].rev.should.be.above( 1 );
done();
} );
} );
it( 'returns a work item update by revision number', function( done ) {
client.getWorkItemUpdate( testItemId, 1, function( err, update ) {
if ( err ) {
console.log( err );
console.log( update );
}
should.not.exist( err );
should.exist( update );
//console.log(update);
update.should.have.property( 'id' );
update.should.have.property( 'rev' );
update.should.have.property( 'url' );
should.exist( update.fields );
done();
} );
} );
it( 'returns a work item by revision number', function( done ) {
client.getWorkItemRevision( testItemId, 1, function( err, item ) {
if ( err ) {
console.log( err );
console.log( item );
}
should.not.exist( err );
should.exist( item );
//console.log(item);
item.should.have.property( 'id' );
item.should.have.property( 'rev' );
item.should.have.property( 'url' );
should.exist( item.fields );
// console.log( item.fields );
item.fields.should.have.property( 'System.Title' );
item.fields.should.have.property( 'System.State' );
done();
} );
} );
} );
// Accounts and Profiles Tests are not testable since they required
// OAuth, thus requiring human intervention to get a token with
// an authorization
describe.skip( 'Accounts', function() {
it( 'should return a list of accounts', function( done ) {
clientOAuth.getAccounts( memberId, function( err, accounts ) {
// console.log(err);
should.not.exist( err );
should.exist( accounts );
// console.log(accounts);
accounts.should.be.instanceOf( Array );
accounts.length.should.be.above( 0 );
var account = accounts[ 0 ];
account.should.have.property( 'accountId' );
account.should.have.property( 'accountUri' );
account.should.have.property( 'accountName' );
account.should.have.property( 'organizationName' );
done();
} );
} );
} );
describe( 'team room tests', function() {
var testTeamRoom = null;
var testTeamRoomId = null;
it( 'returns a list of team rooms', function( done ) {
client.getRooms( function( err, rooms ) {
should.not.exist( err );
should.exist( rooms );
// console.log( rooms );
rooms.length.should.be.above( 0 );
var room = _.find( rooms, function( t ) {
return t.hasReadWritePermissions;
} );
should.exist( room );
// console.log(testTeamRoom);
room.should.have.property( 'id' );
room.should.have.property( 'name' );
room.should.have.property( 'description' );
room.should.have.property( 'lastActivity' );
room.should.have.property( 'createdBy' );
room.should.have.property( 'createdDate' );
room.should.have.property( 'hasAdminPermissions' );
room.should.have.property( 'hasReadWritePermissions' );
testTeamRoomId = room.id;
done();
} );
} );
it( 'returns a room by id', function( done ) {
if ( testTeamRoomId ) {
client.getRoom( testTeamRoomId, function( err, room ) {
should.not.exist( err );
should.exist( room );
// console.log( room );
room.should.have.property( 'id' );
room.should.have.property( 'name' );
room.should.have.property( 'description' );
room.should.have.property( 'lastActivity' );
room.should.have.property( 'createdBy' );
room.should.have.property( 'createdDate' );
room.should.have.property( 'hasAdminPermissions' );
room.should.have.property( 'hasReadWritePermissions' );
done();
} );
} else {
console.log( 'Warning: no test team room' );
done();
}
} );
it( 'creates a room', function( done ) {
var randomName = 'test-room-' + ( Math.random() + 1 ).toString( 36 ).substring( 7 );
client.createRoom( randomName, 'a description', function( err, room ) {
should.not.exist( err );
should.exist( room );
// console.log( room );
testTeamRoom = room;
room.should.have.property( 'id' );
room.should.have.property( 'name' );
room.should.have.property( 'description' );
room.should.have.property( 'lastActivity' );
room.should.have.property( 'createdBy' );
room.should.have.property( 'createdDate' );
room.should.have.property( 'hasAdminPermissions' );
room.should.have.property( 'hasReadWritePermissions' );
done();
} );
} );
it ( 'updates a room', function( done ) {
if ( testTeamRoom ) {
var name = testTeamRoom.name + '-updated';
var description = 'updated description';
client.updateRoom( testTeamRoom.id, name, description, function( err, room ) {
should.not.exist( err );
should.exist( room );
// console.log( room );
room.name.should.equal( name );
room.description.should.equal( description );
done();
} );
} else {
console.log( 'Warning: no test team room' );
done();
}
} );
it( 'deletes a room', function( done ) {
if ( testTeamRoom ) {
client.deleteRoom( testTeamRoom.id, function( err, res ) {
should.not.exist( err );
// console.log( res );
done();
} );
} else {
console.log( 'Warning: no test team room' );
done();
}
} );
} );
describe( 'version control tests', function() {
before( function() {
client.setVersion( '1.0' );
} );
// ---------------------------------------
// Version Control
// ---------------------------------------
it( 'returns root branches', function( done ) {
client.getRootBranches( true, true, function( err, branches ) {
if ( err ) {
console.log( err, branches );
}
should.not.exist( err );
should.exist( branches );
// console.log( branches );
done();
} );
} );
it.skip( 'returns a branch', function( done ) {
var path = '$/TestProject';
client.getBranch( path, true, true, true, function( err, branch ) {
if ( err ) {
console.log( err, branch );
}
should.not.exist( err );
should.exist( branch );
// console.log(branch);
done();
} );
} );
it( 'returns shelvesets', function( done ) {
client.getShelveSets( function( err, shelvesets ) {
if ( err ) {
console.log( err, shelvesets );
}
should.not.exist( err );
should.exist( shelvesets );
// console.log(shelvesets);
done();
} );
} );
var testCommitId = null;
var testChangeSet = null;
it( 'returns changesets', function( done ) {
client.getChangeSets( function( err, changesets ) {
if ( err ) {
console.log( err, changesets );
}
should.not.exist( err );
should.exist( changesets );
// console.log(changesets);
changesets.should.be.instanceOf( Array );
changesets.length.should.be.above( 0 );
var changeset = changesets[ 0 ];
changeset.should.have.property( 'changesetId' );
changeset.should.have.property( 'url' );
changeset.should.have.property( 'createdDate' );
changeset.should.have.property( 'comment' );
changeset.author.should.be.instanceOf( Object );
changeset.checkedInBy.should.be.instanceOf( Object );
testCommitId = changeset.changesetId;
done();
} );
} );
it( 'returns a changeset by id', function( done ) {
if ( testCommitId ) {
client.getChangeSet( testCommitId, function( err, changeset ) {
if ( err ) {
console.log( err, changeset );
}
should.not.exist( err );
should.exist( changeset );
// console.log(changeset);
changeset.should.have.property( 'changesetId' );
changeset.should.have.property( 'url' );
changeset.should.have.property( 'createdDate' );
changeset.should.have.property( 'comment' );
changeset.author.should.be.instanceOf( Object );
changeset.checkedInBy.should.be.instanceOf( Object );
testChangeSet = changeset;
done();
} );
} else {
console.log( 'Warning: no test change set' );
done();
}
} );
it( 'returns changsets from range of IDs', function( done ) {
if ( testChangeSet ) {
var toId = testChangeSet.changesetId;
var fromId = toId - 2;
var expectedCount = 3;
if ( fromId < 1 ) {
fromId = 1;
expectedCount = toId - fromId + 1;
}
var queryOptions = {
fromId: fromId,
toId: testChangeSet.changesetId
};
client.getChangeSets( queryOptions, function( err, changesets ) {
if ( err ) {
console.log( err, changesets );
}
should.not.exist( err );
should.exist( changesets );
// console.log(changesets);
changesets.should.be.instanceOf( Array );
changesets.length.should.equal( expectedCount );
var changeset = changesets[ 0 ];
changeset.should.have.property( 'changesetId' );
changeset.should.have.property( 'url' );
changeset.should.have.property( 'createdDate' );
changeset.should.have.property( 'comment' );
changeset.author.should.be.instanceOf( Object );
changeset.checkedInBy.should.be.instanceOf( Object );
done();
} );
} else {
console.log( 'Warning: no test change set' );
done();
}
} );
it( 'returns a changeset by id with details', function( done ) {
if ( testCommitId ) {
var queryOptions = {
includeDetails: true,
includeWorkItems: false,
maxChangeCount: 0,
maxCommentLength: 1000
};
client.getChangeSet( testCommitId, queryOptions, function( err, changeset ) {
if ( err ) {
console.log( err, changeset );
}
should.not.exist( err );
should.exist( changeset );
// console.log(changeset);
changeset.checkinNotes.should.be.instanceOf( Array );
changeset.policyOverride.should.be.instanceOf( Object );
done();
} );
} else {
console.log( 'Warning: no test change set' );
done();
}
} );
it( 'returns a changeset by id with work items', function( done ) {
if ( testCommitId ) {
var queryOptions = {
includeDetails: false,
includeWorkItems: true,
maxChangeCount: 0,
maxCommentLength: 1000
};
client.getChangeSet( testCommitId, queryOptions, function( err, changeset ) {
if ( err ) {
console.log( err, changeset );
}
should.not.exist( err );
should.exist( changeset );
// console.log(changeset);
changeset.workItems.should.be.instanceOf( Array );
done();
} );
} else {
console.log( 'Warning: no test change set' );
done();
}
} );
it.skip( 'returns latest changeset changes', function( done ) {
client.getChangeSetChanges( function( err, changes ) {
if ( err ) {
console.log( err, changes );
}
should.not.exist( err );
should.exist( changes );
// console.log(changes);
changes.should.be.instanceOf( Array );
done();
} );
} );
it( 'returns changes for a changeset by id', function( done ) {
if ( testCommitId ) {
var queryOptions = {
id: testCommitId
};
client.getChangeSetChanges( queryOptions, function( err, changes ) {
if ( err ) {
console.log( err, changes );
}
should.not.exist( err );
should.exist( changes );
// console.log(changes);
changes.should.be.instanceOf( Array );
done();
} );
} else {
console.log( 'Warning: no test change set' );
done();
}
} );
it.skip( 'returns latest changeset work items', function( done ) {
client.getChangeSetWorkItems( function( err, workitems ) {
if ( err ) {
console.log( err, workitems );
}
should.not.exist( err );
should.exist( workitems );
// console.log(workitems);
workitems.should.be.instanceOf( Array );
done();
} );
} );
it( 'returns work items for a changeset by id', function( done ) {
if ( testCommitId ) {
var queryOptions = {
id: testCommitId
};
client.getChangeSetWorkItems( queryOptions, function( err, workitems ) {
if ( err ) {
console.log( err, workitems );
}
should.not.exist( err );
should.exist( workitems );
// console.log(workitems);
workitems.should.be.instanceOf( Array );
done();
} );
} else {
console.log( 'Warning: no test change set' );
done();
}
} );
it( 'gets a list of labels', function( done ) {
client.getLabels( function( err, labels ) {
if ( err ) {
console.log( err, labels );
}
should.not.exist( err );
should.exist( labels );
// console.log(labels);
labels.should.be.instanceOf( Array );
done();
} );
} );
} );
describe.skip ( 'git repository tests', function() {
// ---------------------------------------
// Git Repositories
// ---------------------------------------
var testRepoName = null;
var testRepository = null;
var testGitProject = null;
var testCommit = null;
var testProject = null;
before( function( done ) {
testRepoName = 'testRepo-' + ( Math.random() + 1 ).toString( 36 ).substring( 7 );
client.getProjects( function( err, projects ) {
testProject = _.find( projects, function( p ) {
return p.name === testProjectName;
} );
// Find a project that uses git
if ( projects && projects.length > 0 ) {
async.each( projects, function( project, callback ) {
client.getProject( project.id, true, function( err, proj ) {
if ( proj.capabilities.versioncontrol.sourceControlType === 'Git' ) {
testGitProject = proj;
callback( 'Found' );
} else {
callback();
}
} );
}, function( err ) {
if ( err !== 'Found' ) {
console.log( err );
}
done();
} );
}
} );
} );
it( 'creates a git repository', function( done ) {
if ( testGitProject ) {
client.createRepository( testGitProject.id, testRepoName, function( err, repository ) {
should.not.exist( err );
should.exist( repository );
testRepository = repository;
done();
} );
} else {
console.log( 'Warning: missing test project' );
done();
}
} );
it( 'returns a list of repositories', function( done ) {
client.getRepositories( function( err, repositories ) {
should.not.exist( err );
should.exist( repositories );
// console.log(repositories);
if ( repositories.length > 0 ) {
var repository = repositories[ 0 ];
repository.should.have.property( 'id' );
repository.should.have.property( 'name' );
repository.should.have.property( 'remoteUrl' );
repository.project.should.be.instanceOf( Object );
}
done();
} );
} );
it( 'returns a list of repositories by project', function( done ) {
if ( testGitProject ) {
client.getRepositories( testGitProject.id, function( err, repositories ) {
should.not.exist( err );
should.exist( repositories );
repositories.length.should.be.above( 0 );
done();
} );
} else {
console.log( 'Warning: missing test project' );
done();
}
} );
it( 'returns a repository by id', function( done ) {
if ( testRepository ) {
client.getRepository( testRepository.id, function( err, repository ) {
should.not.exist( err );
should.exist( repository );
repository.should.have.property( 'id' );
repository.should.have.property( 'name' );
repository.should.have.property( 'remoteUrl' );
repository.project.should.be.instanceOf( Object );
done();
} );
} else {
console.log( 'Warning: missing test repository' );
done();
}
} );
it( 'returns a repository by name', function( done ) {
if ( testRepository ) {
client.getRepository( testRepository.name, testProject.id, function( err, repository ) {
should.not.exist( err );
should.exist( repository );
repository.should.have.property( 'id' );
repository.should.have.property( 'name' );
repository.should.have.property( 'remoteUrl' );
repository.project.should.be.instanceOf( Object );
done();
} );
} else {
console.log( 'Warning: missing test repository' );
done();
}
} );
it( 'renames a repository', function( done ) {
if ( testRepository ) {
client.renameRepository( testRepository.id, testRepository.name + '-update', function( err, repository ) {
should.not.exist( err );
should.exist( repository );
repository.should.have.property( 'id' );
repository.should.have.property( 'name' );
repository.should.have.property( 'remoteUrl' );
repository.project.should.be.instanceOf( Object );
repository.name.should.equal( testRepository.name + '-update' );
done();
} );
} else {
console.log( 'Warning: missing test repository' );
done();
}
} );
it( 'deletes a repository', function( done ) {
if ( testRepository ) {
client.deleteRepository( testRepository.id, function( err, repository ) {
should.not.exist( err );
should.exist( repository );
done();
} );
} else {
console.log( 'Warning: missing test repository' );
done();
}
} );
it( 'gets a list of commits', function( done ) {
if ( testGitProject ) {
client.getRepositories( testGitProject.id, function( err, repositories ) {
should.not.exist( err );
should.exist( repositories );
if ( repositories.length > 0 ) {
// console.log( repositories );
var repository = repositories[ 0 ];
testRepository = repository;
console.log( repository );
client.getCommits( repository.id, function( err, commits ) {
should.not.exist( err );
should.exist( commits );
commits.should.be.instanceOf( Array );
console.log( commits );
if ( commits.length > 0 ) {
var commit = commits[ 0 ];
commit.should.have.property( 'commitId' );
commit.should.have.property( 'comment' );
commit.should.have.property( 'url' );
commit.author.should.be.instanceOf( Object );
commit.committer.should.be.instanceOf( Object );
commit.changeCounts.should.be.instanceOf( Object );
testCommit = commit;
}
// console.log(commits);
done();
} );
} else {
conosole.log( 'Warning: no repositories in project', testProject );
done();
}
} );
} else {
console.log( 'Warning: missing test project' );
done();
}
} );
it( 'gets a list of commits by author', function( done ) {
if ( testRepository && testCommit ) {
client.getCommits( testRepository.id, null, null, testCommit.author.name, function( err, commits ) {
should.not.exist( err );
should.exist( commits );
commits.should.be.instanceOf( Array );
commits.length.should.be.above( 0 );
done();
} );
} else {
console.log( 'Warning: missing test repository and commit' );
done();
}
} );
it( 'gets a commit by id', function( done ) {
if ( testRepository && testCommit ) {
client.getCommit( testRepository.id, testCommit.commitId, function( err, commit ) {
should.not.exist( err );
should.exist( commit );
commit.parents.should.be.instanceOf( Array );
commit.should.have.property( 'treeId' );
commit.push.should.be.instanceOf( Object );
commit.should.have.property( 'commitId' );
commit.should.have.property( 'comment' );
commit.should.have.property( 'url' );
commit.author.should.be.instanceOf( Object );
commit.committer.should.be.instanceOf( Object );
should.not.exist( commit.changes );
// console.log(commit);
done();
} );
} else {
console.log( 'Warning: missing test repository and commit' );
done();
}
} );
it( 'gets a commit by id with changed items', function( done ) {
if ( testRepository && testCommit ) {
client.getCommit( testRepository.id, testCommit.commitId, 10, function( err, commit ) {
should.not.exist( err );
should.exist( commit );
// console.log(commit);
commit.changes.should.be.instanceOf( Array );
commit.changeCounts.should.be.instanceOf( Object );
done();
} );
} else {
console.log( 'Warning: missing test repository and commit' );
done();
}
} );
it( 'gets a list of commit diffs', function( done ) {
if ( testRepository ) {
client.getDiffs( testRepository.id, null, 'master', null, 'develop', function( err, diffs ) {
should.not.exist( err );
should.exist( diffs );
diffs.should.have.property( 'allChangesIncluded' );
diffs.changes.should.be.instanceOf( Array );
diffs.should.have.property( 'commonCommit' );
diffs.should.have.property( 'aheadCount' );
diffs.should.have.property( 'behindCount' );
// console.log(diffs);
done();
} );
} else {
console.log( 'Warning: missing test repository' );
done();
}
} );
it( 'gets a list of pushes', function( done ) {
if ( testRepository ) {
client.getPushes( testRepository.id, function( err, pushes ) {
should.not.exist( err );
should.exist( pushes );
pushes.should.be.instanceOf( Array );
pushes.length.should.be.above( 0 );
// console.log(pushes);
done();
} );
} else {
console.log( 'Warning: missing test repository' );
done();
}
} );
it( 'gets stats for repository', function( done ) {
if ( testRepository ) {
client.getStats( testRepository.id, function( err, stats ) {
should.not.exist( err );
should.exist( stats );
stats.should.be.instanceOf( Array );
stats.length.should.be.above( 0 );
// console.log(stats);
done();
} );
} else {
console.log( 'Warning: missing test repository' );
done();
}
} );
it( 'gets refs for repository', function( done ) {
if ( testRepository ) {
client.getRefs( testRepository.id, function( err, refs ) {
should.not.exist( err );
should.exist( refs );
refs.should.be.instanceOf( Array );
refs.length.should.be.above( 0 );
// console.log(refs);
var ref = refs[ 0 ];
ref.should.have.property( 'name' );
ref.should.have.property( 'objectId' );
ref.should.have.property( 'url' );
done();
} );
} else {
console.log( 'Warning: missing test repository' );
done();
}
} );
} );
describe( 'Service Hook tests', function() {
// ---------------------------------------
// Service Hooks
// ---------------------------------------
var testProject = null;
var testSubscription = null;
before( function( done ) {
client.getProjects( function( err, projects ) {
// console.log(err);
// console.log(projects);
testProject = _.find( projects, function( p ) {
return p.name === testProjectName;
} );
done();
} );
} );
it( 'should get a list of publishers', function( done ) {
client.getConsumers( function( err, publishers ) {
if ( err ) console.log( err, publishers );
should.not.exist( err );
should.exist( publishers );
// console.log(publishers);
publishers.should.be.instanceOf( Array );
var publisher = _.find( publishers, function( c ) {
return c.id === 'webHooks';
} );
should.exist( publisher );
// console.log(publisher);
// console.log(publisher.actions[0].inputDescriptors);
publisher.should.have.property( 'id' );
publisher.should.have.property( 'url' );
publisher.should.have.property( 'name' );
publisher.should.have.property( 'description' );
publisher.should.have.property( 'informationUrl' );
publisher.should.have.property( 'authenticationType' );
publisher.inputDescriptors.should.be.instanceOf( Array );
publisher.actions.should.be.instanceOf( Array );
done();
} );
} );
it( 'should get a list of consumers', function( done ) {
client.getConsumers( function( err, consumers ) {
if ( err ) console.log( err, consumers );
should.not.exist( err );
should.exist( consumers );
// console.log(consumers);
consumers.should.be.instanceOf( Array );
var zendesk = _.find( consumers, function( c ) {
return c.id === 'zendesk';
} );
should.exist( zendesk );
// console.log(zendesk);
zendesk.should.have.property( 'id' );
zendesk.should.have.property( 'url' );
zendesk.should.have.property( 'name' );
zendesk.should.have.property( 'description' );
zendesk.should.have.property( 'informationUrl' );
zendesk.should.have.property( 'authenticationType' );
zendesk.inputDescriptors.should.be.instanceOf( Array );
zendesk.actions.should.be.instanceOf( Array );
done();
} );
} );
it( 'should get a consumer by id', function( done ) {
client.getConsumer( 'zapier', function( err, consumer ) {
if ( err ) console.log( err, consumer );
should.not.exist( err );
should.exist( consumer );
// console.log(consumer);
consumer.should.have.property( 'id' );
consumer.should.have.property( 'url' );
consumer.should.have.property( 'name' );
consumer.should.have.property( 'description' );
consumer.should.have.property( 'informationUrl' );
consumer.should.have.property( 'authenticationType' );
consumer.inputDescriptors.should.be.instanceOf( Array );
consumer.actions.should.be.instanceOf( Array );
done();
} );
} );
it( 'should get a list of consumer actions by id', function( done ) {
client.getConsumerActions( 'zapier', function( err, actions ) {
if ( err ) console.log( err, actions );
should.not.exist( err );
should.exist( actions );
// console.log(actions);
actions.should.be.instanceOf( Array );
actions.length.should.be.above( 0 );
var action = actions[ 0 ];
// console.log(action);
action.should.have.property( 'id' );
action.should.have.property( 'consumerId' );
action.should.have.property( 'url' );
action.should.have.property( 'name' );
action.should.have.property( 'description' );
action.inputDescriptors.should.be.instanceOf( Array );
action.supportedEventTypes.should.be.instanceOf( Array );
done();
} );
} );
it( 'should get a list of consumer action by id', function( done ) {
client.getConsumerAction( 'zapier', 'sendNotification', function( err, action ) {
if ( err ) console.log( err, action );
should.not.exist( err );
should.exist( action );
// console.log(action);
action.should.have.property( 'id' );
action.should.have.property( 'consumerId' );
action.should.have.property( 'url' );
action.should.have.property( 'name' );
action.should.have.property( 'description' );
action.inputDescriptors.should.be.instanceOf( Array );
action.supportedEventTypes.should.be.instanceOf( Array );
done();
} );
} );
it( 'should create a subscription', function( done ) {
should.exist( testProject );
var subscription = {
eventType: 'workitem.created',
publisherId: 'tfs',
resourceVersion: '1.0',
eventDescription: 'Any work item',
consumerId: 'webHooks',
consumerActionId: 'httpRequest',
actionDescription: '...',
consumerInputs: {
url: 'https://localhost:1234/test/test-consumer/' + testProject.id
},
publisherInputs: {
projectId: testProject.id
}
};
client.createSubscription( subscription, function( err, sub ) {
if ( err ) console.log( err, sub );
should.not.exist( err );
should.exist( sub );
// console.log( sub );
sub.should.have.property( 'id' );
sub.should.have.property( 'url' );
sub.should.have.property( 'eventType' );
testSubscription = sub;
done();
} );
} );
it( 'should get a list of subscriptions', function( done ) {
client.getSubscriptions( function( err, subscriptions ) {
if ( err ) console.log( err, subscriptions );
should.not.exist( err );
should.exist( subscriptions );
// console.log( subscriptions );
subscriptions.should.be.instanceOf( Array );
done();
} );
} );
it( 'deletes a subscription', function( done ) {
should.exist( testSubscription );
client.deleteSubscription( testSubscription.id, function( err, res ) {
if ( err ) console.log( err, res );
should.not.exist( err );
should.exist( res );
done();
} );
} );
it.skip( 'should get a list of subscriptions by query', function( done ) {
// Documentation incomplete
var queryOptions = {
publisherId: '',
eventType: '',
consumerId: '',
consumerActionId: '',
publisherInputFilters: [ {
conditions: [ {
inputId: '',
operator: 'equals',
inputValue: ''
} ]
} ]
};
client.querySubscriptions( queryOptions, function( err, subscriptions ) {
if ( err ) console.log( err, subscriptions );
should.not.exist( err );
should.exist( subscriptions );
// console.log(subscriptions);
subscriptions.should.be.instanceOf( Array );
done();
} );
} );
} );
describe.skip( 'Build tests', function() {
it( 'should return a list of build definitions', function( done ) {
client.getBuildDefinitions( function( err, builds ) {
should.not.exist( err );
should.exist( builds );
builds.length.should.be.above( 0 );
var build = builds[ 0 ];
build.should.have.property( 'id' );
build.should.have.property( 'name' );
build.should.have.property( 'url' );
done();
} );
} );
it( 'should queue a build', function( done ) {
var buildRequest = { definition: { id: 1 }, reason: 'Manual', priority: 'Normal' };
// console.log(buildRequest);
client.queueBuild( buildRequest, function( err, buildResponse ) {
should.not.exist( err );
should.exist( buildResponse );
buildResponse.length.should.be.above( 0 );
buildResponse.should.have.property( 'status' );
done();
} );
} );
} );
} );
describe( 'VSO Service Account Tests', function() {
this.timeout( 20000 );
it( 'has a WRAP valid client', function() {
var client = Client.createWrapClient( url, collection, "dummy wrap token", getOptions() );
should.exist( client );
client.should.have.property( 'url' );
client.should.have.property( '_authType' );
client._authType.should.equal( 'Wrap' );
should.exist( client.client );
} );
describe( 'Request WRAP Token Tests', function() {
it( 'should return a WRAP valid token', function( done ) {
Client.getWrapToken( url, serviceAccountUser, serviceAccountPassword, function( err, data, resp ) {
should.not.exist( err );
data.should.have.property( 'wrap_access_token' );
data.should.have.property( 'wrap_access_token_expires_in' );
done();
} );
} );
it( 'should return an error with 401', function( done ) {
Client.getWrapToken( url, "dummy user", "dummy password", function( err, data, resp ) {
should.exist( err );
err.statusCode.should.equal( 401 );
done();
} );
} );
} );
describe( 'API calls with WRAP Token Tests', function() {
var client;
before( function( done ) {
Client.getWrapToken( url, serviceAccountUser, serviceAccountPassword, function( err, data, resp ) {
if ( err ) {
console.log( "Can't get WRAP token" );
throw err;
}
client = Client.createWrapClient( url, collection, data.wrap_access_token, getOptions() );
done();
} );
} );
it( 'should return a list of projects', function( done ) {
client.getProjects( function( err, projects ) {
should.not.exist( err );
should.exist( projects );
// console.log(projects);
projects.length.should.be.above( 0 );
var project = _.find( projects, function( p ) {
return p.name === testProjectName;
} );
project.should.have.property( 'id' );
project.should.have.property( 'name' );
project.should.have.property( 'url' );
should.exist( project.collection );
should.exist( project.defaultTeam );
done();
} );
} );
} );
} );
|
/*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Disable distortion provided by the boilerplate because we are doing
// vertex-based distortion.
WebVRConfig = window.WebVRConfig || {}
WebVRConfig.PREVENT_DISTORTION = true;
// Initialize the loading indicator as quickly as possible to give the user
// immediate feedback.
var LoadingIndicator = require('./loading-indicator');
var loadIndicator = new LoadingIndicator();
// Include relevant polyfills.
require('../node_modules/webvr-polyfill/build/webvr-polyfill');
var ES6Promise = require('../node_modules/es6-promise/dist/es6-promise.min');
// Polyfill ES6 promises for IE.
ES6Promise.polyfill();
var PhotosphereRenderer = require('./photosphere-renderer');
var SceneLoader = require('./scene-loader');
var Stats = require('../node_modules/stats-js/build/stats.min');
var Util = require('./util');
// Include the DeviceMotionReceiver for the iOS cross domain iframe workaround.
// This is a workaround for https://bugs.webkit.org/show_bug.cgi?id=150072.
var DeviceMotionReceiver = require('./device-motion-receiver');
var dmr = new DeviceMotionReceiver();
window.addEventListener('load', init);
var stats = new Stats();
var loader = new SceneLoader();
loader.on('error', onSceneError);
loader.on('load', onSceneLoad);
var renderer = new PhotosphereRenderer();
renderer.on('error', onRenderError);
var videoElement = null;
// TODO: Make this not global.
// Currently global in order to allow callbacks.
var loadedScene = null;
function init() {
if (!Util.isWebGLEnabled()) {
showError('WebGL not supported.');
return;
}
// Load the scene.
loader.loadScene();
if (Util.getQueryParameter('debug')) {
showStats();
}
}
function loadImage(src, params) {
renderer.on('load', onRenderLoad);
renderer.setPhotosphere(src, params);
}
function onSceneLoad(scene) {
if (!scene || !scene.isComplete()) {
showError('Scene failed to load');
return;
}
loadedScene = scene;
var params = {
isStereo: scene.isStereo,
}
renderer.setDefaultLookDirection(scene.yaw || 0);
if (scene.preview) {
var onPreviewLoad = function() {
loadIndicator.hide();
renderer.removeListener('load', onPreviewLoad);
renderer.setPhotosphere(scene.image, params);
}
renderer.removeListener('load', onRenderLoad);
renderer.on('load', onPreviewLoad);
renderer.setPhotosphere(scene.preview, params);
} else if (scene.video) {
if (Util.isIOS() || Util.isIE11()) {
// On iOS and IE 11, if an 'image' param is provided, load it instead of
// showing an error.
//
// TODO(smus): Once video textures are supported, remove this fallback.
if (scene.image) {
loadImage(scene.image, params);
} else {
showError('Video is not supported on this platform (iOS or IE11).');
}
} else {
// Load the video element.
videoElement = document.createElement('video');
videoElement.src = scene.video;
videoElement.loop = true;
videoElement.setAttribute('crossorigin', 'anonymous');
videoElement.addEventListener('canplaythrough', onVideoLoad);
videoElement.addEventListener('error', onVideoError);
}
} else if (scene.image) {
// Otherwise, just render the photosphere.
loadImage(scene.image, params);
}
console.log('Loaded scene', scene);
}
function onVideoLoad() {
// Render the stereo video.
var params = {
isStereo: loadedScene.isStereo,
}
renderer.set360Video(videoElement, params);
// On mobile, tell the user they need to tap to start. Otherwise, autoplay.
if (!Util.isMobile()) {
// Hide loading indicator.
loadIndicator.hide();
// Autoplay the video on desktop.
videoElement.play();
} else {
// Tell user to tap to start.
showError('Tap to start video', 'Play');
document.body.addEventListener('touchend', onVideoTap);
}
// Prevent onVideoLoad from firing multiple times.
videoElement.removeEventListener('canplaythrough', onVideoLoad);
}
function onVideoTap() {
hideError();
videoElement.play();
// Prevent multiple play() calls on the video element.
document.body.removeEventListener('touchend', onVideoTap);
}
function onRenderLoad() {
// Hide loading indicator.
loadIndicator.hide();
}
function onSceneError(message) {
showError('Loader: ' + message);
}
function onRenderError(message) {
showError('Render: ' + message);
}
function onVideoError(e) {
showError('Video load error');
console.log(e);
}
function showError(message, opt_title) {
// Hide loading indicator.
loadIndicator.hide();
var error = document.querySelector('#error');
error.classList.add('visible');
error.querySelector('.message').innerHTML = message;
var title = (opt_title !== undefined ? opt_title : 'Error');
error.querySelector('.title').innerHTML = title;
}
function hideError() {
var error = document.querySelector('#error');
error.classList.remove('visible');
}
function showStats() {
stats.setMode(0); // 0: fps, 1: ms
// Align bottom-left.
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.bottom = '0px';
document.body.appendChild(stats.domElement);
}
function loop(time) {
stats.begin();
renderer.render(time);
stats.end();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
|
describe('the $type operator with a number as parameter:', function() {
var ArrayLike = function ArrayLike() {
this.length = 0;
}
var C = [
{ sample: 1 },
{ sample: Math.PI },
{ sample: "string"},
{ sample: {} },
{ sample: [] },
{ sample: true },
{ sample: new Date(1990, 10, 5) },
{ sample: null },
{ sample: /regexp/ },
{ sample: true },
{ sample: function () { return 'this is a function'; }},
{ sample: 4294967296 } // 2^32
];
beforeEach(function () {
this.addMatchers({
sameCollection: function(expected) {
var c1 = [].slice.apply(this.actual);
var c2 = [].slice.apply(expected);
return jasmine.getEnv().equals_(c1, c2);
},
sameCollectionByItems: function() {
var c1 = [].slice.apply(this.actual);
var c2 = [].slice.apply(arguments);
return jasmine.getEnv().equals_(c1, c2);
}
});
ask.mongify(C);
});
it('accepts the number 1, double ',
function() {
expect(
C.find({ sample: { $type: 1 } })
)
.sameCollectionByItems(
C[0],
C[1],
C[11]
);
}
);
it('accepts the number 2, string ',
function() {
expect(
C.find({ sample: { $type: 2 } })
)
.sameCollectionByItems(
C[2]
);
}
);
it('accepts the number 3, object ',
function() {
expect(
C.find({ sample: { $type: 3 } })
)
.sameCollectionByItems(
C[3]
);
}
);
it('accepts the number 4, array ',
function() {
expect(
C.find({ sample: { $type: 4 } })
)
.sameCollectionByItems(
C[4]
);
}
);
it('accepts the number 8, boolean ',
function() {
expect(
C.find({ sample: { $type: 8 } })
)
.sameCollectionByItems(
C[5],
C[9]
);
}
);
it('accepts the number 9, date ',
function() {
expect(
C.find({ sample: { $type: 9 } })
)
.sameCollectionByItems(
C[6]
);
}
);
it('accepts the number 10, null ',
function() {
expect(
C.find({ sample: { $type: 10 } })
)
.sameCollectionByItems(
C[7]
);
}
);
it('accepts the number 11, regular expression ',
function() {
expect(
C.find({ sample: { $type: 11 } })
)
.sameCollectionByItems(
C[8]
);
}
);
it('accepts the number 13, JavaScript code',
function() {
expect(
C.find({ sample: { $type: 13 } })
)
.sameCollectionByItems(
C[10]
);
}
);
it('accepts the number 15, JavaScript code with scope ',
function() {
expect(
C.find({ sample: { $type: 15 } })
)
.sameCollectionByItems(
C[10]
);
}
);
it('accepts the number 16, 32-bit integer ',
function() {
expect(
C.find({ sample: { $type: 16 } })
)
.sameCollectionByItems(
C[0]
);
}
);
it('accepts the number 18, 64-bit (really 52-bit) integer ',
function() {
expect(
C.find({ sample: { $type: 18 } })
)
.sameCollectionByItems(
C[0],
C[11]
);
}
);
it('does not support 7, object id',
function() {
function f() { C.find({ sample: { $type: 7 } }); }
expect(f).toThrow();
}
);
});
|
/*! X-editable - v1.5.3
* In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery
* http://github.com/vitalets/x-editable
* Copyright (c) 2015 - 2016 Vitaliy Potapov; Licensed MIT */
/**
Form with single input element, two buttons and two states: normal/loading.
Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown.
Editableform is linked with one of input types, e.g. 'text', 'select' etc.
@class editableform
@uses text
@uses textarea
**/
// window.jQuery = $;
(function ($) {
"use strict";
var EditableForm = function (div, options) {
this.options = $.extend({}, $.fn.editableform.defaults, options);
this.$div = $(div); //div, containing form. Not form tag. Not editable-element.
if(!this.options.scope) {
this.options.scope = this;
}
//nothing shown after init
};
EditableForm.prototype = {
constructor: EditableForm,
initInput: function() { //called once
//take input from options (as it is created in editable-element)
this.input = this.options.input;
//set initial value
//todo: may be add check: typeof str === 'string' ?
this.value = this.input.str2value(this.options.value);
//prerender: get input.$input
this.input.prerender();
},
initTemplate: function() {
this.$form = $($.fn.editableform.template);
},
initButtons: function() {
var $btn = this.$form.find('.editable-buttons');
$btn.append($.fn.editableform.buttons);
if(this.options.showbuttons === 'bottom') {
$btn.addClass('editable-buttons-bottom');
}
},
/**
Renders editableform
@method render
**/
render: function() {
//init loader
this.$loading = $($.fn.editableform.loading);
this.$div.empty().append(this.$loading);
//init form template and buttons
this.initTemplate();
if(this.options.showbuttons) {
this.initButtons();
} else {
this.$form.find('.editable-buttons').remove();
}
//show loading state
this.showLoading();
//flag showing is form now saving value to server.
//It is needed to wait when closing form.
this.isSaving = false;
/**
Fired when rendering starts
@event rendering
@param {Object} event event object
**/
this.$div.triggerHandler('rendering');
//init input
this.initInput();
//append input to form
this.$form.find('div.editable-input').append(this.input.$tpl);
//append form to container
this.$div.append(this.$form);
//render input
$.when(this.input.render())
.then($.proxy(function () {
//setup input to submit automatically when no buttons shown
if(!this.options.showbuttons) {
this.input.autosubmit();
}
//attach 'cancel' handler
this.$form.find('.editable-cancel').click($.proxy(this.cancel, this));
if(this.input.error) {
this.error(this.input.error);
this.$form.find('.editable-submit').attr('disabled', true);
this.input.$input.attr('disabled', true);
//prevent form from submitting
this.$form.submit(function(e){ e.preventDefault(); });
} else {
this.error(false);
this.input.$input.removeAttr('disabled');
this.$form.find('.editable-submit').removeAttr('disabled');
var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value;
this.input.value2input(value);
//attach submit handler
this.$form.submit($.proxy(this.submit, this));
}
/**
Fired when form is rendered
@event rendered
@param {Object} event event object
**/
this.$div.triggerHandler('rendered');
this.showForm();
//call postrender method to perform actions required visibility of form
if(this.input.postrender) {
this.input.postrender();
}
}, this));
},
cancel: function() {
/**
Fired when form was cancelled by user
@event cancel
@param {Object} event event object
**/
this.$div.triggerHandler('cancel');
},
showLoading: function() {
var w, h;
if(this.$form) {
//set loading size equal to form
w = this.$form.outerWidth();
h = this.$form.outerHeight();
if(w) {
this.$loading.width(w);
}
if(h) {
this.$loading.height(h);
}
this.$form.hide();
} else {
//stretch loading to fill container width
w = this.$loading.parent().width();
if(w) {
this.$loading.width(w);
}
}
this.$loading.show();
},
showForm: function(activate) {
this.$loading.hide();
this.$form.show();
if(activate !== false) {
this.input.activate();
}
/**
Fired when form is shown
@event show
@param {Object} event event object
**/
this.$div.triggerHandler('show');
},
error: function(msg) {
var $group = this.$form.find('.control-group'),
$block = this.$form.find('.editable-error-block'),
lines;
if(msg === false) {
$group.removeClass($.fn.editableform.errorGroupClass);
$block.removeClass($.fn.editableform.errorBlockClass).empty().hide();
} else {
//convert newline to <br> for more pretty error display
if(msg) {
lines = (''+msg).split('\n');
for (var i = 0; i < lines.length; i++) {
lines[i] = $('<div>').text(lines[i]).html();
}
msg = lines.join('<br>');
}
$group.addClass($.fn.editableform.errorGroupClass);
$block.addClass($.fn.editableform.errorBlockClass).html(msg).show();
}
},
submit: function(e) {
e.stopPropagation();
e.preventDefault();
//get new value from input
var newValue = this.input.input2value();
//validation: if validate returns string or truthy value - means error
//if returns object like {newValue: '...'} => submitted value is reassigned to it
var error = this.validate(newValue);
if ($.type(error) === 'object' && error.newValue !== undefined) {
newValue = error.newValue;
this.input.value2input(newValue);
if(typeof error.msg === 'string') {
this.error(error.msg);
this.showForm();
return;
}
} else if (error) {
this.error(error);
this.showForm();
return;
}
//if value not changed --> trigger 'nochange' event and return
/*jslint eqeq: true*/
if (!this.options.savenochange && this.input.value2str(newValue) === this.input.value2str(this.value)) {
/*jslint eqeq: false*/
/**
Fired when value not changed but form is submitted. Requires savenochange = false.
@event nochange
@param {Object} event event object
**/
this.$div.triggerHandler('nochange');
return;
}
//convert value for submitting to server
var submitValue = this.input.value2submit(newValue);
this.isSaving = true;
//sending data to server
$.when(this.save(submitValue))
.done($.proxy(function(response) {
this.isSaving = false;
//run success callback
var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null;
//if success callback returns false --> keep form open and do not activate input
if(res === false) {
this.error(false);
this.showForm(false);
return;
}
//if success callback returns string --> keep form open, show error and activate input
if(typeof res === 'string') {
this.error(res);
this.showForm();
return;
}
//if success callback returns object like {newValue: <something>} --> use that value instead of submitted
//it is useful if you want to chnage value in url-function
if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) {
newValue = res.newValue;
}
//clear error message
this.error(false);
this.value = newValue;
/**
Fired when form is submitted
@event save
@param {Object} event event object
@param {Object} params additional params
@param {mixed} params.newValue raw new value
@param {mixed} params.submitValue submitted value as string
@param {Object} params.response ajax response
@example
$('#form-div').on('save'), function(e, params){
if(params.newValue === 'username') {...}
});
**/
this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response});
}, this))
.fail($.proxy(function(xhr) {
this.isSaving = false;
var msg;
if(typeof this.options.error === 'function') {
msg = this.options.error.call(this.options.scope, xhr, newValue);
} else {
msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!';
}
this.error(msg);
this.showForm();
}, this));
},
save: function(submitValue) {
//try parse composite pk defined as json string in data-pk
this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true);
var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk,
/*
send on server in following cases:
1. url is function
2. url is string AND (pk defined OR send option = always)
*/
send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))),
params;
if (send) { //send to server
this.showLoading();
//standard params
params = {
name: this.options.name || '',
value: submitValue,
pk: pk
};
//additional params
if(typeof this.options.params === 'function') {
params = this.options.params.call(this.options.scope, params);
} else {
//try parse json in single quotes (from data-params attribute)
this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true);
$.extend(params, this.options.params);
}
if(typeof this.options.url === 'function') { //user's function
return this.options.url.call(this.options.scope, params);
} else {
//send ajax to server and return deferred object
return $.ajax($.extend({
url : this.options.url,
data : params,
type : 'POST'
}, this.options.ajaxOptions));
}
}
},
validate: function (value) {
if (value === undefined) {
value = this.value;
}
if (typeof this.options.validate === 'function') {
return this.options.validate.call(this.options.scope, value);
}
},
option: function(key, value) {
if(key in this.options) {
this.options[key] = value;
}
if(key === 'value') {
this.setValue(value);
}
//do not pass option to input as it is passed in editable-element
},
setValue: function(value, convertStr) {
if(convertStr) {
this.value = this.input.str2value(value);
} else {
this.value = value;
}
//if form is visible, update input
if(this.$form && this.$form.is(':visible')) {
this.input.value2input(this.value);
}
}
};
/*
Initialize editableform. Applied to jQuery object.
@method $().editableform(options)
@params {Object} options
@example
var $form = $('<div>').editableform({
type: 'text',
name: 'username',
url: '/post',
value: 'vitaliy'
});
//to display form you should call 'render' method
$form.editableform('render');
*/
$.fn.editableform = function (option) {
var args = arguments;
return this.each(function () {
var $this = $(this),
data = $this.data('editableform'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('editableform', (data = new EditableForm(this, options)));
}
if (typeof option === 'string') { //call method
data[option].apply(data, Array.prototype.slice.call(args, 1));
}
});
};
//keep link to constructor to allow inheritance
$.fn.editableform.Constructor = EditableForm;
//defaults
$.fn.editableform.defaults = {
/* see also defaults for input */
/**
Type of input. Can be <code>text|textarea|select|date|checklist</code>
@property type
@type string
@default 'text'
**/
type: 'text',
/**
Url for submit, e.g. <code>'/post'</code>
If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks.
@property url
@type string|function
@default null
@example
url: function(params) {
var d = new $.Deferred;
if(params.value === 'abc') {
return d.reject('error message'); //returning error via deferred object
} else {
//async saving data in js model
someModel.asyncSaveMethod({
...,
success: function(){
d.resolve();
}
});
return d.promise();
}
}
**/
url:null,
/**
Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value).
If defined as <code>function</code> - returned object **overwrites** original ajax data.
@example
params: function(params) {
//originally params contain pk, name and value
params.a = 1;
return params;
}
@property params
@type object|function
@default null
**/
params:null,
/**
Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute
@property name
@type string
@default null
**/
name: null,
/**
Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>.
Can be calculated dynamically via function.
@property pk
@type string|object|function
@default null
**/
pk: null,
/**
Initial value. If not defined - will be taken from element's content.
For __select__ type should be defined (as it is ID of shown text).
@property value
@type string|object
@default null
**/
value: null,
/**
Value that will be displayed in input if original field value is empty (`null|undefined|''`).
@property defaultValue
@type string|object
@default null
@since 1.4.6
**/
defaultValue: null,
/**
Strategy for sending data on server. Can be `auto|always|never`.
When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally.
@property send
@type string
@default 'auto'
**/
send: 'auto',
/**
Function for client-side validation. If returns string - means validation not passed and string showed as error.
Since 1.5.1 you can modify submitted value by returning object from `validate`:
`{newValue: '...'}` or `{newValue: '...', msg: '...'}`
@property validate
@type function
@default null
@example
validate: function(value) {
if($.trim(value) == '') {
return 'This field is required';
}
}
**/
validate: null,
/**
Success callback. Called when value successfully sent on server and **response status = 200**.
Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code>
or `{success: false, msg: "server error"}` you can check it inside this callback.
If it returns **string** - means error occured and string is shown as error message.
If it returns **object like** `{newValue: <something>}` - it overwrites value, submitted by user
(useful when server changes value).
Otherwise newValue simply rendered into element.
@property success
@type function
@default null
@example
success: function(response, newValue) {
if(!response.success) return response.msg;
}
**/
success: null,
/**
Error callback. Called when request failed (response status != 200).
Usefull when you want to parse error response and display a custom message.
Must return **string** - the message to be displayed in the error block.
@property error
@type function
@default null
@since 1.4.4
@example
error: function(response, newValue) {
if(response.status === 500) {
return 'Service unavailable. Please try later.';
} else {
return response.responseText;
}
}
**/
error: null,
/**
Additional options for submit ajax request.
List of values: http://api.jquery.com/jQuery.ajax
@property ajaxOptions
@type object
@default null
@since 1.1.1
@example
ajaxOptions: {
type: 'put',
dataType: 'json'
}
**/
ajaxOptions: null,
/**
Where to show buttons: left(true)|bottom|false
Form without buttons is auto-submitted.
@property showbuttons
@type boolean|string
@default true
@since 1.1.1
**/
showbuttons: true,
/**
Scope for callback methods (success, validate).
If <code>null</code> means editableform instance itself.
@property scope
@type DOMElement|object
@default null
@since 1.2.0
@private
**/
scope: null,
/**
Whether to save or cancel value when it was not changed but form was submitted
@property savenochange
@type boolean
@default false
@since 1.2.0
**/
savenochange: false
};
/*
Note: following params could redefined in engine: bootstrap or jqueryui:
Classes 'control-group' and 'editable-error-block' must always present!
*/
$.fn.editableform.template = '<form class="form-inline editableform">'+
'<div class="control-group">' +
'<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+
'<div class="editable-error-block"></div>' +
'</div>' +
'</form>';
//loading div
$.fn.editableform.loading = '<div class="editableform-loading"></div>';
//buttons
$.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+
'<button type="button" class="editable-cancel">cancel</button>';
//error class attached to control-group
$.fn.editableform.errorGroupClass = null;
//error class attached to editable-error-block
$.fn.editableform.errorBlockClass = 'editable-error';
//engine
$.fn.editableform.engine = 'jquery';
}(window.jQuery));
/**
* EditableForm utilites
*/
(function ($) {
"use strict";
//utils
$.fn.editableutils = {
/**
* classic JS inheritance function
*/
inherit: function (Child, Parent) {
var F = function() { };
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.superclass = Parent.prototype;
},
/**
* set caret position in input
* see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
*/
setCursorPosition: function(elem, pos) {
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
},
/**
* function to parse JSON in *single* quotes. (jquery automatically parse only double quotes)
* That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}">
* safe = true --> means no exception will be thrown
* for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery
*/
tryParseJson: function(s, safe) {
if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) {
if (safe) {
try {
/*jslint evil: true*/
s = (new Function('return ' + s))();
/*jslint evil: false*/
} catch (e) {} finally {
return s;
}
} else {
/*jslint evil: true*/
s = (new Function('return ' + s))();
/*jslint evil: false*/
}
}
return s;
},
/**
* slice object by specified keys
*/
sliceObj: function(obj, keys, caseSensitive /* default: false */) {
var key, keyLower, newObj = {};
if (!$.isArray(keys) || !keys.length) {
return newObj;
}
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key];
}
if(caseSensitive === true) {
continue;
}
//when getting data-* attributes via $.data() it's converted to lowercase.
//details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery
//workaround is code below.
keyLower = key.toLowerCase();
if (obj.hasOwnProperty(keyLower)) {
newObj[key] = obj[keyLower];
}
}
return newObj;
},
/*
exclude complex objects from $.data() before pass to config
*/
getConfigData: function($element) {
var data = {};
$.each($element.data(), function(k, v) {
if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) {
data[k] = v;
}
});
return data;
},
/*
returns keys of object
*/
objectKeys: function(o) {
if (Object.keys) {
return Object.keys(o);
} else {
if (o !== Object(o)) {
throw new TypeError('Object.keys called on a non-object');
}
var k=[], p;
for (p in o) {
if (Object.prototype.hasOwnProperty.call(o,p)) {
k.push(p);
}
}
return k;
}
},
/**
method to escape html.
**/
escape: function(str) {
return $('<div>').text(str).html();
},
/*
returns array items from sourceData having value property equal or inArray of 'value'
*/
itemsByValue: function(value, sourceData, valueProp) {
if(!sourceData || value === null) {
return [];
}
if (typeof(valueProp) !== "function") {
var idKey = valueProp || 'value';
valueProp = function (e) { return e[idKey]; };
}
var isValArray = $.isArray(value),
result = [],
that = this;
$.each(sourceData, function(i, o) {
if(o.children) {
result = result.concat(that.itemsByValue(value, o.children, valueProp));
} else {
/*jslint eqeq: true*/
if(isValArray) {
if($.grep(value, function(v){ return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) {
result.push(o);
}
} else {
var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o;
if(value == itemValue) {
result.push(o);
}
}
/*jslint eqeq: false*/
}
});
return result;
},
/*
Returns input by options: type, mode.
*/
createInput: function(options) {
var TypeConstructor, typeOptions, input,
type = options.type;
//`date` is some kind of virtual type that is transformed to one of exact types
//depending on mode and core lib
if(type === 'date') {
//inline
if(options.mode === 'inline') {
if($.fn.editabletypes.datefield) {
type = 'datefield';
} else if($.fn.editabletypes.dateuifield) {
type = 'dateuifield';
}
//popup
} else {
if($.fn.editabletypes.date) {
type = 'date';
} else if($.fn.editabletypes.dateui) {
type = 'dateui';
}
}
//if type still `date` and not exist in types, replace with `combodate` that is base input
if(type === 'date' && !$.fn.editabletypes.date) {
type = 'combodate';
}
}
//`datetime` should be datetimefield in 'inline' mode
if(type === 'datetime' && options.mode === 'inline') {
type = 'datetimefield';
}
//change wysihtml5 to textarea for jquery UI and plain versions
if(type === 'wysihtml5' && !$.fn.editabletypes[type]) {
type = 'textarea';
}
//create input of specified type. Input will be used for converting value, not in form
if(typeof $.fn.editabletypes[type] === 'function') {
TypeConstructor = $.fn.editabletypes[type];
typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults));
input = new TypeConstructor(typeOptions);
return input;
} else {
$.error('Unknown type: '+ type);
return false;
}
},
//see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr
supportsTransitions: function () {
var b = document.body || document.documentElement,
s = b.style,
p = 'transition',
v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'];
if(typeof s[p] === 'string') {
return true;
}
// Tests for vendor specific prop
p = p.charAt(0).toUpperCase() + p.substr(1);
for(var i=0; i<v.length; i++) {
if(typeof s[v[i] + p] === 'string') {
return true;
}
}
return false;
}
};
}(window.jQuery));
/**
Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br>
This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br>
Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br>
Applied as jQuery method.
@class editableContainer
@uses editableform
**/
(function ($) {
"use strict";
var Popup = function (element, options) {
this.init(element, options);
};
var Inline = function (element, options) {
this.init(element, options);
};
//methods
Popup.prototype = {
containerName: null, //method to call container on element
containerDataName: null, //object name in element's .data()
innerCss: null, //tbd in child class
containerClass: 'editable-container editable-popup', //css class applied to container element
defaults: {}, //container itself defaults
init: function(element, options) {
this.$element = $(element);
//since 1.4.1 container do not use data-* directly as they already merged into options.
this.options = $.extend({}, $.fn.editableContainer.defaults, options);
this.splitOptions();
//set scope of form callbacks to element
this.formOptions.scope = this.$element[0];
this.initContainer();
//flag to hide container, when saving value will finish
this.delayedHide = false;
//bind 'destroyed' listener to destroy container when element is removed from dom
this.$element.on('destroyed', $.proxy(function(){
this.destroy();
}, this));
//attach document handler to close containers on click / escape
if(!$(document).data('editable-handlers-attached')) {
//close all on escape
$(document).on('keyup.editable', function (e) {
if (e.which === 27) {
$('.editable-open').editableContainer('hide');
//todo: return focus on element
}
});
//close containers when click outside
//(mousedown could be better than click, it closes everything also on drag drop)
$(document).on('click.editable', function(e) {
var $target = $(e.target), i,
exclude_classes = ['.editable-container',
'.ui-datepicker-header',
'.datepicker', //in inline mode datepicker is rendered into body
'.modal-backdrop',
'.bootstrap-wysihtml5-insert-image-modal',
'.bootstrap-wysihtml5-insert-link-modal'
];
// select2 has extra body click in IE
// see: https://github.com/ivaynberg/select2/issues/1058
if ($('.select2-drop-mask').is(':visible')) {
return;
}
//check if element is detached. It occurs when clicking in bootstrap datepicker
if (!$.contains(document.documentElement, e.target)) {
return;
}
//for some reason FF 20 generates extra event (click) in select2 widget with e.target = document
//we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199
//Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec
if($target.is(document)) {
return;
}
//if click inside one of exclude classes --> no nothing
for(i=0; i<exclude_classes.length; i++) {
if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) {
return;
}
}
//close all open containers (except one - target)
Popup.prototype.closeOthers(e.target);
});
$(document).data('editable-handlers-attached', true);
}
},
//split options on containerOptions and formOptions
splitOptions: function() {
this.containerOptions = {};
this.formOptions = {};
if(!$.fn[this.containerName]) {
throw new Error(this.containerName + ' not found. Have you included corresponding js file?');
}
//keys defined in container defaults go to container, others go to form
for(var k in this.options) {
if(k in this.defaults) {
this.containerOptions[k] = this.options[k];
} else {
this.formOptions[k] = this.options[k];
}
}
},
/*
Returns jquery object of container
@method tip()
*/
tip: function() {
return this.container() ? this.container().$tip : null;
},
/* returns container object */
container: function() {
var container;
//first, try get it by `containerDataName`
if(this.containerDataName) {
if(container = this.$element.data(this.containerDataName)) {
return container;
}
}
//second, try `containerName`
container = this.$element.data(this.containerName);
return container;
},
/* call native method of underlying container, e.g. this.$element.popover('method') */
call: function() {
this.$element[this.containerName].apply(this.$element, arguments);
},
initContainer: function(){
this.call(this.containerOptions);
},
renderForm: function() {
this.$form
.editableform(this.formOptions)
.on({
save: $.proxy(this.save, this), //click on submit button (value changed)
nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed)
cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on cancel button
show: $.proxy(function() {
if(this.delayedHide) {
this.hide(this.delayedHide.reason);
this.delayedHide = false;
} else {
this.setPosition();
}
}, this), //re-position container every time form is shown (occurs each time after loading state)
rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown
resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed
rendered: $.proxy(function(){
/**
Fired when container is shown and form is rendered (for select will wait for loading dropdown options).
**Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one.
The workaround is to check `arguments.length` that is always `2` for x-editable.
@event shown
@param {Object} event event object
@example
$('#username').on('shown', function(e, editable) {
editable.input.$input.val('overwriting value of input..');
});
**/
/*
TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events.
*/
this.$element.triggerHandler('shown', $(this.options.scope).data('editable'));
}, this)
})
.editableform('render');
},
/**
Shows container with form
@method show()
@param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
**/
/* Note: poshytip owerwrites this method totally! */
show: function (closeAll) {
this.$element.addClass('editable-open');
if(closeAll !== false) {
//close all open containers (except this)
this.closeOthers(this.$element[0]);
}
//show container itself
this.innerShow();
this.tip().addClass(this.containerClass);
/*
Currently, form is re-rendered on every show.
The main reason is that we dont know, what will container do with content when closed:
remove(), detach() or just hide() - it depends on container.
Detaching form itself before hide and re-insert before show is good solution,
but visually it looks ugly --> container changes size before hide.
*/
//if form already exist - delete previous data
if(this.$form) {
//todo: destroy prev data!
//this.$form.destroy();
}
this.$form = $('<div>');
//insert form into container body
if(this.tip().is(this.innerCss)) {
//for inline container
this.tip().append(this.$form);
} else {
this.tip().find(this.innerCss).append(this.$form);
}
//render form
this.renderForm();
},
/**
Hides container with form
@method hide()
@param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code>
**/
hide: function(reason) {
if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) {
return;
}
//if form is saving value, schedule hide
if(this.$form.data('editableform').isSaving) {
this.delayedHide = {reason: reason};
return;
} else {
this.delayedHide = false;
}
this.$element.removeClass('editable-open');
this.innerHide();
/**
Fired when container was hidden. It occurs on both save or cancel.
**Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one.
The workaround is to check `arguments.length` that is always `2` for x-editable.
@event hidden
@param {object} event event object
@param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code>
@example
$('#username').on('hidden', function(e, reason) {
if(reason === 'save' || reason === 'cancel') {
//auto-open next editable
$(this).closest('tr').next().find('.editable').editable('show');
}
});
**/
this.$element.triggerHandler('hidden', reason || 'manual');
},
/* internal show method. To be overwritten in child classes */
innerShow: function () {
},
/* internal hide method. To be overwritten in child classes */
innerHide: function () {
},
/**
Toggles container visibility (show / hide)
@method toggle()
@param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
**/
toggle: function(closeAll) {
if(this.container() && this.tip() && this.tip().is(':visible')) {
this.hide();
} else {
this.show(closeAll);
}
},
/*
Updates the position of container when content changed.
@method setPosition()
*/
setPosition: function() {
//tbd in child class
},
save: function(e, params) {
/**
Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance
@event save
@param {Object} event event object
@param {Object} params additional params
@param {mixed} params.newValue submitted value
@param {Object} params.response ajax response
@example
$('#username').on('save', function(e, params) {
//assuming server response: '{success: true}'
var pk = $(this).data('editableContainer').options.pk;
if(params.response && params.response.success) {
alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!');
} else {
alert('error!');
}
});
**/
this.$element.triggerHandler('save', params);
//hide must be after trigger, as saving value may require methods of plugin, applied to input
this.hide('save');
},
/**
Sets new option
@method option(key, value)
@param {string} key
@param {mixed} value
**/
option: function(key, value) {
this.options[key] = value;
if(key in this.containerOptions) {
this.containerOptions[key] = value;
this.setContainerOption(key, value);
} else {
this.formOptions[key] = value;
if(this.$form) {
this.$form.editableform('option', key, value);
}
}
},
setContainerOption: function(key, value) {
this.call('option', key, value);
},
/**
Destroys the container instance
@method destroy()
**/
destroy: function() {
this.hide();
this.innerDestroy();
this.$element.off('destroyed');
this.$element.removeData('editableContainer');
},
/* to be overwritten in child classes */
innerDestroy: function() {
},
/*
Closes other containers except one related to passed element.
Other containers can be cancelled or submitted (depends on onblur option)
*/
closeOthers: function(element) {
$('.editable-open').each(function(i, el){
//do nothing with passed element and it's children
if(el === element || $(el).find(element).length) {
return;
}
//otherwise cancel or submit all open containers
var $el = $(el),
ec = $el.data('editableContainer');
if(!ec) {
return;
}
if(ec.options.onblur === 'cancel') {
$el.data('editableContainer').hide('onblur');
} else if(ec.options.onblur === 'submit') {
$el.data('editableContainer').tip().find('form').submit();
}
});
},
/**
Activates input of visible container (e.g. set focus)
@method activate()
**/
activate: function() {
if(this.tip && this.tip().is(':visible') && this.$form) {
this.$form.data('editableform').input.activate();
}
}
};
/**
jQuery method to initialize editableContainer.
@method $().editableContainer(options)
@params {Object} options
@example
$('#edit').editableContainer({
type: 'text',
url: '/post',
pk: 1,
value: 'hello'
});
**/
$.fn.editableContainer = function (option) {
var args = arguments;
return this.each(function () {
var $this = $(this),
dataKey = 'editableContainer',
data = $this.data(dataKey),
options = typeof option === 'object' && option,
Constructor = (options.mode === 'inline') ? Inline : Popup;
if (!data) {
$this.data(dataKey, (data = new Constructor(this, options)));
}
if (typeof option === 'string') { //call method
data[option].apply(data, Array.prototype.slice.call(args, 1));
}
});
};
//store constructors
$.fn.editableContainer.Popup = Popup;
$.fn.editableContainer.Inline = Inline;
//defaults
$.fn.editableContainer.defaults = {
/**
Initial value of form input
@property value
@type mixed
@default null
@private
**/
value: null,
/**
Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container.
@property placement
@type string
@default 'top'
**/
placement: 'top',
/**
Whether to hide container on save/cancel.
@property autohide
@type boolean
@default true
@private
**/
autohide: true,
/**
Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>.
Setting <code>ignore</code> allows to have several containers open.
@property onblur
@type string
@default 'cancel'
@since 1.1.1
**/
onblur: 'cancel',
/**
Animation speed (inline mode only)
@property anim
@type string
@default false
**/
anim: false,
/**
Mode of editable, can be `popup` or `inline`
@property mode
@type string
@default 'popup'
@since 1.4.0
**/
mode: 'popup'
};
/*
* workaround to have 'destroyed' event to destroy popover when element is destroyed
* see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom
*/
jQuery.event.special.destroyed = {
remove: function(o) {
if (o.handler) {
o.handler();
}
}
};
}(window.jQuery));
/**
* Editable Inline
* ---------------------
*/
(function ($) {
"use strict";
//copy prototype from EditableContainer
//extend methods
$.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, {
containerName: 'editableform',
innerCss: '.editable-inline',
containerClass: 'editable-container editable-inline', //css class applied to container element
initContainer: function(){
//container is <span> element
this.$tip = $('<span></span>');
//convert anim to miliseconds (int)
if(!this.options.anim) {
this.options.anim = 0;
}
},
splitOptions: function() {
//all options are passed to form
this.containerOptions = {};
this.formOptions = this.options;
},
tip: function() {
return this.$tip;
},
innerShow: function () {
this.$element.hide();
this.tip().insertAfter(this.$element).show();
},
innerHide: function () {
this.$tip.hide(this.options.anim, $.proxy(function() {
this.$element.show();
this.innerDestroy();
}, this));
},
innerDestroy: function() {
if(this.tip()) {
this.tip().empty().remove();
}
}
});
}(window.jQuery));
/**
Makes editable any HTML element on the page. Applied as jQuery method.
@class editable
@uses editableContainer
**/
(function ($) {
"use strict";
var Editable = function (element, options) {
this.$element = $(element);
//data-* has more priority over js options: because dynamically created elements may change data-*
this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element));
if(this.options.selector) {
this.initLive();
} else {
this.init();
}
//check for transition support
if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) {
this.options.highlight = false;
}
};
Editable.prototype = {
constructor: Editable,
init: function () {
var isValueByText = false,
doAutotext, finalize;
//name
this.options.name = this.options.name || this.$element.attr('id');
//create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select)
//also we set scope option to have access to element inside input specific callbacks (e. g. source as function)
this.options.scope = this.$element[0];
this.input = $.fn.editableutils.createInput(this.options);
if(!this.input) {
return;
}
//set value from settings or by element's text
if (this.options.value === undefined || this.options.value === null) {
this.value = this.input.html2value($.trim(this.$element.html()));
isValueByText = true;
} else {
/*
value can be string when received from 'data-value' attribute
for complext objects value can be set as json string in data-value attribute,
e.g. data-value="{city: 'Moscow', street: 'Lenina'}"
*/
this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true);
if(typeof this.options.value === 'string') {
this.value = this.input.str2value(this.options.value);
} else {
this.value = this.options.value;
}
}
//add 'editable' class to every editable element
this.$element.addClass('editable');
//specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks
if(this.input.type === 'textarea') {
this.$element.addClass('editable-pre-wrapped');
}
//attach handler activating editable. In disabled mode it just prevent default action (useful for links)
if(this.options.toggle !== 'manual') {
this.$element.addClass('editable-click');
this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){
//prevent following link if editable enabled
if(!this.options.disabled) {
e.preventDefault();
}
//stop propagation not required because in document click handler it checks event target
//e.stopPropagation();
if(this.options.toggle === 'mouseenter') {
//for hover only show container
this.show();
} else {
//when toggle='click' we should not close all other containers as they will be closed automatically in document click listener
var closeAll = (this.options.toggle !== 'click');
this.toggle(closeAll);
}
}, this));
} else {
this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually
}
//if display is function it's far more convinient to have autotext = always to render correctly on init
//see https://github.com/vitalets/x-editable-yii/issues/34
if(typeof this.options.display === 'function') {
this.options.autotext = 'always';
}
//check conditions for autotext:
switch(this.options.autotext) {
case 'always':
doAutotext = true;
break;
case 'auto':
//if element text is empty and value is defined and value not generated by text --> run autotext
doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText;
break;
default:
doAutotext = false;
}
//depending on autotext run render() or just finilize init
$.when(doAutotext ? this.render() : true).then($.proxy(function() {
if(this.options.disabled) {
this.disable();
} else {
this.enable();
}
/**
Fired when element was initialized by `$().editable()` method.
Please note that you should setup `init` handler **before** applying `editable`.
@event init
@param {Object} event event object
@param {Object} editable editable instance (as here it cannot accessed via data('editable'))
@since 1.2.0
@example
$('#username').on('init', function(e, editable) {
alert('initialized ' + editable.options.name);
});
$('#username').editable();
**/
this.$element.triggerHandler('init', this);
}, this));
},
/*
Initializes parent element for live editables
*/
initLive: function() {
//store selector
var selector = this.options.selector;
//modify options for child elements
this.options.selector = false;
this.options.autotext = 'never';
//listen toggle events
this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){
var $target = $(e.target);
if(!$target.data('editable')) {
//if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user)
//see https://github.com/vitalets/x-editable/issues/137
if($target.hasClass(this.options.emptyclass)) {
$target.empty();
}
$target.editable(this.options).trigger(e);
}
}, this));
},
/*
Renders value into element's text.
Can call custom display method from options.
Can return deferred object.
@method render()
@param {mixed} response server response (if exist) to pass into display function
*/
render: function(response) {
//do not display anything
if(this.options.display === false) {
return;
}
//if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded
if(this.input.value2htmlFinal) {
return this.input.value2html(this.value, this.$element[0], this.options.display, response);
//if display method defined --> use it
} else if(typeof this.options.display === 'function') {
return this.options.display.call(this.$element[0], this.value, response);
//else use input's original value2html() method
} else {
return this.input.value2html(this.value, this.$element[0]);
}
},
/**
Enables editable
@method enable()
**/
enable: function() {
this.options.disabled = false;
this.$element.removeClass('editable-disabled');
this.handleEmpty(this.isEmpty);
if(this.options.toggle !== 'manual') {
if(this.$element.attr('tabindex') === '-1') {
this.$element.removeAttr('tabindex');
}
}
},
/**
Disables editable
@method disable()
**/
disable: function() {
this.options.disabled = true;
this.hide();
this.$element.addClass('editable-disabled');
this.handleEmpty(this.isEmpty);
//do not stop focus on this element
this.$element.attr('tabindex', -1);
},
/**
Toggles enabled / disabled state of editable element
@method toggleDisabled()
**/
toggleDisabled: function() {
if(this.options.disabled) {
this.enable();
} else {
this.disable();
}
},
/**
Sets new option
@method option(key, value)
@param {string|object} key option name or object with several options
@param {mixed} value option new value
@example
$('.editable').editable('option', 'pk', 2);
**/
option: function(key, value) {
//set option(s) by object
if(key && typeof key === 'object') {
$.each(key, $.proxy(function(k, v){
this.option($.trim(k), v);
}, this));
return;
}
//set option by string
this.options[key] = value;
//disabled
if(key === 'disabled') {
return value ? this.disable() : this.enable();
}
//value
if(key === 'value') {
this.setValue(value);
}
//transfer new option to container!
if(this.container) {
this.container.option(key, value);
}
//pass option to input directly (as it points to the same in form)
if(this.input.option) {
this.input.option(key, value);
}
},
/*
* set emptytext if element is empty
*/
handleEmpty: function (isEmpty) {
//do not handle empty if we do not display anything
if(this.options.display === false) {
return;
}
/*
isEmpty may be set directly as param of method.
It is required when we enable/disable field and can't rely on content
as node content is text: "Empty" that is not empty %)
*/
if(isEmpty !== undefined) {
this.isEmpty = isEmpty;
} else {
//detect empty
//for some inputs we need more smart check
//e.g. wysihtml5 may have <br>, <p></p>, <img>
if(typeof(this.input.isEmpty) === 'function') {
this.isEmpty = this.input.isEmpty(this.$element);
} else {
this.isEmpty = $.trim(this.$element.html()) === '';
}
}
//emptytext shown only for enabled
if(!this.options.disabled) {
if (this.isEmpty) {
this.$element.html(this.options.emptytext);
if(this.options.emptyclass) {
this.$element.addClass(this.options.emptyclass);
}
} else if(this.options.emptyclass) {
this.$element.removeClass(this.options.emptyclass);
}
} else {
//below required if element disable property was changed
if(this.isEmpty) {
this.$element.empty();
if(this.options.emptyclass) {
this.$element.removeClass(this.options.emptyclass);
}
}
}
},
/**
Shows container with form
@method show()
@param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
**/
show: function (closeAll) {
if(this.options.disabled) {
return;
}
//init editableContainer: popover, tooltip, inline, etc..
if(!this.container) {
var containerOptions = $.extend({}, this.options, {
value: this.value,
input: this.input //pass input to form (as it is already created)
});
this.$element.editableContainer(containerOptions);
//listen `save` event
this.$element.on("save.internal", $.proxy(this.save, this));
this.container = this.$element.data('editableContainer');
} else if(this.container.tip().is(':visible')) {
return;
}
//show container
this.container.show(closeAll);
},
/**
Hides container with form
@method hide()
**/
hide: function () {
if(this.container) {
this.container.hide();
}
},
/**
Toggles container visibility (show / hide)
@method toggle()
@param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
**/
toggle: function(closeAll) {
if(this.container && this.container.tip().is(':visible')) {
this.hide();
} else {
this.show(closeAll);
}
},
/*
* called when form was submitted
*/
save: function(e, params) {
//mark element with unsaved class if needed
if(this.options.unsavedclass) {
/*
Add unsaved css to element if:
- url is not user's function
- value was not sent to server
- params.response === undefined, that means data was not sent
- value changed
*/
var sent = false;
sent = sent || typeof this.options.url === 'function';
sent = sent || this.options.display === false;
sent = sent || params.response !== undefined;
sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue));
if(sent) {
this.$element.removeClass(this.options.unsavedclass);
} else {
this.$element.addClass(this.options.unsavedclass);
}
}
//highlight when saving
if(this.options.highlight) {
var $e = this.$element,
bgColor = $e.css('background-color');
$e.css('background-color', this.options.highlight);
setTimeout(function(){
if(bgColor === 'transparent') {
bgColor = '';
}
$e.css('background-color', bgColor);
$e.addClass('editable-bg-transition');
setTimeout(function(){
$e.removeClass('editable-bg-transition');
}, 1700);
}, 10);
}
//set new value
this.setValue(params.newValue, false, params.response);
/**
Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance
@event save
@param {Object} event event object
@param {Object} params additional params
@param {mixed} params.newValue submitted value
@param {Object} params.response ajax response
@example
$('#username').on('save', function(e, params) {
alert('Saved value: ' + params.newValue);
});
**/
//event itself is triggered by editableContainer. Description here is only for documentation
},
validate: function () {
if (typeof this.options.validate === 'function') {
return this.options.validate.call(this, this.value);
}
},
/**
Sets new value of editable
@method setValue(value, convertStr)
@param {mixed} value new value
@param {boolean} convertStr whether to convert value from string to internal format
**/
setValue: function(value, convertStr, response) {
if(convertStr) {
this.value = this.input.str2value(value);
} else {
this.value = value;
}
if(this.container) {
this.container.option('value', this.value);
}
$.when(this.render(response))
.then($.proxy(function() {
this.handleEmpty();
}, this));
},
/**
Activates input of visible container (e.g. set focus)
@method activate()
**/
activate: function() {
if(this.container) {
this.container.activate();
}
},
/**
Removes editable feature from element
@method destroy()
**/
destroy: function() {
this.disable();
if(this.container) {
this.container.destroy();
}
this.input.destroy();
if(this.options.toggle !== 'manual') {
this.$element.removeClass('editable-click');
this.$element.off(this.options.toggle + '.editable');
}
this.$element.off("save.internal");
this.$element.removeClass('editable editable-open editable-disabled');
this.$element.removeData('editable');
}
};
/* EDITABLE PLUGIN DEFINITION
* ======================= */
/**
jQuery method to initialize editable element.
@method $().editable(options)
@params {Object} options
@example
$('#username').editable({
type: 'text',
url: '/post',
pk: 1
});
**/
$.fn.editable = function (option) {
//special API methods returning non-jquery object
var result = {}, args = arguments, datakey = 'editable';
switch (option) {
/**
Runs client-side validation for all matched editables
@method validate()
@returns {Object} validation errors map
@example
$('#username, #fullname').editable('validate');
// possible result:
{
username: "username is required",
fullname: "fullname should be minimum 3 letters length"
}
**/
case 'validate':
this.each(function () {
var $this = $(this), data = $this.data(datakey), error;
if (data && (error = data.validate())) {
result[data.options.name] = error;
}
});
return result;
/**
Returns current values of editable elements.
Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements.
If value of some editable is `null` or `undefined` it is excluded from result object.
When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object.
@method getValue()
@param {bool} isSingle whether to return just value of single element
@returns {Object} object of element names and values
@example
$('#username, #fullname').editable('getValue');
//result:
{
username: "superuser",
fullname: "John"
}
//isSingle = true
$('#username').editable('getValue', true);
//result "superuser"
**/
case 'getValue':
if(arguments.length === 2 && arguments[1] === true) { //isSingle = true
result = this.eq(0).data(datakey).value;
} else {
this.each(function () {
var $this = $(this), data = $this.data(datakey);
if (data && data.value !== undefined && data.value !== null) {
result[data.options.name] = data.input.value2submit(data.value);
}
});
}
return result;
/**
This method collects values from several editable elements and submit them all to server.
Internally it runs client-side validation for all fields and submits only in case of success.
See <a href="#newrecord">creating new records</a> for details.
Since 1.5.1 `submit` can be applied to single element to send data programmatically. In that case
`url`, `success` and `error` is taken from initial options and you can just call `$('#username').editable('submit')`.
@method submit(options)
@param {object} options
@param {object} options.url url to submit data
@param {object} options.data additional data to submit
@param {object} options.ajaxOptions additional ajax options
@param {function} options.error(obj) error handler
@param {function} options.success(obj,config) success handler
@returns {Object} jQuery object
**/
case 'submit': //collects value, validate and submit to server for creating new record
var config = arguments[1] || {},
$elems = this,
errors = this.editable('validate');
// validation ok
if($.isEmptyObject(errors)) {
var ajaxOptions = {};
// for single element use url, success etc from options
if($elems.length === 1) {
var editable = $elems.data('editable');
//standard params
var params = {
name: editable.options.name || '',
value: editable.input.value2submit(editable.value),
pk: (typeof editable.options.pk === 'function') ?
editable.options.pk.call(editable.options.scope) :
editable.options.pk
};
//additional params
if(typeof editable.options.params === 'function') {
params = editable.options.params.call(editable.options.scope, params);
} else {
//try parse json in single quotes (from data-params attribute)
editable.options.params = $.fn.editableutils.tryParseJson(editable.options.params, true);
$.extend(params, editable.options.params);
}
ajaxOptions = {
url: editable.options.url,
data: params,
type: 'POST'
};
// use success / error from options
config.success = config.success || editable.options.success;
config.error = config.error || editable.options.error;
// multiple elements
} else {
var values = this.editable('getValue');
ajaxOptions = {
url: config.url,
data: values,
type: 'POST'
};
}
// ajax success callabck (response 200 OK)
ajaxOptions.success = typeof config.success === 'function' ? function(response) {
config.success.call($elems, response, config);
} : $.noop;
// ajax error callabck
ajaxOptions.error = typeof config.error === 'function' ? function() {
config.error.apply($elems, arguments);
} : $.noop;
// extend ajaxOptions
if(config.ajaxOptions) {
$.extend(ajaxOptions, config.ajaxOptions);
}
// extra data
if(config.data) {
$.extend(ajaxOptions.data, config.data);
}
// perform ajax request
$.ajax(ajaxOptions);
} else { //client-side validation error
if(typeof config.error === 'function') {
config.error.call($elems, errors);
}
}
return this;
}
//return jquery object
return this.each(function () {
var $this = $(this),
data = $this.data(datakey),
options = typeof option === 'object' && option;
//for delegated targets do not store `editable` object for element
//it's allows several different selectors.
//see: https://github.com/vitalets/x-editable/issues/312
if(options && options.selector) {
data = new Editable(this, options);
return;
}
if (!data) {
$this.data(datakey, (data = new Editable(this, options)));
}
if (typeof option === 'string') { //call method
data[option].apply(data, Array.prototype.slice.call(args, 1));
}
});
};
$.fn.editable.defaults = {
/**
Type of input. Can be <code>text|textarea|select|date|checklist</code> and more
@property type
@type string
@default 'text'
**/
type: 'text',
/**
Sets disabled state of editable
@property disabled
@type boolean
@default false
**/
disabled: false,
/**
How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>.
When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable.
**Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element,
you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document.
@example
$('#edit-button').click(function(e) {
e.stopPropagation();
$('#username').editable('toggle');
});
@property toggle
@type string
@default 'click'
**/
toggle: 'click',
/**
Text shown when element is empty.
@property emptytext
@type string
@default 'Empty'
**/
emptytext: 'Empty',
/**
Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date.
For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>.
<code>auto</code> - text will be automatically set only if element is empty.
<code>always|never</code> - always(never) try to set element's text.
@property autotext
@type string
@default 'auto'
**/
autotext: 'auto',
/**
Initial value of input. If not set, taken from element's text.
Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option).
For example, to display currency sign:
@example
<a id="price" data-type="text" data-value="100"></a>
<script>
$('#price').editable({
...
display: function(value) {
$(this).text(value + '$');
}
})
</script>
@property value
@type mixed
@default element's text
**/
value: null,
/**
Callback to perform custom displaying of value in element's text.
If `null`, default input's display used.
If `false`, no displaying methods will be called, element's text will never change.
Runs under element's scope.
_**Parameters:**_
* `value` current value to be displayed
* `response` server response (if display called after ajax submit), since 1.4.0
For _inputs with source_ (select, checklist) parameters are different:
* `value` current value to be displayed
* `sourceData` array of items for current input (e.g. dropdown items)
* `response` server response (if display called after ajax submit), since 1.4.0
To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`.
@property display
@type function|boolean
@default null
@since 1.2.0
@example
display: function(value, sourceData) {
//display checklist as comma-separated values
var html = [],
checked = $.fn.editableutils.itemsByValue(value, sourceData);
if(checked.length) {
$.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); });
$(this).html(html.join(', '));
} else {
$(this).empty();
}
}
**/
display: null,
/**
Css class applied when editable text is empty.
@property emptyclass
@type string
@since 1.4.1
@default editable-empty
**/
emptyclass: 'editable-empty',
/**
Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`).
You may set it to `null` if you work with editables locally and submit them together.
@property unsavedclass
@type string
@since 1.4.1
@default editable-unsaved
**/
unsavedclass: 'editable-unsaved',
/**
If selector is provided, editable will be delegated to the specified targets.
Usefull for dynamically generated DOM elements.
**Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options,
as they actually become editable only after first click.
You should manually set class `editable-click` to these elements.
Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element:
@property selector
@type string
@since 1.4.1
@default null
@example
<div id="user">
<!-- empty -->
<a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a>
<!-- non-empty -->
<a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a>
</div>
<script>
$('#user').editable({
selector: 'a',
url: '/post',
pk: 1
});
</script>
**/
selector: null,
/**
Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers.
@property highlight
@type string|boolean
@since 1.4.5
@default #FFFF80
**/
highlight: '#FFFF80'
};
}(window.jQuery));
/**
AbstractInput - base class for all editable inputs.
It defines interface to be implemented by any input type.
To create your own input you can inherit from this class.
@class abstractinput
**/
(function ($) {
"use strict";
//types
$.fn.editabletypes = {};
var AbstractInput = function () { };
AbstractInput.prototype = {
/**
Initializes input
@method init()
**/
init: function(type, options, defaults) {
this.type = type;
this.options = $.extend({}, defaults, options);
},
/*
this method called before render to init $tpl that is inserted in DOM
*/
prerender: function() {
this.$tpl = $(this.options.tpl); //whole tpl as jquery object
this.$input = this.$tpl; //control itself, can be changed in render method
this.$clear = null; //clear button
this.error = null; //error message, if input cannot be rendered
},
/**
Renders input from tpl. Can return jQuery deferred object.
Can be overwritten in child objects
@method render()
**/
render: function() {
},
/**
Sets element's html by value.
@method value2html(value, element)
@param {mixed} value
@param {DOMElement} element
**/
value2html: function(value, element) {
$(element)[this.options.escape ? 'text' : 'html']($.trim(value));
},
/**
Converts element's html to value
@method html2value(html)
@param {string} html
@returns {mixed}
**/
html2value: function(html) {
return $('<div>').html(html).text();
},
/**
Converts value to string (for internal compare). For submitting to server used value2submit().
@method value2str(value)
@param {mixed} value
@returns {string}
**/
value2str: function(value) {
return value;
},
/**
Converts string received from server into value. Usually from `data-value` attribute.
@method str2value(str)
@param {string} str
@returns {mixed}
**/
str2value: function(str) {
return str;
},
/**
Converts value for submitting to server. Result can be string or object.
@method value2submit(value)
@param {mixed} value
@returns {mixed}
**/
value2submit: function(value) {
return value;
},
/**
Sets value of input.
@method value2input(value)
@param {mixed} value
**/
value2input: function(value) {
this.$input.val(value);
},
/**
Returns value of input. Value can be object (e.g. datepicker)
@method input2value()
**/
input2value: function() {
return this.$input.val();
},
/**
Activates input. For text it sets focus.
@method activate()
**/
activate: function() {
if(this.$input.is(':visible')) {
this.$input.focus();
}
},
/**
Creates input.
@method clear()
**/
clear: function() {
this.$input.val(null);
},
/**
method to escape html.
**/
escape: function(str) {
return $('<div>').text(str).html();
},
/**
attach handler to automatically submit form when value changed (useful when buttons not shown)
**/
autosubmit: function() {
},
/**
Additional actions when destroying element
**/
destroy: function() {
},
// -------- helper functions --------
setClass: function() {
if(this.options.inputclass) {
this.$input.addClass(this.options.inputclass);
}
},
setAttr: function(attr) {
if (this.options[attr] !== undefined && this.options[attr] !== null) {
this.$input.attr(attr, this.options[attr]);
}
},
option: function(key, value) {
this.options[key] = value;
}
};
AbstractInput.defaults = {
/**
HTML template of input. Normally you should not change it.
@property tpl
@type string
@default ''
**/
tpl: '',
/**
CSS class automatically applied to input
@property inputclass
@type string
@default null
**/
inputclass: null,
/**
If `true` - html will be escaped in content of element via $.text() method.
If `false` - html will not be escaped, $.html() used.
When you use own `display` function, this option obviosly has no effect.
@property escape
@type boolean
@since 1.5.0
@default true
**/
escape: true,
//scope for external methods (e.g. source defined as function)
//for internal use only
scope: null,
//need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults)
showbuttons: true
};
$.extend($.fn.editabletypes, {abstractinput: AbstractInput});
}(window.jQuery));
/**
List - abstract class for inputs that have source option loaded from js array or via ajax
@class list
@extends abstractinput
**/
(function ($) {
"use strict";
var List = function (options) {
};
$.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput);
$.extend(List.prototype, {
render: function () {
var deferred = $.Deferred();
this.error = null;
this.onSourceReady(function () {
this.renderList();
deferred.resolve();
}, function () {
this.error = this.options.sourceError;
deferred.resolve();
});
return deferred.promise();
},
html2value: function (html) {
return null; //can't set value by text
},
value2html: function (value, element, display, response) {
var deferred = $.Deferred(),
success = function () {
if(typeof display === 'function') {
//custom display method
display.call(element, value, this.sourceData, response);
} else {
this.value2htmlFinal(value, element);
}
deferred.resolve();
};
//for null value just call success without loading source
if(value === null) {
success.call(this);
} else {
this.onSourceReady(success, function () { deferred.resolve(); });
}
return deferred.promise();
},
// ------------- additional functions ------------
onSourceReady: function (success, error) {
//run source if it function
var source;
if ($.isFunction(this.options.source)) {
source = this.options.source.call(this.options.scope);
this.sourceData = null;
//note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed
} else {
source = this.options.source;
}
//if allready loaded just call success
if(this.options.sourceCache && $.isArray(this.sourceData)) {
success.call(this);
return;
}
//try parse json in single quotes (for double quotes jquery does automatically)
try {
source = $.fn.editableutils.tryParseJson(source, false);
} catch (e) {
error.call(this);
return;
}
//loading from url
if (typeof source === 'string') {
//try to get sourceData from cache
if(this.options.sourceCache) {
var cacheID = source,
cache;
if (!$(document).data(cacheID)) {
$(document).data(cacheID, {});
}
cache = $(document).data(cacheID);
//check for cached data
if (cache.loading === false && cache.sourceData) { //take source from cache
this.sourceData = cache.sourceData;
this.doPrepend();
success.call(this);
return;
} else if (cache.loading === true) { //cache is loading, put callback in stack to be called later
cache.callbacks.push($.proxy(function () {
this.sourceData = cache.sourceData;
this.doPrepend();
success.call(this);
}, this));
//also collecting error callbacks
cache.err_callbacks.push($.proxy(error, this));
return;
} else { //no cache yet, activate it
cache.loading = true;
cache.callbacks = [];
cache.err_callbacks = [];
}
}
//ajaxOptions for source. Can be overwritten bt options.sourceOptions
var ajaxOptions = $.extend({
url: source,
type: 'get',
cache: false,
dataType: 'json',
success: $.proxy(function (data) {
if(cache) {
cache.loading = false;
}
this.sourceData = this.makeArray(data);
if($.isArray(this.sourceData)) {
if(cache) {
//store result in cache
cache.sourceData = this.sourceData;
//run success callbacks for other fields waiting for this source
$.each(cache.callbacks, function () { this.call(); });
}
this.doPrepend();
success.call(this);
} else {
error.call(this);
if(cache) {
//run error callbacks for other fields waiting for this source
$.each(cache.err_callbacks, function () { this.call(); });
}
}
}, this),
error: $.proxy(function () {
error.call(this);
if(cache) {
cache.loading = false;
//run error callbacks for other fields
$.each(cache.err_callbacks, function () { this.call(); });
}
}, this)
}, this.options.sourceOptions);
//loading sourceData from server
$.ajax(ajaxOptions);
} else { //options as json/array
this.sourceData = this.makeArray(source);
if($.isArray(this.sourceData)) {
this.doPrepend();
success.call(this);
} else {
error.call(this);
}
}
},
doPrepend: function () {
if(this.options.prepend === null || this.options.prepend === undefined) {
return;
}
if(!$.isArray(this.prependData)) {
//run prepend if it is function (once)
if ($.isFunction(this.options.prepend)) {
this.options.prepend = this.options.prepend.call(this.options.scope);
}
//try parse json in single quotes
this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true);
//convert prepend from string to object
if (typeof this.options.prepend === 'string') {
this.options.prepend = {'': this.options.prepend};
}
this.prependData = this.makeArray(this.options.prepend);
}
if($.isArray(this.prependData) && $.isArray(this.sourceData)) {
this.sourceData = this.prependData.concat(this.sourceData);
}
},
/*
renders input list
*/
renderList: function() {
// this method should be overwritten in child class
},
/*
set element's html by value
*/
value2htmlFinal: function(value, element) {
// this method should be overwritten in child class
},
/**
* convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}]
*/
makeArray: function(data) {
var count, obj, result = [], item, iterateItem;
if(!data || typeof data === 'string') {
return null;
}
if($.isArray(data)) { //array
/*
function to iterate inside item of array if item is object.
Caclulates count of keys in item and store in obj.
*/
iterateItem = function (k, v) {
obj = {value: k, text: v};
if(count++ >= 2) {
return false;// exit from `each` if item has more than one key.
}
};
for(var i = 0; i < data.length; i++) {
item = data[i];
if(typeof item === 'object') {
count = 0; //count of keys inside item
$.each(item, iterateItem);
//case: [{val1: 'text1'}, {val2: 'text2} ...]
if(count === 1) {
result.push(obj);
//case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...]
} else if(count > 1) {
//removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text')
if(item.children) {
item.children = this.makeArray(item.children);
}
result.push(item);
}
} else {
//case: ['text1', 'text2' ...]
result.push({value: item, text: item});
}
}
} else { //case: {val1: 'text1', val2: 'text2, ...}
$.each(data, function (k, v) {
result.push({value: k, text: v});
});
}
return result;
},
option: function(key, value) {
this.options[key] = value;
if(key === 'source') {
this.sourceData = null;
}
if(key === 'prepend') {
this.prependData = null;
}
}
});
List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
Source data for list.
If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]`
For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order.
If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option.
If **function**, it should return data in format above (since 1.4.0).
Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only):
@example
[
{text: "group1", children: [
{value: 1, text: "text1"},
{value: 2, text: "text2"}
]},
...
]
@property source
@type string | array | object | function
@default null
**/
source: null,
/**
Data automatically prepended to the beginning of dropdown list.
@property prepend
@type string | array | object | function
@default false
**/
prepend: false,
/**
Error message when list cannot be loaded (e.g. ajax error)
@property sourceError
@type string
@default Error when loading list
**/
sourceError: 'Error when loading list',
/**
if `true` and source is **string url** - results will be cached for fields with the same source.
Usefull for editable column in grid to prevent extra requests.
@property sourceCache
@type boolean
@default true
@since 1.2.0
**/
sourceCache: true,
/**
Additional ajax options to be used in $.ajax() when loading list from server.
Useful to send extra parameters or change request method.
@property sourceOptions
@type object|function
@default null
@since 1.5.0
@example
sourceOptions: {
data: {param: 123},
type: 'post'
}
**/
sourceOptions: null
});
$.fn.editabletypes.list = List;
}(window.jQuery));
/**
Text input
@class text
@extends abstractinput
@final
@example
<a href="#" id="username" data-type="text" data-pk="1">awesome</a>
<script>
$(function(){
$('#username').editable({
url: '/post',
title: 'Enter username'
});
});
</script>
**/
(function ($) {
"use strict";
var Text = function (options) {
this.init('text', options, Text.defaults);
};
$.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput);
$.extend(Text.prototype, {
render: function() {
this.renderClear();
this.setClass();
this.setAttr('placeholder');
},
activate: function() {
if(this.$input.is(':visible')) {
this.$input.focus();
if (this.$input.is('input,textarea') && !this.$input.is('[type="checkbox"],[type="range"]')) {
$.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length);
}
if(this.toggleClear) {
this.toggleClear();
}
}
},
//render clear button
renderClear: function() {
if (this.options.clear) {
this.$clear = $('<span class="editable-clear-x"></span>');
this.$input.after(this.$clear)
.css('padding-right', 24)
.keyup($.proxy(function(e) {
//arrows, enter, tab, etc
if(~$.inArray(e.keyCode, [40,38,9,13,27])) {
return;
}
clearTimeout(this.t);
var that = this;
this.t = setTimeout(function() {
that.toggleClear(e);
}, 100);
}, this))
.parent().css('position', 'relative');
this.$clear.click($.proxy(this.clear, this));
}
},
postrender: function() {
/*
//now `clear` is positioned via css
if(this.$clear) {
//can position clear button only here, when form is shown and height can be calculated
// var h = this.$input.outerHeight(true) || 20,
var h = this.$clear.parent().height(),
delta = (h - this.$clear.height()) / 2;
//this.$clear.css({bottom: delta, right: delta});
}
*/
},
//show / hide clear button
toggleClear: function(e) {
if(!this.$clear) {
return;
}
var len = this.$input.val().length,
visible = this.$clear.is(':visible');
if(len && !visible) {
this.$clear.show();
}
if(!len && visible) {
this.$clear.hide();
}
},
clear: function() {
this.$clear.hide();
this.$input.val('').focus();
}
});
Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <input type="text">
**/
tpl: '<input type="text">',
/**
Placeholder attribute of input. Shown when input is empty.
@property placeholder
@type string
@default null
**/
placeholder: null,
/**
Whether to show `clear` button
@property clear
@type boolean
@default true
**/
clear: true
});
$.fn.editabletypes.text = Text;
}(window.jQuery));
/**
Textarea input
@class textarea
@extends abstractinput
@final
@example
<a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a>
<script>
$(function(){
$('#comments').editable({
url: '/post',
title: 'Enter comments',
rows: 10
});
});
</script>
**/
(function ($) {
"use strict";
var Textarea = function (options) {
this.init('textarea', options, Textarea.defaults);
};
$.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput);
$.extend(Textarea.prototype, {
render: function () {
this.setClass();
this.setAttr('placeholder');
this.setAttr('rows');
//ctrl + enter
this.$input.keydown(function (e) {
if (e.ctrlKey && e.which === 13) {
$(this).closest('form').submit();
}
});
},
//using `white-space: pre-wrap` solves \n <--> BR conversion very elegant!
/*
value2html: function(value, element) {
var html = '', lines;
if(value) {
lines = value.split("\n");
for (var i = 0; i < lines.length; i++) {
lines[i] = $('<div>').text(lines[i]).html();
}
html = lines.join('<br>');
}
$(element).html(html);
},
html2value: function(html) {
if(!html) {
return '';
}
var regex = new RegExp(String.fromCharCode(10), 'g');
var lines = html.split(/<br\s*\/?>/i);
for (var i = 0; i < lines.length; i++) {
var text = $('<div>').html(lines[i]).text();
// Remove newline characters (\n) to avoid them being converted by value2html() method
// thus adding extra <br> tags
text = text.replace(regex, '');
lines[i] = text;
}
return lines.join("\n");
},
*/
activate: function() {
$.fn.editabletypes.text.prototype.activate.call(this);
}
});
Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <textarea></textarea>
**/
tpl:'<textarea></textarea>',
/**
@property inputclass
@default input-large
**/
inputclass: 'input-large',
/**
Placeholder attribute of input. Shown when input is empty.
@property placeholder
@type string
@default null
**/
placeholder: null,
/**
Number of rows in textarea
@property rows
@type integer
@default 7
**/
rows: 7
});
$.fn.editabletypes.textarea = Textarea;
}(window.jQuery));
/**
Select (dropdown)
@class select
@extends list
@final
@example
<a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a>
<script>
$(function(){
$('#status').editable({
value: 2,
source: [
{value: 1, text: 'Active'},
{value: 2, text: 'Blocked'},
{value: 3, text: 'Deleted'}
]
});
});
</script>
**/
(function ($) {
"use strict";
var Select = function (options) {
this.init('select', options, Select.defaults);
};
$.fn.editableutils.inherit(Select, $.fn.editabletypes.list);
$.extend(Select.prototype, {
renderList: function() {
this.$input.empty();
var escape = this.options.escape;
var fillItems = function($el, data) {
var attr;
if($.isArray(data)) {
for(var i=0; i<data.length; i++) {
attr = {};
if(data[i].children) {
attr.label = data[i].text;
$el.append(fillItems($('<optgroup>', attr), data[i].children));
} else {
attr.value = data[i].value;
if(data[i].disabled) {
attr.disabled = true;
}
var $option = $('<option>', attr);
$option[escape ? 'text' : 'html'](data[i].text);
$el.append($option);
}
}
}
return $el;
};
fillItems(this.$input, this.sourceData);
this.setClass();
//enter submit
this.$input.on('keydown.editable', function (e) {
if (e.which === 13) {
$(this).closest('form').submit();
}
});
},
value2htmlFinal: function(value, element) {
var text = '',
items = $.fn.editableutils.itemsByValue(value, this.sourceData);
if(items.length) {
text = items[0].text;
}
//$(element).text(text);
$.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element);
},
autosubmit: function() {
this.$input.off('keydown.editable').on('change.editable', function(){
$(this).closest('form').submit();
});
}
});
Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, {
/**
@property tpl
@default <select></select>
**/
tpl:'<select></select>'
});
$.fn.editabletypes.select = Select;
}(window.jQuery));
/**
List of checkboxes.
Internally value stored as javascript array of values.
@class checklist
@extends list
@final
@example
<a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a>
<script>
$(function(){
$('#options').editable({
value: [2, 3],
source: [
{value: 1, text: 'option1'},
{value: 2, text: 'option2'},
{value: 3, text: 'option3'}
]
});
});
</script>
**/
(function ($) {
"use strict";
var Checklist = function (options) {
this.init('checklist', options, Checklist.defaults);
};
$.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list);
$.extend(Checklist.prototype, {
renderList: function() {
var $label, $div;
this.$tpl.empty();
if(!$.isArray(this.sourceData)) {
return;
}
for(var i=0; i<this.sourceData.length; i++) {
$label = $('<label>').append($('<input>', {
type: 'checkbox',
value: this.sourceData[i].value
}));
var $option = $('<span>');
$option[this.options.escape ? 'text' : 'html'](' '+this.sourceData[i].text);
$label.append($option);
$('<div>').append($label).appendTo(this.$tpl);
}
this.$input = this.$tpl.find('input[type="checkbox"]');
this.setClass();
},
value2str: function(value) {
return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : '';
},
//parse separated string
str2value: function(str) {
var reg, value = null;
if(typeof str === 'string' && str.length) {
reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*');
value = str.split(reg);
} else if($.isArray(str)) {
value = str;
} else {
value = [str];
}
return value;
},
//set checked on required checkboxes
value2input: function(value) {
this.$input.prop('checked', false);
if($.isArray(value) && value.length) {
this.$input.each(function(i, el) {
var $el = $(el);
// cannot use $.inArray as it performs strict comparison
$.each(value, function(j, val){
/*jslint eqeq: true*/
if($el.val() == val) {
/*jslint eqeq: false*/
$el.prop('checked', true);
}
});
});
}
},
input2value: function() {
var checked = [];
this.$input.filter(':checked').each(function(i, el) {
checked.push($(el).val());
});
return checked;
},
//collect text of checked boxes
value2htmlFinal: function(value, element) {
var html = [],
checked = $.fn.editableutils.itemsByValue(value, this.sourceData),
escape = this.options.escape;
if(checked.length) {
$.each(checked, function(i, v) {
var text = escape ? $.fn.editableutils.escape(v.text) : v.text;
html.push(text);
});
$(element).html(html.join('<br>'));
} else {
$(element).empty();
}
},
activate: function() {
this.$input.first().focus();
},
autosubmit: function() {
this.$input.on('keydown', function(e){
if (e.which === 13) {
$(this).closest('form').submit();
}
});
}
});
Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, {
/**
@property tpl
@default <div></div>
**/
tpl:'<div class="editable-checklist"></div>',
/**
@property inputclass
@type string
@default null
**/
inputclass: null,
/**
Separator of values when reading from `data-value` attribute
@property separator
@type string
@default ','
**/
separator: ','
});
$.fn.editabletypes.checklist = Checklist;
}(window.jQuery));
/**
HTML5 input types.
Following types are supported:
* password
* email
* url
* tel
* number
* range
* time
Learn more about html5 inputs:
http://www.w3.org/wiki/HTML5_form_additions
To check browser compatibility please see:
https://developer.mozilla.org/en-US/docs/HTML/Element/Input
@class html5types
@extends text
@final
@since 1.3.0
@example
<a href="#" id="email" data-type="email" data-pk="1">admin@example.com</a>
<script>
$(function(){
$('#email').editable({
url: '/post',
title: 'Enter email'
});
});
</script>
**/
/**
@property tpl
@default depends on type
**/
/*
Password
*/
(function ($) {
"use strict";
var Password = function (options) {
this.init('password', options, Password.defaults);
};
$.fn.editableutils.inherit(Password, $.fn.editabletypes.text);
$.extend(Password.prototype, {
//do not display password, show '[hidden]' instead
value2html: function(value, element) {
if(value) {
$(element).text('[hidden]');
} else {
$(element).empty();
}
},
//as password not displayed, should not set value by html
html2value: function(html) {
return null;
}
});
Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="password">'
});
$.fn.editabletypes.password = Password;
}(window.jQuery));
/*
Email
*/
(function ($) {
"use strict";
var Email = function (options) {
this.init('email', options, Email.defaults);
};
$.fn.editableutils.inherit(Email, $.fn.editabletypes.text);
Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="email">'
});
$.fn.editabletypes.email = Email;
}(window.jQuery));
/*
Url
*/
(function ($) {
"use strict";
var Url = function (options) {
this.init('url', options, Url.defaults);
};
$.fn.editableutils.inherit(Url, $.fn.editabletypes.text);
Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="url">'
});
$.fn.editabletypes.url = Url;
}(window.jQuery));
/*
Tel
*/
(function ($) {
"use strict";
var Tel = function (options) {
this.init('tel', options, Tel.defaults);
};
$.fn.editableutils.inherit(Tel, $.fn.editabletypes.text);
Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="tel">'
});
$.fn.editabletypes.tel = Tel;
}(window.jQuery));
/*
Number
*/
(function ($) {
"use strict";
var NumberInput = function (options) {
this.init('number', options, NumberInput.defaults);
};
$.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text);
$.extend(NumberInput.prototype, {
render: function () {
NumberInput.superclass.render.call(this);
this.setAttr('min');
this.setAttr('max');
this.setAttr('step');
},
postrender: function() {
if(this.$clear) {
//increase right ffset for up/down arrows
this.$clear.css({right: 24});
/*
//can position clear button only here, when form is shown and height can be calculated
var h = this.$input.outerHeight(true) || 20,
delta = (h - this.$clear.height()) / 2;
//add 12px to offset right for up/down arrows
this.$clear.css({top: delta, right: delta + 16});
*/
}
}
});
NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="number">',
inputclass: 'input-mini',
min: null,
max: null,
step: null
});
$.fn.editabletypes.number = NumberInput;
}(window.jQuery));
/*
Range (inherit from number)
*/
(function ($) {
"use strict";
var Range = function (options) {
this.init('range', options, Range.defaults);
};
$.fn.editableutils.inherit(Range, $.fn.editabletypes.number);
$.extend(Range.prototype, {
render: function () {
this.$input = this.$tpl.filter('input');
this.setClass();
this.setAttr('min');
this.setAttr('max');
this.setAttr('step');
this.$input.on('input', function(){
$(this).siblings('output').text($(this).val());
});
},
activate: function() {
this.$input.focus();
}
});
Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, {
tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>',
inputclass: 'input-medium'
});
$.fn.editabletypes.range = Range;
}(window.jQuery));
/*
Time
*/
(function ($) {
"use strict";
var Time = function (options) {
this.init('time', options, Time.defaults);
};
//inherit from abstract, as inheritance from text gives selection error.
$.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput);
$.extend(Time.prototype, {
render: function() {
this.setClass();
}
});
Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
tpl: '<input type="time">'
});
$.fn.editabletypes.time = Time;
}(window.jQuery));
/**
Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2.
Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options.
You should manually download and include select2 distributive:
<link href="select2/select2.css" rel="stylesheet" type="text/css"></link>
<script src="select2/select2.js"></script>
To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css):
<link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link>
**Note:** currently `autotext` feature does not work for select2 with `ajax` remote source.
You need initially put both `data-value` and element's text youself:
<a href="#" data-type="select2" data-value="1">Text1</a>
@class select2
@extends abstractinput
@since 1.4.1
@final
@example
<a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a>
<script>
$(function(){
//local source
$('#country').editable({
source: [
{id: 'gb', text: 'Great Britain'},
{id: 'us', text: 'United States'},
{id: 'ru', text: 'Russia'}
],
select2: {
multiple: true
}
});
//remote source (simple)
$('#country').editable({
source: '/getCountries',
select2: {
placeholder: 'Select Country',
minimumInputLength: 1
}
});
//remote source (advanced)
$('#country').editable({
select2: {
placeholder: 'Select Country',
allowClear: true,
minimumInputLength: 3,
id: function (item) {
return item.CountryId;
},
ajax: {
url: '/getCountries',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},
formatResult: function (item) {
return item.CountryName;
},
formatSelection: function (item) {
return item.CountryName;
},
initSelection: function (element, callback) {
return $.get('/getCountryById', { query: element.val() }, function (data) {
callback(data);
});
}
}
});
});
</script>
**/
(function ($) {
"use strict";
var Constructor = function (options) {
this.init('select2', options, Constructor.defaults);
options.select2 = options.select2 || {};
this.sourceData = null;
//placeholder
if(options.placeholder) {
options.select2.placeholder = options.placeholder;
}
//if not `tags` mode, use source
if(!options.select2.tags && options.source) {
var source = options.source;
//if source is function, call it (once!)
if ($.isFunction(options.source)) {
source = options.source.call(options.scope);
}
if (typeof source === 'string') {
options.select2.ajax = options.select2.ajax || {};
// default ajax params
if(!options.select2.ajax.dataType) {
options.select2.ajax.dataType = 'json';
}
if(!options.select2.ajax.data) {
options.select2.ajax.data = function(term) {
return {
query:term
};
};
}
if(!options.select2.ajax.processResults) {
options.select2.ajax.processResults = function(data) { return {results:data };};
}
options.select2.ajax.url = source;
} else {
//check format and convert x-editable format to select2 format (if needed)
this.sourceData = this.convertSource(source);
options.select2.data = this.sourceData;
}
}
//overriding objects in config (as by default jQuery extend() is not recursive)
this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2);
//detect whether it is multi-valued
this.isMultiple = this.options.select2.tags || this.options.select2.multiple;
this.isRemote = ('ajax' in this.options.select2);
//store function returning ID of item
//should be here as used inautotext for local source
this.idFunc = this.options.select2.id;
if (typeof(this.idFunc) !== "function") {
var idKey = this.idFunc || 'id';
this.idFunc = function (e) { return e[idKey]; };
}
//store function that renders text in select2
this.formatSelection = this.options.select2.formatSelection;
if (typeof(this.formatSelection) !== "function") {
this.formatSelection = function (e) { return e.text; };
}
};
$.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput);
$.extend(Constructor.prototype, {
render: function() {
this.setClass();
//can not apply select2 here as it calls initSelection
//over input that does not have correct value yet.
//apply select2 only in value2input
//this.$input.select2(this.options.select2);
//when data is loaded via ajax, we need to know when it's done to populate listData
if(this.isRemote) {
//listen to loaded event to populate data
this.$input.on('select2-loaded', $.proxy(function(e) {
this.sourceData = e.items.results;
}, this));
}
//trigger resize of editableform to re-position container in multi-valued mode
if(this.isMultiple) {
this.$input.on('change', function() {
$(this).closest('form').parent().triggerHandler('resize');
});
}
},
value2html: function(value, element) {
var text = '', data,
that = this;
if(this.options.select2.tags) { //in tags mode just assign value
data = value;
//data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc);
} else if(this.sourceData) {
data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc);
} else {
//can not get list of possible values
//(e.g. autotext for select2 with ajax source)
}
//data may be array (when multiple values allowed)
if($.isArray(data)) {
//collect selected data and show with separator
text = [];
$.each(data, function(k, v){
text.push(v && typeof v === 'object' ? that.formatSelection(v) : v);
});
} else if(data) {
text = that.formatSelection(data);
}
text = $.isArray(text) ? text.join(this.options.viewseparator) : text;
//$(element).text(text);
Constructor.superclass.value2html.call(this, text, element);
},
html2value: function(html) {
return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null;
},
value2input: function(value) {
// if value array => join it anyway
if($.isArray(value)) {
value = value.join(this.getSeparator());
}
//for remote source just set value, text is updated by initSelection
if(!this.$input.data('select2')) {
this.$input.val(value);
this.$input.select2(this.options.select2);
} else {
//second argument needed to separate initial change from user's click (for autosubmit)
this.$input.val(value).trigger('change', true);
//Uncaught Error: cannot call val() if initSelection() is not defined
//this.$input.select2('val', value);
}
// if defined remote source AND no multiple mode AND no user's initSelection provided -->
// we should somehow get text for provided id.
// The solution is to use element's text as text for that id (exclude empty)
if(this.isRemote && !this.isMultiple && !this.options.select2.initSelection) {
// customId and customText are methods to extract `id` and `text` from data object
// we can use this workaround only if user did not define these methods
// otherwise we cant construct data object
var customId = this.options.select2.id,
customText = this.options.select2.formatSelection;
if(!customId && !customText) {
var $el = $(this.options.scope);
if (!$el.data('editable').isEmpty) {
var data = {id: value, text: $el.text()};
this.$input.select2('data', data);
}
}
}
},
input2value: function() {
return this.$input.select2('val');
},
str2value: function(str, separator) {
if(typeof str !== 'string' || !this.isMultiple) {
return str;
}
separator = separator || this.getSeparator();
var val, i, l;
if (str === null || str.length < 1) {
return null;
}
val = str.split(separator);
for (i = 0, l = val.length; i < l; i = i + 1) {
val[i] = $.trim(val[i]);
}
return val;
},
autosubmit: function() {
this.$input.on('change', function(e, isInitial){
if(!isInitial) {
$(this).closest('form').submit();
}
});
},
getSeparator: function() {
return this.options.select2.separator || $.fn.select2.defaults.separator;
},
/*
Converts source from x-editable format: {value: 1, text: "1"} to
select2 format: {id: 1, text: "1"}
*/
convertSource: function(source) {
if($.isArray(source) && source.length && source[0].value !== undefined) {
for(var i = 0; i<source.length; i++) {
if(source[i].value !== undefined) {
source[i].id = source[i].value;
delete source[i].value;
}
}
}
return source;
},
destroy: function() {
if(this.$input.data('select2')) {
this.$input.select2('destroy');
}
}
});
Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <input type="hidden">
**/
tpl:'<input type="hidden">',
/**
Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2).
@property select2
@type object
@default null
**/
select2: null,
/**
Placeholder attribute of select
@property placeholder
@type string
@default null
**/
placeholder: null,
/**
Source data for select. It will be assigned to select2 `data` property and kept here just for convenience.
Please note, that format is different from simple `select` input: use 'id' instead of 'value'.
E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`.
@property source
@type array|string|function
@default null
**/
source: null,
/**
Separator used to display tags.
@property viewseparator
@type string
@default ', '
**/
viewseparator: ', '
});
$.fn.editabletypes.select2 = Constructor;
}(window.jQuery));
/**
* Combodate - 1.0.5
* Dropdown date and time picker.
* Converts text input into dropdowns to pick day, month, year, hour, minute and second.
* Uses momentjs as datetime library http://momentjs.com.
* For i18n include corresponding file from https://github.com/timrwood/moment/tree/master/lang
*
* Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight
* In combodate:
* 12:00 pm --> 12:00 (24-h format, midday)
* 12:00 am --> 00:00 (24-h format, midnight, start of day)
*
* Differs from momentjs parse rules:
* 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change)
* 00:00 am, 12:00 am --> 00:00 (24-h format, day not change)
*
*
* Author: Vitaliy Potapov
* Project page: http://github.com/vitalets/combodate
* Copyright (c) 2012 Vitaliy Potapov. Released under MIT License.
**/
(function ($) {
var Combodate = function (element, options) {
this.$element = $(element);
if(!this.$element.is('input')) {
$.error('Combodate should be applied to INPUT element');
return;
}
this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data());
this.init();
};
Combodate.prototype = {
constructor: Combodate,
init: function () {
this.map = {
//key regexp moment.method
day: ['D', 'date'],
month: ['M', 'month'],
year: ['Y', 'year'],
hour: ['[Hh]', 'hours'],
minute: ['m', 'minutes'],
second: ['s', 'seconds'],
ampm: ['[Aa]', '']
};
this.$widget = $('<span class="combodate"></span>').html(this.getTemplate());
this.initCombos();
//update original input on change
this.$widget.on('change', 'select', $.proxy(function(e) {
this.$element.val(this.getValue()).change();
// update days count if month or year changes
if (this.options.smartDays) {
if ($(e.target).is('.month') || $(e.target).is('.year')) {
this.fillCombo('day');
}
}
}, this));
this.$widget.find('select').css('width', 'auto');
// hide original input and insert widget
this.$element.hide().after(this.$widget);
// set initial value
this.setValue(this.$element.val() || this.options.value);
},
/*
Replace tokens in template with <select> elements
*/
getTemplate: function() {
var tpl = this.options.template;
//first pass
$.each(this.map, function(k, v) {
v = v[0];
var r = new RegExp(v+'+'),
token = v.length > 1 ? v.substring(1, 2) : v;
tpl = tpl.replace(r, '{'+token+'}');
});
//replace spaces with
tpl = tpl.replace(/ /g, ' ');
//second pass
$.each(this.map, function(k, v) {
v = v[0];
var token = v.length > 1 ? v.substring(1, 2) : v;
tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>');
});
return tpl;
},
/*
Initialize combos that presents in template
*/
initCombos: function() {
for (var k in this.map) {
var $c = this.$widget.find('.'+k);
// set properties like this.$day, this.$month etc.
this['$'+k] = $c.length ? $c : null;
// fill with items
this.fillCombo(k);
}
},
/*
Fill combo with items
*/
fillCombo: function(k) {
var $combo = this['$'+k];
if (!$combo) {
return;
}
// define method name to fill items, e.g `fillDays`
var f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1);
var items = this[f]();
var value = $combo.val();
$combo.empty();
for(var i=0; i<items.length; i++) {
$combo.append('<option value="'+items[i][0]+'">'+items[i][1]+'</option>');
}
$combo.val(value);
},
/*
Initialize items of combos. Handles `firstItem` option
*/
fillCommon: function(key) {
var values = [],
relTime;
if(this.options.firstItem === 'name') {
//need both to support moment ver < 2 and >= 2
relTime = moment.relativeTime || moment.langData()._relativeTime;
var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key];
//take last entry (see momentjs lang files structure)
header = header.split(' ').reverse()[0];
values.push(['', header]);
} else if(this.options.firstItem === 'empty') {
values.push(['', '']);
}
return values;
},
/*
fill day
*/
fillDay: function() {
var items = this.fillCommon('d'), name, i,
twoDigit = this.options.template.indexOf('DD') !== -1,
daysCount = 31;
// detect days count (depends on month and year)
// originally https://github.com/vitalets/combodate/pull/7
if (this.options.smartDays && this.$month && this.$year) {
var month = parseInt(this.$month.val(), 10);
var year = parseInt(this.$year.val(), 10);
if (!isNaN(month) && !isNaN(year)) {
daysCount = moment([year, month]).daysInMonth();
}
}
for (i = 1; i <= daysCount; i++) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill month
*/
fillMonth: function() {
var items = this.fillCommon('M'), name, i,
longNames = this.options.template.indexOf('MMMM') !== -1,
shortNames = this.options.template.indexOf('MMM') !== -1,
twoDigit = this.options.template.indexOf('MM') !== -1;
for(i=0; i<=11; i++) {
if(longNames) {
//see https://github.com/timrwood/momentjs.com/pull/36
name = moment().date(1).month(i).format('MMMM');
} else if(shortNames) {
name = moment().date(1).month(i).format('MMM');
} else if(twoDigit) {
name = this.leadZero(i+1);
} else {
name = i+1;
}
items.push([i, name]);
}
return items;
},
/*
fill year
*/
fillYear: function() {
var items = [], name, i,
longNames = this.options.template.indexOf('YYYY') !== -1;
for(i=this.options.maxYear; i>=this.options.minYear; i--) {
name = longNames ? i : (i+'').substring(2);
items[this.options.yearDescending ? 'push' : 'unshift']([i, name]);
}
items = this.fillCommon('y').concat(items);
return items;
},
/*
fill hour
*/
fillHour: function() {
var items = this.fillCommon('h'), name, i,
h12 = this.options.template.indexOf('h') !== -1,
h24 = this.options.template.indexOf('H') !== -1,
twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1,
min = h12 ? 1 : 0,
max = h12 ? 12 : 23;
for(i=min; i<=max; i++) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill minute
*/
fillMinute: function() {
var items = this.fillCommon('m'), name, i,
twoDigit = this.options.template.indexOf('mm') !== -1;
for(i=0; i<=59; i+= this.options.minuteStep) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill second
*/
fillSecond: function() {
var items = this.fillCommon('s'), name, i,
twoDigit = this.options.template.indexOf('ss') !== -1;
for(i=0; i<=59; i+= this.options.secondStep) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill ampm
*/
fillAmpm: function() {
var ampmL = this.options.template.indexOf('a') !== -1,
ampmU = this.options.template.indexOf('A') !== -1,
items = [
['am', ampmL ? 'am' : 'AM'],
['pm', ampmL ? 'pm' : 'PM']
];
return items;
},
/*
Returns current date value from combos.
If format not specified - `options.format` used.
If format = `null` - Moment object returned.
*/
getValue: function(format) {
var dt, values = {},
that = this,
notSelected = false;
//getting selected values
$.each(this.map, function(k, v) {
if(k === 'ampm') {
return;
}
var def = k === 'day' ? 1 : 0;
values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def;
if(isNaN(values[k])) {
notSelected = true;
return false;
}
});
//if at least one visible combo not selected - return empty string
if(notSelected) {
return '';
}
//convert hours 12h --> 24h
if(this.$ampm) {
//12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
if(values.hour === 12) {
values.hour = this.$ampm.val() === 'am' ? 0 : 12;
} else {
values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12;
}
}
dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]);
//highlight invalid date
this.highlight(dt);
format = format === undefined ? this.options.format : format;
if(format === null) {
return dt.isValid() ? dt : null;
} else {
return dt.isValid() ? dt.format(format) : '';
}
},
setValue: function(value) {
if(!value) {
return;
}
var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value),
that = this,
values = {};
//function to find nearest value in select options
function getNearest($select, value) {
var delta = {};
$select.children('option').each(function(i, opt){
var optValue = $(opt).attr('value'),
distance;
if(optValue === '') return;
distance = Math.abs(optValue - value);
if(typeof delta.distance === 'undefined' || distance < delta.distance) {
delta = {value: optValue, distance: distance};
}
});
return delta.value;
}
if(dt.isValid()) {
//read values from date object
$.each(this.map, function(k, v) {
if(k === 'ampm') {
return;
}
values[k] = dt[v[1]]();
});
if(this.$ampm) {
//12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
if(values.hour >= 12) {
values.ampm = 'pm';
if(values.hour > 12) {
values.hour -= 12;
}
} else {
values.ampm = 'am';
if(values.hour === 0) {
values.hour = 12;
}
}
}
$.each(values, function(k, v) {
//call val() for each existing combo, e.g. this.$hour.val()
if(that['$'+k]) {
if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) {
v = getNearest(that['$'+k], v);
}
if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) {
v = getNearest(that['$'+k], v);
}
that['$'+k].val(v);
}
});
// update days count
if (this.options.smartDays) {
this.fillCombo('day');
}
this.$element.val(dt.format(this.options.format)).change();
}
},
/*
highlight combos if date is invalid
*/
highlight: function(dt) {
if(!dt.isValid()) {
if(this.options.errorClass) {
this.$widget.addClass(this.options.errorClass);
} else {
//store original border color
if(!this.borderColor) {
this.borderColor = this.$widget.find('select').css('border-color');
}
this.$widget.find('select').css('border-color', 'red');
}
} else {
if(this.options.errorClass) {
this.$widget.removeClass(this.options.errorClass);
} else {
this.$widget.find('select').css('border-color', this.borderColor);
}
}
},
leadZero: function(v) {
return v <= 9 ? '0' + v : v;
},
destroy: function() {
this.$widget.remove();
this.$element.removeData('combodate').show();
}
//todo: clear method
};
$.fn.combodate = function ( option ) {
var d, args = Array.apply(null, arguments);
args.shift();
//getValue returns date as string / object (not jQuery object)
if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) {
return d.getValue.apply(d, args);
}
return this.each(function () {
var $this = $(this),
data = $this.data('combodate'),
options = typeof option == 'object' && option;
if (!data) {
$this.data('combodate', (data = new Combodate(this, options)));
}
if (typeof option == 'string' && typeof data[option] == 'function') {
data[option].apply(data, args);
}
});
};
$.fn.combodate.defaults = {
//in this format value stored in original input
format: 'DD-MM-YYYY HH:mm',
//in this format items in dropdowns are displayed
template: 'D / MMM / YYYY H : mm',
//initial value, can be `new Date()`
value: null,
minYear: 1970,
maxYear: new Date().getFullYear(),
yearDescending: true,
minuteStep: 5,
secondStep: 1,
firstItem: 'empty', //'name', 'empty', 'none'
errorClass: null,
roundTime: true, // whether to round minutes and seconds if step > 1
smartDays: false // whether days in combo depend on selected month: 31, 30, 28
};
}(window.jQuery));
/**
Combodate input - dropdown date and time picker.
Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com).
<script src="js/moment.min.js"></script>
Allows to input:
* only date
* only time
* both date and time
Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker.
Internally value stored as `momentjs` object.
@class combodate
@extends abstractinput
@final
@since 1.4.0
@example
<a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a>
<script>
$(function(){
$('#dob').editable({
format: 'YYYY-MM-DD',
viewformat: 'DD.MM.YYYY',
template: 'D / MMMM / YYYY',
combodate: {
minYear: 2000,
maxYear: new Date().getFullYear(),
minuteStep: 1
}
}
});
});
</script>
**/
/*global moment*/
(function ($) {
"use strict";
var Constructor = function (options) {
this.init('combodate', options, Constructor.defaults);
//by default viewformat equals to format
if(!this.options.viewformat) {
this.options.viewformat = this.options.format;
}
//try parse combodate config defined as json string in data-combodate
options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true);
//overriding combodate config (as by default jQuery extend() is not recursive)
this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, {
format: this.options.format,
template: this.options.template
});
};
$.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput);
$.extend(Constructor.prototype, {
render: function () {
this.$input.combodate(this.options.combodate);
if($.fn.editableform.engine === 'bs3') {
this.$input.siblings().find('select').addClass('form-control');
}
if(this.options.inputclass) {
this.$input.siblings().find('select').addClass(this.options.inputclass);
}
//"clear" link
/*
if(this.options.clear) {
this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
e.preventDefault();
e.stopPropagation();
this.clear();
}, this));
this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));
}
*/
},
value2html: function(value, element) {
var text = value ? value.format(this.options.viewformat) : '';
//$(element).text(text);
Constructor.superclass.value2html.call(this, text, element);
},
html2value: function(html) {
return html ? moment(html, this.options.viewformat) : null;
},
value2str: function(value) {
return value ? value.format(this.options.format) : '';
},
str2value: function(str) {
return str ? moment(str, this.options.format) : null;
},
value2submit: function(value) {
return this.value2str(value);
},
value2input: function(value) {
this.$input.combodate('setValue', value);
},
input2value: function() {
return this.$input.combodate('getValue', null);
},
activate: function() {
this.$input.siblings('.combodate').find('select').eq(0).focus();
},
/*
clear: function() {
this.$input.data('datepicker').date = null;
this.$input.find('.active').removeClass('active');
},
*/
autosubmit: function() {
}
});
Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <input type="text">
**/
tpl:'<input type="text">',
/**
@property inputclass
@default null
**/
inputclass: null,
/**
Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format)
@property format
@type string
@default YYYY-MM-DD
**/
format:'YYYY-MM-DD',
/**
Format used for displaying date. Also applied when converting date from element's text on init.
If not specified equals to `format`.
@property viewformat
@type string
@default null
**/
viewformat: null,
/**
Template used for displaying dropdowns.
@property template
@type string
@default D / MMM / YYYY
**/
template: 'D / MMM / YYYY',
/**
Configuration of combodate.
Full list of options: http://vitalets.github.com/combodate/#docs
@property combodate
@type object
@default null
**/
combodate: null
/*
(not implemented yet)
Text shown as clear date button.
If <code>false</code> clear button will not be rendered.
@property clear
@type boolean|string
@default 'x clear'
*/
//clear: '× clear'
});
$.fn.editabletypes.combodate = Constructor;
}(window.jQuery));
/*
Editableform based on Twitter Bootstrap 3
*/
(function ($) {
"use strict";
//store parent methods
var pInitInput = $.fn.editableform.Constructor.prototype.initInput;
$.extend($.fn.editableform.Constructor.prototype, {
initTemplate: function() {
this.$form = $($.fn.editableform.template);
this.$form.find('.control-group').addClass('form-group');
this.$form.find('.editable-error-block').addClass('help-block');
},
initInput: function() {
pInitInput.apply(this);
//for bs3 set default class `input-sm` to standard inputs
var emptyInputClass = this.input.options.inputclass === null || this.input.options.inputclass === false;
var defaultClass = 'input-sm';
//bs3 add `form-control` class to standard inputs
var stdtypes = 'text,select,textarea,password,email,url,tel,number,range,time,typeaheadjs'.split(',');
if(~$.inArray(this.input.type, stdtypes)) {
this.input.$input.addClass('form-control');
if(emptyInputClass) {
this.input.options.inputclass = defaultClass;
this.input.$input.addClass(defaultClass);
}
}
//apply bs3 size class also to buttons (to fit size of control)
var $btn = this.$form.find('.editable-buttons');
var classes = emptyInputClass ? [defaultClass] : this.input.options.inputclass.split(' ');
for(var i=0; i<classes.length; i++) {
// `btn-sm` is default now
/*
if(classes[i].toLowerCase() === 'input-sm') {
$btn.find('button').addClass('btn-sm');
}
*/
if(classes[i].toLowerCase() === 'input-lg') {
$btn.find('button').removeClass('btn-sm').addClass('btn-lg');
}
}
}
});
//buttons
$.fn.editableform.buttons =
'<button type="submit" class="btn btn-primary btn-sm editable-submit">'+
'<i class="glyphicon glyphicon-ok"></i>'+
'</button>'+
'<button type="button" class="btn btn-default btn-sm editable-cancel">'+
'<i class="glyphicon glyphicon-remove"></i>'+
'</button>';
//error classes
$.fn.editableform.errorGroupClass = 'has-error';
$.fn.editableform.errorBlockClass = null;
//engine
$.fn.editableform.engine = 'bs3';
}(window.jQuery));
/**
* Editable Popover3 (for Bootstrap 3)
* ---------------------
* requires bootstrap-popover.js
*/
(function ($) {
"use strict";
//extend methods
$.extend($.fn.editableContainer.Popup.prototype, {
containerName: 'popover',
containerDataName: 'bs.popover',
innerCss: '.popover-content',
defaults: $.fn.popover.Constructor.DEFAULTS,
initContainer: function(){
$.extend(this.containerOptions, {
trigger: 'manual',
selector: false,
content: ' ',
template: this.defaults.template
});
//as template property is used in inputs, hide it from popover
var t;
if(this.$element.data('template')) {
t = this.$element.data('template');
this.$element.removeData('template');
}
this.call(this.containerOptions);
if(t) {
//restore data('template')
this.$element.data('template', t);
}
},
/* show */
innerShow: function () {
this.call('show');
},
/* hide */
innerHide: function () {
this.call('hide');
},
/* destroy */
innerDestroy: function() {
this.call('destroy');
},
setContainerOption: function(key, value) {
this.container().options[key] = value;
},
/**
* move popover to new position. This function mainly copied from bootstrap-popover.
*/
/*jshint laxcomma: true, eqeqeq: false*/
setPosition: function () {
(function() {
/*
var $tip = this.tip()
, inside
, pos
, actualWidth
, actualHeight
, placement
, tp
, tpt
, tpb
, tpl
, tpr;
placement = typeof this.options.placement === 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement;
inside = /in/.test(placement);
$tip
// .detach()
//vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover
.removeClass('top right bottom left')
.css({ top: 0, left: 0, display: 'block' });
// .insertAfter(this.$element);
pos = this.getPosition(inside);
actualWidth = $tip[0].offsetWidth;
actualHeight = $tip[0].offsetHeight;
placement = inside ? placement.split(' ')[1] : placement;
tpb = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2};
tpt = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2};
tpl = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth};
tpr = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width};
switch (placement) {
case 'bottom':
if ((tpb.top + actualHeight) > ($(window).scrollTop() + $(window).height())) {
if (tpt.top > $(window).scrollTop()) {
placement = 'top';
} else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
placement = 'right';
} else if (tpl.left > $(window).scrollLeft()) {
placement = 'left';
} else {
placement = 'right';
}
}
break;
case 'top':
if (tpt.top < $(window).scrollTop()) {
if ((tpb.top + actualHeight) < ($(window).scrollTop() + $(window).height())) {
placement = 'bottom';
} else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
placement = 'right';
} else if (tpl.left > $(window).scrollLeft()) {
placement = 'left';
} else {
placement = 'right';
}
}
break;
case 'left':
if (tpl.left < $(window).scrollLeft()) {
if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
placement = 'right';
} else if (tpt.top > $(window).scrollTop()) {
placement = 'top';
} else if (tpt.top > $(window).scrollTop()) {
placement = 'bottom';
} else {
placement = 'right';
}
}
break;
case 'right':
if ((tpr.left + actualWidth) > ($(window).scrollLeft() + $(window).width())) {
if (tpl.left > $(window).scrollLeft()) {
placement = 'left';
} else if (tpt.top > $(window).scrollTop()) {
placement = 'top';
} else if (tpt.top > $(window).scrollTop()) {
placement = 'bottom';
}
}
break;
}
switch (placement) {
case 'bottom':
tp = tpb;
break;
case 'top':
tp = tpt;
break;
case 'left':
tp = tpl;
break;
case 'right':
tp = tpr;
break;
}
$tip
.offset(tp)
.addClass(placement)
.addClass('in');
*/
var $tip = this.tip();
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement;
var autoToken = /\s?auto?\s?/i;
var autoPlace = autoToken.test(placement);
if (autoPlace) {
placement = placement.replace(autoToken, '') || 'top';
}
var pos = this.getPosition();
var actualWidth = $tip[0].offsetWidth;
var actualHeight = $tip[0].offsetHeight;
if (autoPlace) {
var $parent = this.$element.parent();
var orgPlacement = placement;
var docScroll = document.documentElement.scrollTop || document.body.scrollTop;
var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth();
var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight();
var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left;
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
placement;
$tip
.removeClass(orgPlacement)
.addClass(placement);
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight);
this.applyPlacement(calculatedOffset, placement);
}).call(this.container());
/*jshint laxcomma: false, eqeqeq: true*/
}
});
}(window.jQuery));
/* =========================================================
* bootstrap-datepicker.js
* http://www.eyecon.ro/bootstrap-datepicker
* =========================================================
* Copyright 2012 Stefan Petre
* Improvements by Andrew Rowls
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================= */
(function( $ ) {
function UTCDate(){
return new Date(Date.UTC.apply(Date, arguments));
}
function UTCToday(){
var today = new Date();
return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
}
// Picker object
var Datepicker = function(element, options) {
var that = this;
this._process_options(options);
this.element = $(element);
this.isInline = false;
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false;
this.hasInput = this.component && this.element.find('input').length;
if(this.component && this.component.length === 0)
this.component = false;
this.picker = $(DPGlobal.template);
this._buildEvents();
this._attachEvents();
if(this.isInline) {
this.picker.addClass('datepicker-inline').appendTo(this.element);
} else {
this.picker.addClass('datepicker-dropdown dropdown-menu');
}
if (this.o.rtl){
this.picker.addClass('datepicker-rtl');
this.picker.find('.prev i, .next i')
.toggleClass('icon-arrow-left icon-arrow-right');
}
this.viewMode = this.o.startView;
if (this.o.calendarWeeks)
this.picker.find('tfoot th.today')
.attr('colspan', function(i, val){
return parseInt(val) + 1;
});
this._allow_update = false;
this.setStartDate(this.o.startDate);
this.setEndDate(this.o.endDate);
this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);
this.fillDow();
this.fillMonths();
this._allow_update = true;
this.update();
this.showMode();
if(this.isInline) {
this.show();
}
};
Datepicker.prototype = {
constructor: Datepicker,
_process_options: function(opts){
// Store raw options for reference
this._o = $.extend({}, this._o, opts);
// Processed options
var o = this.o = $.extend({}, this._o);
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
var lang = o.language;
if (!dates[lang]) {
lang = lang.split('-')[0];
if (!dates[lang])
lang = defaults.language;
}
o.language = lang;
switch(o.startView){
case 2:
case 'decade':
o.startView = 2;
break;
case 1:
case 'year':
o.startView = 1;
break;
default:
o.startView = 0;
}
switch (o.minViewMode) {
case 1:
case 'months':
o.minViewMode = 1;
break;
case 2:
case 'years':
o.minViewMode = 2;
break;
default:
o.minViewMode = 0;
}
o.startView = Math.max(o.startView, o.minViewMode);
o.weekStart %= 7;
o.weekEnd = ((o.weekStart + 6) % 7);
var format = DPGlobal.parseFormat(o.format)
if (o.startDate !== -Infinity) {
o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
}
if (o.endDate !== Infinity) {
o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
}
o.daysOfWeekDisabled = o.daysOfWeekDisabled||[];
if (!$.isArray(o.daysOfWeekDisabled))
o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) {
return parseInt(d, 10);
});
},
_events: [],
_secondaryEvents: [],
_applyEvents: function(evs){
for (var i=0, el, ev; i<evs.length; i++){
el = evs[i][0];
ev = evs[i][1];
el.on(ev);
}
},
_unapplyEvents: function(evs){
for (var i=0, el, ev; i<evs.length; i++){
el = evs[i][0];
ev = evs[i][1];
el.off(ev);
}
},
_buildEvents: function(){
if (this.isInput) { // single input
this._events = [
[this.element, {
focus: $.proxy(this.show, this),
keyup: $.proxy(this.update, this),
keydown: $.proxy(this.keydown, this)
}]
];
}
else if (this.component && this.hasInput){ // component: input + button
this._events = [
// For components that are not readonly, allow keyboard nav
[this.element.find('input'), {
focus: $.proxy(this.show, this),
keyup: $.proxy(this.update, this),
keydown: $.proxy(this.keydown, this)
}],
[this.component, {
click: $.proxy(this.show, this)
}]
];
}
else if (this.element.is('div')) { // inline datepicker
this.isInline = true;
}
else {
this._events = [
[this.element, {
click: $.proxy(this.show, this)
}]
];
}
this._secondaryEvents = [
[this.picker, {
click: $.proxy(this.click, this)
}],
[$(window), {
resize: $.proxy(this.place, this)
}],
[$(document), {
mousedown: $.proxy(function (e) {
// Clicked outside the datepicker, hide it
if (!(
this.element.is(e.target) ||
this.element.find(e.target).size() ||
this.picker.is(e.target) ||
this.picker.find(e.target).size()
)) {
this.hide();
}
}, this)
}]
];
},
_attachEvents: function(){
this._detachEvents();
this._applyEvents(this._events);
},
_detachEvents: function(){
this._unapplyEvents(this._events);
},
_attachSecondaryEvents: function(){
this._detachSecondaryEvents();
this._applyEvents(this._secondaryEvents);
},
_detachSecondaryEvents: function(){
this._unapplyEvents(this._secondaryEvents);
},
_trigger: function(event, altdate){
var date = altdate || this.date,
local_date = new Date(date.getTime() + (date.getTimezoneOffset()*60000));
this.element.trigger({
type: event,
date: local_date,
format: $.proxy(function(altformat){
var format = altformat || this.o.format;
return DPGlobal.formatDate(date, format, this.o.language);
}, this)
});
},
show: function(e) {
if (!this.isInline)
this.picker.appendTo('body');
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.place();
this._attachSecondaryEvents();
if (e) {
e.preventDefault();
}
this._trigger('show');
},
hide: function(e){
if(this.isInline) return;
if (!this.picker.is(':visible')) return;
this.picker.hide().detach();
this._detachSecondaryEvents();
this.viewMode = this.o.startView;
this.showMode();
if (
this.o.forceParse &&
(
this.isInput && this.element.val() ||
this.hasInput && this.element.find('input').val()
)
)
this.setValue();
this._trigger('hide');
},
remove: function() {
this.hide();
this._detachEvents();
this._detachSecondaryEvents();
this.picker.remove();
delete this.element.data().datepicker;
if (!this.isInput) {
delete this.element.data().date;
}
},
getDate: function() {
var d = this.getUTCDate();
return new Date(d.getTime() + (d.getTimezoneOffset()*60000));
},
getUTCDate: function() {
return this.date;
},
setDate: function(d) {
this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000)));
},
setUTCDate: function(d) {
this.date = d;
this.setValue();
},
setValue: function() {
var formatted = this.getFormattedDate();
if (!this.isInput) {
if (this.component){
this.element.find('input').val(formatted);
}
} else {
this.element.val(formatted);
}
},
getFormattedDate: function(format) {
if (format === undefined)
format = this.o.format;
return DPGlobal.formatDate(this.date, format, this.o.language);
},
setStartDate: function(startDate){
this._process_options({startDate: startDate});
this.update();
this.updateNavArrows();
},
setEndDate: function(endDate){
this._process_options({endDate: endDate});
this.update();
this.updateNavArrows();
},
setDaysOfWeekDisabled: function(daysOfWeekDisabled){
this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
this.update();
this.updateNavArrows();
},
place: function(){
if(this.isInline) return;
var zIndex = parseInt(this.element.parents().filter(function() {
return $(this).css('z-index') != 'auto';
}).first().css('z-index'))+10;
var offset = this.component ? this.component.parent().offset() : this.element.offset();
var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true);
this.picker.css({
top: offset.top + height,
left: offset.left,
zIndex: zIndex
});
},
_allow_update: true,
update: function(){
if (!this._allow_update) return;
var date, fromArgs = false;
if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
date = arguments[0];
fromArgs = true;
} else {
date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val();
delete this.element.data().date;
}
this.date = DPGlobal.parseDate(date, this.o.format, this.o.language);
if(fromArgs) this.setValue();
if (this.date < this.o.startDate) {
this.viewDate = new Date(this.o.startDate);
} else if (this.date > this.o.endDate) {
this.viewDate = new Date(this.o.endDate);
} else {
this.viewDate = new Date(this.date);
}
this.fill();
},
fillDow: function(){
var dowCnt = this.o.weekStart,
html = '<tr>';
if(this.o.calendarWeeks){
var cell = '<th class="cw"> </th>';
html += cell;
this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
}
while (dowCnt < this.o.weekStart + 7) {
html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '',
i = 0;
while (i < 12) {
html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').html(html);
},
setRange: function(range){
if (!range || !range.length)
delete this.range;
else
this.range = $.map(range, function(d){ return d.valueOf(); });
this.fill();
},
getClassNames: function(date){
var cls = [],
year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth(),
currentDate = this.date.valueOf(),
today = new Date();
if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) {
cls.push('old');
} else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) {
cls.push('new');
}
// Compare internal UTC date with local today, not UTC today
if (this.o.todayHighlight &&
date.getUTCFullYear() == today.getFullYear() &&
date.getUTCMonth() == today.getMonth() &&
date.getUTCDate() == today.getDate()) {
cls.push('today');
}
if (currentDate && date.valueOf() == currentDate) {
cls.push('active');
}
if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
$.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) {
cls.push('disabled');
}
if (this.range){
if (date > this.range[0] && date < this.range[this.range.length-1]){
cls.push('range');
}
if ($.inArray(date.valueOf(), this.range) != -1){
cls.push('selected');
}
}
return cls;
},
fill: function() {
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
currentDate = this.date && this.date.valueOf(),
tooltip;
this.picker.find('.datepicker-days thead th.datepicker-switch')
.text(dates[this.o.language].months[month]+' '+year);
this.picker.find('tfoot th.today')
.text(dates[this.o.language].today)
.toggle(this.o.todayBtn !== false);
this.picker.find('tfoot th.clear')
.text(dates[this.o.language].clear)
.toggle(this.o.clearBtn !== false);
this.updateNavArrows();
this.fillMonths();
var prevMonth = UTCDate(year, month-1, 28,0,0,0,0),
day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
prevMonth.setUTCDate(day);
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName;
while(prevMonth.valueOf() < nextMonth) {
if (prevMonth.getUTCDay() == this.o.weekStart) {
html.push('<tr>');
if(this.o.calendarWeeks){
// ISO 8601: First week contains first thursday.
// ISO also states week starts on Monday, but we can be more abstract here.
var
// Start of current week: based on weekstart/current date
ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
// Thursday of this week
th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
// First Thursday of year, year from thursday
yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
// Calendar week: ms between thursdays, div ms per day, div 7 days
calWeek = (th - yth) / 864e5 / 7 + 1;
html.push('<td class="cw">'+ calWeek +'</td>');
}
}
clsName = this.getClassNames(prevMonth);
clsName.push('day');
var before = this.o.beforeShowDay(prevMonth);
if (before === undefined)
before = {};
else if (typeof(before) === 'boolean')
before = {enabled: before};
else if (typeof(before) === 'string')
before = {classes: before};
if (before.enabled === false)
clsName.push('disabled');
if (before.classes)
clsName = clsName.concat(before.classes.split(/\s+/));
if (before.tooltip)
tooltip = before.tooltip;
clsName = $.unique(clsName);
html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>');
if (prevMonth.getUTCDay() == this.o.weekEnd) {
html.push('</tr>');
}
prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date && this.date.getUTCFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear && currentYear == year) {
months.eq(this.date.getUTCMonth()).addClass('active');
}
if (year < startYear || year > endYear) {
months.addClass('disabled');
}
if (year == startYear) {
months.slice(0, startMonth).addClass('disabled');
}
if (year == endYear) {
months.slice(endMonth+1).addClass('disabled');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year'+(i == -1 ? ' old' : i == 10 ? ' new' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
updateNavArrows: function() {
if (!this._allow_update) return;
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth();
switch (this.viewMode) {
case 0:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) {
this.picker.find('.prev').css({visibility: 'hidden'});
} else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) {
this.picker.find('.next').css({visibility: 'hidden'});
} else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
case 1:
case 2:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) {
this.picker.find('.prev').css({visibility: 'hidden'});
} else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) {
this.picker.find('.next').css({visibility: 'hidden'});
} else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
}
},
click: function(e) {
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length == 1) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'datepicker-switch':
this.showMode(1);
break;
case 'prev':
case 'next':
var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1);
switch(this.viewMode){
case 0:
this.viewDate = this.moveMonth(this.viewDate, dir);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, dir);
break;
}
this.fill();
break;
case 'today':
var date = new Date();
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
this.showMode(-2);
var which = this.o.todayBtn == 'linked' ? null : 'view';
this._setDate(date, which);
break;
case 'clear':
var element;
if (this.isInput)
element = this.element;
else if (this.component)
element = this.element.find('input');
if (element)
element.val("").change();
this._trigger('changeDate');
this.update();
if (this.o.autoclose)
this.hide();
break;
}
break;
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
var day = 1;
var month = target.parent().find('span').index(target);
var year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
} else {
var year = parseInt(target.text(), 10)||0;
var day = 1;
var month = 0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
}
this.showMode(-1);
this.fill();
}
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
var day = parseInt(target.text(), 10)||1;
var year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth();
if (target.is('.old')) {
if (month === 0) {
month = 11;
year -= 1;
} else {
month -= 1;
}
} else if (target.is('.new')) {
if (month == 11) {
month = 0;
year += 1;
} else {
month += 1;
}
}
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
break;
}
}
},
_setDate: function(date, which){
if (!which || which == 'date')
this.date = new Date(date);
if (!which || which == 'view')
this.viewDate = new Date(date);
this.fill();
this.setValue();
this._trigger('changeDate');
var element;
if (this.isInput) {
element = this.element;
} else if (this.component){
element = this.element.find('input');
}
if (element) {
element.change();
if (this.o.autoclose && (!which || which == 'date')) {
this.hide();
}
}
},
moveMonth: function(date, dir){
if (!dir) return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag == 1){
test = dir == -1
// If going back one month, make sure month is not current month
// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
? function(){ return new_date.getUTCMonth() == month; }
// If going forward one month, make sure month is as expected
// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
: function(){ return new_date.getUTCMonth() != new_month; };
new_month = month + dir;
new_date.setUTCMonth(new_month);
// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
if (new_month < 0 || new_month > 11)
new_month = (new_month + 12) % 12;
} else {
// For magnitudes >1, move one month at a time...
for (var i=0; i<mag; i++)
// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
new_date = this.moveMonth(new_date, dir);
// ...then reset the day, keeping it in the new month
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function(){ return new_month != new_date.getUTCMonth(); };
}
// Common date-resetting loop -- if date is beyond end of month, make it
// end of month
while (test()){
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function(date, dir){
return this.moveMonth(date, dir*12);
},
dateWithinRange: function(date){
return date >= this.o.startDate && date <= this.o.endDate;
},
keydown: function(e){
if (this.picker.is(':not(:visible)')){
if (e.keyCode == 27) // allow escape to hide and re-show picker
this.show();
return;
}
var dateChanged = false,
dir, day, month,
newDate, newViewDate;
switch(e.keyCode){
case 27: // escape
this.hide();
e.preventDefault();
break;
case 37: // left
case 39: // right
if (!this.o.keyboardNavigation) break;
dir = e.keyCode == 37 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.date, dir);
newViewDate = this.moveYear(this.viewDate, dir);
} else if (e.shiftKey){
newDate = this.moveMonth(this.date, dir);
newViewDate = this.moveMonth(this.viewDate, dir);
} else {
newDate = new Date(this.date);
newDate.setUTCDate(this.date.getUTCDate() + dir);
newViewDate = new Date(this.viewDate);
newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
}
if (this.dateWithinRange(newDate)){
this.date = newDate;
this.viewDate = newViewDate;
this.setValue();
this.update();
e.preventDefault();
dateChanged = true;
}
break;
case 38: // up
case 40: // down
if (!this.o.keyboardNavigation) break;
dir = e.keyCode == 38 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.date, dir);
newViewDate = this.moveYear(this.viewDate, dir);
} else if (e.shiftKey){
newDate = this.moveMonth(this.date, dir);
newViewDate = this.moveMonth(this.viewDate, dir);
} else {
newDate = new Date(this.date);
newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
newViewDate = new Date(this.viewDate);
newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
}
if (this.dateWithinRange(newDate)){
this.date = newDate;
this.viewDate = newViewDate;
this.setValue();
this.update();
e.preventDefault();
dateChanged = true;
}
break;
case 13: // enter
this.hide();
e.preventDefault();
break;
case 9: // tab
this.hide();
break;
}
if (dateChanged){
this._trigger('changeDate');
var element;
if (this.isInput) {
element = this.element;
} else if (this.component){
element = this.element.find('input');
}
if (element) {
element.change();
}
}
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
}
/*
vitalets: fixing bug of very special conditions:
jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover.
Method show() does not set display css correctly and datepicker is not shown.
Changed to .css('display', 'block') solve the problem.
See https://github.com/vitalets/x-editable/issues/37
In jquery 1.7.2+ everything works fine.
*/
//this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block');
this.updateNavArrows();
}
};
var DateRangePicker = function(element, options){
this.element = $(element);
this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; });
delete options.inputs;
$(this.inputs)
.datepicker(options)
.bind('changeDate', $.proxy(this.dateUpdated, this));
this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); });
this.updateDates();
};
DateRangePicker.prototype = {
updateDates: function(){
this.dates = $.map(this.pickers, function(i){ return i.date; });
this.updateRanges();
},
updateRanges: function(){
var range = $.map(this.dates, function(d){ return d.valueOf(); });
$.each(this.pickers, function(i, p){
p.setRange(range);
});
},
dateUpdated: function(e){
var dp = $(e.target).data('datepicker'),
new_date = dp.getUTCDate(),
i = $.inArray(e.target, this.inputs),
l = this.inputs.length;
if (i == -1) return;
if (new_date < this.dates[i]){
// Date being moved earlier/left
while (i>=0 && new_date < this.dates[i]){
this.pickers[i--].setUTCDate(new_date);
}
}
else if (new_date > this.dates[i]){
// Date being moved later/right
while (i<l && new_date > this.dates[i]){
this.pickers[i++].setUTCDate(new_date);
}
}
this.updateDates();
},
remove: function(){
$.map(this.pickers, function(p){ p.remove(); });
delete this.element.data().datepicker;
}
};
function opts_from_el(el, prefix){
// Derive options from element data-attrs
var data = $(el).data(),
out = {}, inkey,
replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'),
prefix = new RegExp('^' + prefix.toLowerCase());
for (var key in data)
if (prefix.test(key)){
inkey = key.replace(replace, function(_,a){ return a.toLowerCase(); });
out[inkey] = data[key];
}
return out;
}
function opts_from_locale(lang){
// Derive options from locale plugins
var out = {};
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
if (!dates[lang]) {
lang = lang.split('-')[0]
if (!dates[lang])
return;
}
var d = dates[lang];
$.each(locale_opts, function(i,k){
if (k in d)
out[k] = d[k];
});
return out;
}
var old = $.fn.datepicker;
var datepicker = $.fn.datepicker = function ( option ) {
var args = Array.apply(null, arguments);
args.shift();
var internal_return,
this_return;
this.each(function () {
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option == 'object' && option;
if (!data) {
var elopts = opts_from_el(this, 'date'),
// Preliminary otions
xopts = $.extend({}, defaults, elopts, options),
locopts = opts_from_locale(xopts.language),
// Options priority: js args, data-attrs, locales, defaults
opts = $.extend({}, defaults, locopts, elopts, options);
if ($this.is('.input-daterange') || opts.inputs){
var ropts = {
inputs: opts.inputs || $this.find('input').toArray()
};
$this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
}
else{
$this.data('datepicker', (data = new Datepicker(this, opts)));
}
}
if (typeof option == 'string' && typeof data[option] == 'function') {
internal_return = data[option].apply(data, args);
if (internal_return !== undefined)
return false;
}
});
if (internal_return !== undefined)
return internal_return;
else
return this;
};
var defaults = $.fn.datepicker.defaults = {
autoclose: false,
beforeShowDay: $.noop,
calendarWeeks: false,
clearBtn: false,
daysOfWeekDisabled: [],
endDate: Infinity,
forceParse: true,
format: 'mm/dd/yyyy',
keyboardNavigation: true,
language: 'en',
minViewMode: 0,
rtl: false,
startDate: -Infinity,
startView: 0,
todayBtn: false,
todayHighlight: false,
weekStart: 0
};
var locale_opts = $.fn.datepicker.locale_opts = [
'format',
'rtl',
'weekStart'
];
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today",
clear: "Clear"
}
};
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function(format){
// IE treats \0 as a string end in inputs (truncating the value),
// so it's a bad format delimiter, anyway
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separators: separators, parts: parts};
},
parseDate: function(date, format, language) {
if (date instanceof Date) return date;
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([\-+]\d+)([dmwy])/,
parts = date.match(/([\-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i=0; i<parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch(part[2]){
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
}
var parts = date && date.match(this.nonpunctuation) || [],
date = new Date(),
parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function(d,v){ return d.setUTCFullYear(v); },
yy: function(d,v){ return d.setUTCFullYear(2000+v); },
m: function(d,v){
v -= 1;
while (v<0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() != v)
d.setUTCDate(d.getUTCDate()-1);
return d;
},
d: function(d,v){ return d.setUTCDate(v); }
},
val, filtered, part;
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var fparts = format.parts.slice();
// Remove noop parts
if (parts.length != fparts.length) {
fparts = $(fparts).filter(function(i,p){
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
// Process remainder
if (parts.length == fparts.length) {
for (var i=0, cnt = fparts.length; i < cnt; i++) {
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)) {
switch(part) {
case 'MM':
filtered = $(dates[language].months).filter(function(){
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m == p;
});
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(function(){
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m == p;
});
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
for (var i=0, s; i<setters_order.length; i++){
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s]))
setters_map[s](date, parsed[s]);
}
}
return date;
},
formatDate: function(date, format, language){
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [],
seps = $.extend([], format.separators);
for (var i=0, cnt = format.parts.length; i <= cnt; i++) {
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev"><i class="icon-arrow-left"/></th>'+
'<th colspan="5" class="datepicker-switch"></th>'+
'<th class="next"><i class="icon-arrow-right"/></th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'
};
DPGlobal.template = '<div class="datepicker">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'</div>';
$.fn.datepicker.DPGlobal = DPGlobal;
/* DATEPICKER NO CONFLICT
* =================== */
$.fn.datepicker.noConflict = function(){
$.fn.datepicker = old;
return this;
};
/* DATEPICKER DATA-API
* ================== */
$(document).on(
'focus.datepicker.data-api click.datepicker.data-api',
'[data-provide="datepicker"]',
function(e){
var $this = $(this);
if ($this.data('datepicker')) return;
e.preventDefault();
// component click requires us to explicitly show it
datepicker.call($this, 'show');
}
);
$(function(){
//$('[data-provide="datepicker-inline"]').datepicker();
//vit: changed to support noConflict()
datepicker.call($('[data-provide="datepicker-inline"]'));
});
}( window.jQuery ));
/**
Bootstrap-datepicker.
Description and examples: https://github.com/eternicode/bootstrap-datepicker.
For **i18n** you should include js file from here: https://github.com/eternicode/bootstrap-datepicker/tree/master/js/locales
and set `language` option.
Since 1.4.0 date has different appearance in **popup** and **inline** modes.
@class date
@extends abstractinput
@final
@example
<a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a>
<script>
$(function(){
$('#dob').editable({
format: 'yyyy-mm-dd',
viewformat: 'dd/mm/yyyy',
datepicker: {
weekStart: 1
}
}
});
});
</script>
**/
(function ($) {
"use strict";
//store bootstrap-datepicker as bdateicker to exclude conflict with jQuery UI one
$.fn.bdatepicker = $.fn.datepicker.noConflict();
if(!$.fn.datepicker) { //if there were no other datepickers, keep also original name
$.fn.datepicker = $.fn.bdatepicker;
}
var Date = function (options) {
this.init('date', options, Date.defaults);
this.initPicker(options, Date.defaults);
};
$.fn.editableutils.inherit(Date, $.fn.editabletypes.abstractinput);
$.extend(Date.prototype, {
initPicker: function(options, defaults) {
//'format' is set directly from settings or data-* attributes
//by default viewformat equals to format
if(!this.options.viewformat) {
this.options.viewformat = this.options.format;
}
//try parse datepicker config defined as json string in data-datepicker
options.datepicker = $.fn.editableutils.tryParseJson(options.datepicker, true);
//overriding datepicker config (as by default jQuery extend() is not recursive)
//since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only
this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, {
format: this.options.viewformat
});
//language
this.options.datepicker.language = this.options.datepicker.language || 'en';
//store DPglobal
this.dpg = $.fn.bdatepicker.DPGlobal;
//store parsed formats
this.parsedFormat = this.dpg.parseFormat(this.options.format);
this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat);
},
render: function () {
this.$input.bdatepicker(this.options.datepicker);
//"clear" link
if(this.options.clear) {
this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
e.preventDefault();
e.stopPropagation();
this.clear();
}, this));
this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));
}
},
value2html: function(value, element) {
var text = value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : '';
Date.superclass.value2html.call(this, text, element);
},
html2value: function(html) {
return this.parseDate(html, this.parsedViewFormat);
},
value2str: function(value) {
return value ? this.dpg.formatDate(value, this.parsedFormat, this.options.datepicker.language) : '';
},
str2value: function(str) {
return this.parseDate(str, this.parsedFormat);
},
value2submit: function(value) {
return this.value2str(value);
},
value2input: function(value) {
this.$input.bdatepicker('update', value);
},
input2value: function() {
return this.$input.data('datepicker').date;
},
activate: function() {
},
clear: function() {
this.$input.data('datepicker').date = null;
this.$input.find('.active').removeClass('active');
if(!this.options.showbuttons) {
this.$input.closest('form').submit();
}
},
autosubmit: function() {
this.$input.on('mouseup', '.day', function(e){
if($(e.currentTarget).is('.old') || $(e.currentTarget).is('.new')) {
return;
}
var $form = $(this).closest('form');
setTimeout(function() {
$form.submit();
}, 200);
});
//changedate is not suitable as it triggered when showing datepicker. see #149
/*
this.$input.on('changeDate', function(e){
var $form = $(this).closest('form');
setTimeout(function() {
$form.submit();
}, 200);
});
*/
},
/*
For incorrect date bootstrap-datepicker returns current date that is not suitable
for datefield.
This function returns null for incorrect date.
*/
parseDate: function(str, format) {
var date = null, formattedBack;
if(str) {
date = this.dpg.parseDate(str, format, this.options.datepicker.language);
if(typeof str === 'string') {
formattedBack = this.dpg.formatDate(date, format, this.options.datepicker.language);
if(str !== formattedBack) {
date = null;
}
}
}
return date;
}
});
Date.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <div></div>
**/
tpl:'<div class="editable-date well"></div>',
/**
@property inputclass
@default null
**/
inputclass: null,
/**
Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
Possible tokens are: <code>d, dd, m, mm, yy, yyyy</code>
@property format
@type string
@default yyyy-mm-dd
**/
format:'yyyy-mm-dd',
/**
Format used for displaying date. Also applied when converting date from element's text on init.
If not specified equals to <code>format</code>
@property viewformat
@type string
@default null
**/
viewformat: null,
/**
Configuration of datepicker.
Full list of options: http://bootstrap-datepicker.readthedocs.org/en/latest/options.html
@property datepicker
@type object
@default {
weekStart: 0,
startView: 0,
minViewMode: 0,
autoclose: false
}
**/
datepicker:{
weekStart: 0,
startView: 0,
minViewMode: 0,
autoclose: false
},
/**
Text shown as clear date button.
If <code>false</code> clear button will not be rendered.
@property clear
@type boolean|string
@default 'x clear'
**/
clear: '× clear'
});
$.fn.editabletypes.date = Date;
}(window.jQuery));
/**
Bootstrap datefield input - modification for inline mode.
Shows normal <input type="text"> and binds popup datepicker.
Automatically shown in inline mode.
@class datefield
@extends date
@since 1.4.0
**/
(function ($) {
"use strict";
var DateField = function (options) {
this.init('datefield', options, DateField.defaults);
this.initPicker(options, DateField.defaults);
};
$.fn.editableutils.inherit(DateField, $.fn.editabletypes.date);
$.extend(DateField.prototype, {
render: function () {
this.$input = this.$tpl.find('input');
this.setClass();
this.setAttr('placeholder');
//bootstrap-datepicker is set `bdateicker` to exclude conflict with jQuery UI one. (in date.js)
this.$tpl.bdatepicker(this.options.datepicker);
//need to disable original event handlers
this.$input.off('focus keydown');
//update value of datepicker
this.$input.keyup($.proxy(function(){
this.$tpl.removeData('date');
this.$tpl.bdatepicker('update');
}, this));
},
value2input: function(value) {
this.$input.val(value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : '');
this.$tpl.bdatepicker('update');
},
input2value: function() {
return this.html2value(this.$input.val());
},
activate: function() {
$.fn.editabletypes.text.prototype.activate.call(this);
},
autosubmit: function() {
//reset autosubmit to empty
}
});
DateField.defaults = $.extend({}, $.fn.editabletypes.date.defaults, {
/**
@property tpl
**/
tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>',
/**
@property inputclass
@default 'input-small'
**/
inputclass: 'input-small',
/* datepicker config */
datepicker: {
weekStart: 0,
startView: 0,
minViewMode: 0,
autoclose: true
}
});
$.fn.editabletypes.datefield = DateField;
}(window.jQuery));
/**
Bootstrap-datetimepicker.
Based on [smalot bootstrap-datetimepicker plugin](https://github.com/smalot/bootstrap-datetimepicker).
Before usage you should manually include dependent js and css:
<link href="css/datetimepicker.css" rel="stylesheet" type="text/css"></link>
<script src="js/bootstrap-datetimepicker.js"></script>
For **i18n** you should include js file from here: https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales
and set `language` option.
@class datetime
@extends abstractinput
@final
@since 1.4.4
@example
<a href="#" id="last_seen" data-type="datetime" data-pk="1" data-url="/post" title="Select date & time">15/03/2013 12:45</a>
<script>
$(function(){
$('#last_seen').editable({
format: 'yyyy-mm-dd hh:ii',
viewformat: 'dd/mm/yyyy hh:ii',
datetimepicker: {
weekStart: 1
}
}
});
});
</script>
**/
(function ($) {
"use strict";
var DateTime = function (options) {
this.init('datetime', options, DateTime.defaults);
this.initPicker(options, DateTime.defaults);
};
$.fn.editableutils.inherit(DateTime, $.fn.editabletypes.abstractinput);
$.extend(DateTime.prototype, {
initPicker: function(options, defaults) {
//'format' is set directly from settings or data-* attributes
//by default viewformat equals to format
if(!this.options.viewformat) {
this.options.viewformat = this.options.format;
}
//try parse datetimepicker config defined as json string in data-datetimepicker
options.datetimepicker = $.fn.editableutils.tryParseJson(options.datetimepicker, true);
//overriding datetimepicker config (as by default jQuery extend() is not recursive)
//since 1.4 datetimepicker internally uses viewformat instead of format. Format is for submit only
this.options.datetimepicker = $.extend({}, defaults.datetimepicker, options.datetimepicker, {
format: this.options.viewformat
});
//language
this.options.datetimepicker.language = this.options.datetimepicker.language || 'en';
//store DPglobal
this.dpg = $.fn.datetimepicker.DPGlobal;
//store parsed formats
this.parsedFormat = this.dpg.parseFormat(this.options.format, this.options.formatType);
this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat, this.options.formatType);
},
render: function () {
this.$input.datetimepicker(this.options.datetimepicker);
//adjust container position when viewMode changes
//see https://github.com/smalot/bootstrap-datetimepicker/pull/80
this.$input.on('changeMode', function(e) {
var f = $(this).closest('form').parent();
//timeout here, otherwise container changes position before form has new size
setTimeout(function(){
f.triggerHandler('resize');
}, 0);
});
//"clear" link
if(this.options.clear) {
this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
e.preventDefault();
e.stopPropagation();
this.clear();
}, this));
this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));
}
},
value2html: function(value, element) {
//formatDate works with UTCDate!
var text = value ? this.dpg.formatDate(this.toUTC(value), this.parsedViewFormat, this.options.datetimepicker.language, this.options.formatType) : '';
if(element) {
DateTime.superclass.value2html.call(this, text, element);
} else {
return text;
}
},
html2value: function(html) {
//parseDate return utc date!
var value = this.parseDate(html, this.parsedViewFormat);
return value ? this.fromUTC(value) : null;
},
value2str: function(value) {
//formatDate works with UTCDate!
return value ? this.dpg.formatDate(this.toUTC(value), this.parsedFormat, this.options.datetimepicker.language, this.options.formatType) : '';
},
str2value: function(str) {
//parseDate return utc date!
var value = this.parseDate(str, this.parsedFormat);
return value ? this.fromUTC(value) : null;
},
value2submit: function(value) {
return this.value2str(value);
},
value2input: function(value) {
if(value) {
this.$input.data('datetimepicker').setDate(value);
}
},
input2value: function() {
//date may be cleared, in that case getDate() triggers error
var dt = this.$input.data('datetimepicker');
return dt.date ? dt.getDate() : null;
},
activate: function() {
},
clear: function() {
this.$input.data('datetimepicker').date = null;
this.$input.find('.active').removeClass('active');
if(!this.options.showbuttons) {
this.$input.closest('form').submit();
}
},
autosubmit: function() {
this.$input.on('mouseup', '.minute', function(e){
var $form = $(this).closest('form');
setTimeout(function() {
$form.submit();
}, 200);
});
},
//convert date from local to utc
toUTC: function(value) {
return value ? new Date(value.valueOf() - value.getTimezoneOffset() * 60000) : value;
},
//convert date from utc to local
fromUTC: function(value) {
return value ? new Date(value.valueOf() + value.getTimezoneOffset() * 60000) : value;
},
/*
For incorrect date bootstrap-datetimepicker returns current date that is not suitable
for datetimefield.
This function returns null for incorrect date.
*/
parseDate: function(str, format) {
var date = null, formattedBack;
if(str) {
date = this.dpg.parseDate(str, format, this.options.datetimepicker.language, this.options.formatType);
if(typeof str === 'string') {
formattedBack = this.dpg.formatDate(date, format, this.options.datetimepicker.language, this.options.formatType);
if(str !== formattedBack) {
date = null;
}
}
}
return date;
}
});
DateTime.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <div></div>
**/
tpl:'<div class="editable-date well"></div>',
/**
@property inputclass
@default null
**/
inputclass: null,
/**
Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
Possible tokens are: <code>d, dd, m, mm, yy, yyyy, h, i</code>
@property format
@type string
@default yyyy-mm-dd hh:ii
**/
format:'yyyy-mm-dd hh:ii',
formatType:'standard',
/**
Format used for displaying date. Also applied when converting date from element's text on init.
If not specified equals to <code>format</code>
@property viewformat
@type string
@default null
**/
viewformat: null,
/**
Configuration of datetimepicker.
Full list of options: https://github.com/smalot/bootstrap-datetimepicker
@property datetimepicker
@type object
@default { }
**/
datetimepicker:{
todayHighlight: false,
autoclose: false
},
/**
Text shown as clear date button.
If <code>false</code> clear button will not be rendered.
@property clear
@type boolean|string
@default 'x clear'
**/
clear: '× clear'
});
$.fn.editabletypes.datetime = DateTime;
}(window.jQuery));
/**
Bootstrap datetimefield input - datetime input for inline mode.
Shows normal <input type="text"> and binds popup datetimepicker.
Automatically shown in inline mode.
@class datetimefield
@extends datetime
**/
(function ($) {
"use strict";
var DateTimeField = function (options) {
this.init('datetimefield', options, DateTimeField.defaults);
this.initPicker(options, DateTimeField.defaults);
};
$.fn.editableutils.inherit(DateTimeField, $.fn.editabletypes.datetime);
$.extend(DateTimeField.prototype, {
render: function () {
this.$input = this.$tpl.find('input');
this.setClass();
this.setAttr('placeholder');
this.$tpl.datetimepicker(this.options.datetimepicker);
//need to disable original event handlers
this.$input.off('focus keydown');
//update value of datepicker
this.$input.keyup($.proxy(function(){
this.$tpl.removeData('date');
this.$tpl.datetimepicker('update');
}, this));
},
value2input: function(value) {
this.$input.val(this.value2html(value));
this.$tpl.datetimepicker('update');
},
input2value: function() {
return this.html2value(this.$input.val());
},
activate: function() {
$.fn.editabletypes.text.prototype.activate.call(this);
},
autosubmit: function() {
//reset autosubmit to empty
}
});
DateTimeField.defaults = $.extend({}, $.fn.editabletypes.datetime.defaults, {
/**
@property tpl
**/
tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>',
/**
@property inputclass
@default 'input-medium'
**/
inputclass: 'input-medium',
/* datetimepicker config */
datetimepicker:{
todayHighlight: false,
autoclose: true
}
});
$.fn.editabletypes.datetimefield = DateTimeField;
}(window.jQuery));
|
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import Plotly from 'plotly.js';
import Theme from '../../helpers/theme.js';
class RangeMetrics extends React.Component {
// data should be an array of track and truth data
// filtered by a track id
static propTypes = {
data: PropTypes.object,
title: PropTypes.string,
width: PropTypes.number,
fieldX: PropTypes.string,
fieldY: PropTypes.string,
height: PropTypes.number
}
constructor () {
super();
this.state = {};
}
componentDidMount () {
const plotDiv = ReactDOM.findDOMNode(this);
this.setState({
plotDiv
});
Plotly.newPlot(plotDiv, this.createPlotData(this.props.data), this.createLayout());
}
componentWillReceiveProps (nextProps) {
const { plotDiv } = this.state;
this.props = nextProps;
if (plotDiv) {
Plotly.newPlot(plotDiv, this.createPlotData(nextProps.data), this.createLayout());
}
}
createPlotData (data) {
const { fieldX, fieldY } = this.props;
let trackX = [];
let trackY = [];
data.forEach((row) => {
if (row.has(fieldX) && row.has(fieldY)) {
trackX.push(row.get(fieldX));
trackY.push(row.get(fieldY));
}
});
return [{
type: 'scatter',
x: trackX,
y: trackY,
mode: 'markers',
marker: {
size: 12,
opacity: 0.6,
symbol: 'dot',
color: Theme.palette.track,
line: {
opacity: 0.5,
width: 1,
color: Theme.palette.truth
}
},
name: 'Track'
}];
}
createLayout () {
const { title, width, height, fieldY, fieldX } = this.props;
return {
title,
width,
height,
yaxis: {
title: fieldY
},
xaxis: {
title: fieldX
}
};
}
config = {
showLink: false,
displayModeBar: true
};
render () {
return (
<div />
);
}
}
export default RangeMetrics;
|
'use strict';
var forEach = require('lodash/collection/forEach');
var Collections = require('../../../util/Collections');
/**
* A handler that implements reversible moving of connections.
*
* The handler differs from the layout connection handler in a sense
* that it preserves the connection layout.
*/
function MoveConnectionHandler() { }
module.exports = MoveConnectionHandler;
MoveConnectionHandler.prototype.execute = function(context) {
var updateAnchors = (context.hints.updateAnchors !== false);
var connection = context.connection,
delta = context.delta;
var newParent = this.getNewParent(connection, context),
oldParent = connection.parent;
// save old position + parent in context
context.oldParent = oldParent;
context.oldParentIndex = Collections.indexOf(oldParent.children, connection);
// update waypoint positions
forEach(connection.waypoints, function(p) {
p.x += delta.x;
p.y += delta.y;
if (updateAnchors && p.original) {
p.original.x += delta.x;
p.original.y += delta.y;
}
});
// update parent
connection.parent = newParent;
return connection;
};
MoveConnectionHandler.prototype.revert = function(context) {
var updateAnchors = (context.hints.updateAnchors !== false);
var connection = context.connection,
oldParent = context.oldParent,
oldParentIndex = context.oldParentIndex,
delta = context.delta;
// restore previous location in old parent
Collections.add(oldParent.children, connection, oldParentIndex);
// restore parent
connection.parent = oldParent;
// revert to old waypoint positions
forEach(connection.waypoints, function(p) {
p.x -= delta.x;
p.y -= delta.y;
if (updateAnchors && p.original) {
p.original.x -= delta.x;
p.original.y -= delta.y;
}
});
return connection;
};
MoveConnectionHandler.prototype.getNewParent = function(connection, context) {
return context.newParent || connection.parent;
};
|
var expect = require('expect.js');
require('../dist/linq.js');
describe('skip', function () {
it('Should bypass a specified number of elements in a sequence and then returns the remaining elements', function (done) {
var arr = [1, 2, 3, 4, 5];
var res = arr.skip(2);
expect(res).be.an(Array);
expect(res).be.eql([3, 4, 5]);
done();
});
}); |
///import core
///import plugins/inserthtml.js
///commands 音乐
///commandsName Music
///commandsTitle 插入音乐
///commandsDialog dialogs\music
UE.plugins['music'] = function () {
var me = this,
div;
/**
* 创建插入音乐字符窜
* @param url 音乐地址
* @param width 音乐宽度
* @param height 音乐高度
* @param align 阴雨对齐
* @param toEmbed 是否以flash代替显示
* @param addParagraph 是否需要添加P标签
*/
function creatInsertStr(url,width,height,align,toEmbed,addParagraph){
return !toEmbed ?
(addParagraph? ('<p '+ (align !="none" ? ( align == "center"? ' style="text-align:center;" ':' style="float:"'+ align ) : '') + '>'): '') +
'<img align="'+align+'" width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
' src="'+me.options.langPath+me.options.lang+'/images/music.png" />' +
(addParagraph?'</p>':'')
:
'<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
' src="' + url + '" width="' + width + '" height="' + height + '" align="' + align + '"' +
( align !="none" ? ' style= "'+ ( align == "center"? "display:block;":" float: "+ align ) + '"' :'' ) +
' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
}
function switchImgAndEmbed(img2embed) {
var tmpdiv,
nodes = domUtils.getElementsByTagName(me.document, !img2embed ? "embed" : "img");
for (var i = 0, node; node = nodes[i++];) {
if (node.className != "edui-faked-music") {
continue;
}
tmpdiv = me.document.createElement("div");
//先看float在看align,浮动有的是时候是在float上定义的
var align = domUtils.getComputedStyle(node,'float');
align = align == 'none' ? (node.getAttribute('align') || '') : align;
tmpdiv.innerHTML = creatInsertStr(img2embed ? node.getAttribute("_url") : node.getAttribute("src"), node.width, node.height, align, img2embed);
node.parentNode.replaceChild(tmpdiv.firstChild, node);
}
}
me.addListener("beforegetcontent", function () {
switchImgAndEmbed(true);
});
me.addListener('aftersetcontent', function () {
switchImgAndEmbed(false);
});
me.addListener('aftergetcontent', function (cmdName) {
if (cmdName == 'aftergetcontent' && me.queryCommandState('source')) {
return;
}
switchImgAndEmbed(false);
});
me.commands["music"] = {
execCommand:function (cmd, musicObj) {
var me = this,
str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false, true);
me.execCommand("inserthtml",str);
},
queryCommandState:function () {
var me = this,
img = me.selection.getRange().getClosedNode(),
flag = img && (img.className == "edui-faked-music");
return flag ? 1 : 0;
}
};
}; |
const {
BufferedProcess
} = require('atom');
const path = require('path');
const fs = require('fs');
const _ = require('underscore-plus');
const {
watchPath
} = require('atom');
const Package = require('./package');
const {
CompositeDisposable,
Emitter
} = require('event-kit');
class Folder {
static initClass() {
// static variable makes sure we only show the warning
// about using an old browser only once
this.oldParserWarningShown = false;
this.parserErrorShown = false;
}
constructor(path1, getParserExecutable) {
this.showParserError = this.showParserError.bind(this);
this.path = path1;
this.getParserExecutable = getParserExecutable;
this.packages = {};
this.fileStats = {};
// create watches for the directory
// and rescan if anything changes.
this.watch();
}
setUpdateCallback(updateCallback) {
this.updateCallback = updateCallback;
}
setParserStatusCallback(parserStatusCallback) {
this.parserStatusCallback = parserStatusCallback;
}
getPackages() {
return _.values(this.packages);
}
watch() {
if(this.watchSubscription === null) {
return;
}
this.watchSubscription = watchPath(this.path, {}, events => {
var changed = false;
for(const event of events) {
if(['modified', 'created', 'deleted'].indexOf(event.action) > -1){
changed=true;
break;
}
}
if(changed) {
return this.fullReparse();
}
});
}
fullReparse() {
let names;
try {
names = fs.readdirSync(this.path);
} catch (error) {
names = [];
}
// ignore non-go-files
names = _.filter(names, x => x.endsWith('.go'));
const files = [];
const promises = [];
this.parserStatusCallback(names, [], []);
const doneFiles = new Set();
const failedFiles = new Set();
for(let name of Array.from(names)) {
var result = this.parseFile(name);
if(result != null) {
const f = n => {
result.then(code => {
if(code === 0) {
doneFiles.add(n);
} else {
failedFiles.add(n);
}
return this.parserStatusCallback(names, doneFiles, failedFiles);
});
return promises.push(result);
};
f(name);
} else {
// if the result was no promise, the file was ignored
// meaning it was not updated or different type, so we count a success
doneFiles.add(name);
}
}
return Promise.all(promises).then(() => {
this.parserStatusCallback(names, doneFiles, failedFiles);
for(let pkgName in this.packages) {
const pkg = this.packages[pkgName];
pkg.sortChildren();
}
return this.updateCallback(this);
});
}
parseFile(name) {
// check stats of file, load symlinks etc.
const fullPath = path.join(this.path, name);
let stat = fs.statSync(fullPath);
if(typeof stat.isSymbolicLink === 'function' ? stat.isSymbolicLink() : undefined) {
stat = fs.lstatSync(fullPath);
}
if((typeof stat.isDirectory === 'function' ? stat.isDirectory() : undefined) || !(typeof stat.isFile === 'function' ? stat.isFile() : undefined)) {
return null;
}
// file stats exist, and file is not newer -> has not changed
if(fullPath in this.fileStats && (this.fileStats[fullPath].mtime.getTime() >= stat.mtime.getTime())) {
return null;
}
this.fileStats[fullPath] = stat;
return this.reparseFile(fullPath);
}
reparseFile(filePath) {
const out = [];
const parserExecutable = this.getParserExecutable();
const promise = new Promise((resolve, reject) => {
const proc = new BufferedProcess({
command: parserExecutable,
args: ['-f', filePath],
stdout: data => {
return out.push(data);
},
exit: code => {
return resolve(code);
}
});
proc.onWillThrowError(c => {
resolve(c);
this.showParserError(c.error);
return c.handle();
});
return proc;
}).then(code => {
if(code !== 0) {
return code;
}
try {
return this.updateFolder(out.join("\n"));
} catch (error) {
return console.log("Error creating outline from parser-output", error, out);
} finally {
return code;
}
});
return promise;
}
showParserError(error) {
if(Folder.parserErrorShown) {
return;
}
atom.notifications.addError("Error executing go-outline-parser", {
detail: error + "\nExecutable not found?",
dismissable: true,
});
return Folder.parserErrorShown = true;
}
updateFolder(parserOutput) {
const parsed = JSON.parse(parserOutput);
// maybe the file does not have any entries? Ignore it
if((parsed.Entries == null)) {
return;
}
if(!(parsed.Entries instanceof Array)) {
// for the first time this happens per session
// show a warning to update go-outline-parser
if(!Folder.oldParserWarningShown) {
atom.notifications.addInfo("Update go-outline-parser", {
detail: "It seems like you're using an outdated version of go-outline.\nUpdate to get more features/bugfixes.",
dismissable: true
});
Folder.oldParserWarningShown = true;
}
// convert it to a list anyway to be backwards compatible
parsed.Entries = _.values(parsed.Entries);
}
const file = parsed.Filename;
const packageName = parsed.Packagename;
const pkg = this.updatePackage(file, packageName);
return pkg.updateChildrenForFile(parsed.Entries, file);
}
updatePackage(file, packageName) {
if(!(packageName in this.packages)) {
this.packages[packageName] = new Package(packageName);
}
const pkg = this.packages[packageName];
// add the parsed file to its package and remove it from all the other
// packages. This covers the case when the package has been renamed.
pkg.addFile(file);
for(var name in this.packages) {
const p = this.packages[name];
if(p === pkg) {
continue;
}
p.removeFile(file);
}
// remove all packages that don't have any files
for(name of Array.from(_.keys(this.packages))) {
if(!this.packages[name].hasFiles()) {
delete this.packages[name];
}
}
return pkg;
}
expandPackages() {
return Array.from(this.getPackages()).map((pkg) =>
pkg.expand());
}
collapsePackages() {
return Array.from(this.getPackages()).map((pkg) =>
pkg.collapse());
}
destroy() {
this.unwatch;
return this.emitter.emit("did-destroy");
}
unwatch() {
if(this.watchSubscription != null) {
this.watchSubscription.close();
return this.watchSubscription = null;
}
}
};
Folder.initClass();
module.exports = Folder;
|
var fs = require('fs');
var FTP = require('ftp');
var client = new FTP();
client.on('ready', function() {
client.list(function(err, list) {
if (err)
throw err;
client.get(list[1].name, function(err, stream) {
if (err)
throw err;
var output = fs.createWriteStream(list[1].name);
stream.pipe(output);
stream.on('close', function() {
client.end();
});
});
});
});
client.connect({
host: 'ftp.speed.hinet.net',
user: 'ftp',
password: 'ftp'
});
|
/**
* This is a manifest file that will be compiled into application.js, which will
* include all the files listed below.
*
* Any JavaScript file within this directory can be referenced here using a
* relative path.
*
* It's not advisable to add code directly here, but if you do, it will appear
* at the bottom of the compiled file.
*/
//= require lib/jquery-2.1.0.min
//= require lib/bootstrap.min
//= require lib/d3.v3.min.js
//= require main
|
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
'environments': 'environments',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
defaultExtension: 'js',
meta: {
'./*.js': {
loader: 'systemjs-angular-loader.js'
}
}
},
environments: {
defaultExtension: 'js'
},
rxjs: {
main: "Rx.js",
defaultExtension: 'js'
}
}
});
})(this);
|
KISSY.use('grid/util',function(S,Util){
describe("测试mask", function(){
var el = S.one('#J_Mask');
it('测试mask生成 ',function(){
Util.maskElement(el);
expect(el.one('.ks-ext-mask')).not.toBe(null);
});
it('测试mask取消',function(){
Util.unmaskElement(el);
expect(el.one('.ks-ext-mask')).toBe(null);
});
it('测试显示mask信息',function(){
Util.maskElement(el,'这是Mask');
expect(el.one('.ks-ext-mask')).not.toBe(null);
expect(el.one('.ks-ext-mask-msg')).not.toBe(null);
});
});
describe("测试load mask", function(){
var el = S.one('#J_LoadMask'),
loadMask = new Util.LoadMask(el);
it('测试显示loadMask ',function(){
loadMask.show();
expect(el.one('.ks-ext-mask')).not.toBe(null);
expect(el.one('.x-mask-loading')).not.toBe(null);
});
it('测试隐藏loadMask ',function(){
loadMask.hide();
expect(el.one('.ks-ext-mask')).toBe(null);
expect(el.one('.x-mask-loading')).toBe(null);
loadMask.show();
});
});
describe("测试renderer", function(){
var d = 1340595056900;
it('测试日期',function(){
var v = Util.Format.dateRenderer(d);
expect(v).toBe('2012-06-25');
});
it('测试日期时间 ',function(){
var v = Util.Format.datetimeRenderer(d);
expect(v).toBe('2012-06-25 11:30:56');
});
it('测试枚举 ',function(){
});
});
}); |
'use strict';
(function() {
// Resume Controller Spec
describe('Resume Controller Tests', function() {
// Initialize global variables
var ResumeController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Resume controller.
ResumeController = $controller('ResumeController', {
$scope: scope
});
}));
it('Should do some controller test', inject(function() {
// The test logic
// ...
}));
});
}()); |
/*!
* mime-types
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var db = require('mime-db');
var extname = require('path').extname;
/**
* Module variables.
* @private
*/
var extractTypeRegExp = /^\s*([^;\s]*)(?:;|\s|$)/;
var textTypeRegExp = /^text\//i;
/**
* Module exports.
* @public
*/
exports.charset = charset;
exports.charsets = { lookup: charset };
exports.contentType = contentType;
exports.extension = extension;
exports.extensions = Object.create(null);
exports.lookup = lookup;
exports.types = Object.create(null);
// Populate the extensions/types maps
populateMaps(exports.extensions, exports.types);
/**
* Get the default charset for a MIME type.
*
* @param {string} type
* @return {boolean|string}
*/
function charset(type) {
if (!type || typeof type !== 'string') {
return false;
}
// TODO: use media-typer
var match = extractTypeRegExp.exec(type);
var mime = match && db[match[1].toLowerCase()];
if (mime && mime.charset) {
return mime.charset;
}
// default text/* to utf-8
if (match && textTypeRegExp.test(match[1])) {
return 'UTF-8';
}
return false;
}
/**
* Create a full Content-Type header given a MIME type or extension.
*
* @param {string} str
* @return {boolean|string}
*/
function contentType(str) {
// TODO: should this even be in this module?
if (!str || typeof str !== 'string') {
return false;
}
var mime = str.indexOf('/') === -1 ? exports.lookup(str) : str;
if (!mime) {
return false;
}
// TODO: use content-type or other module
if (mime.indexOf('charset') === -1) {
var charset = exports.charset(mime);
if (charset) mime += '; charset=' + charset.toLowerCase();
}
return mime;
}
/**
* Get the default extension for a MIME type.
*
* @param {string} type
* @return {boolean|string}
*/
function extension(type) {
if (!type || typeof type !== 'string') {
return false;
}
// TODO: use media-typer
var match = extractTypeRegExp.exec(type);
// get extensions
var exts = match && exports.extensions[match[1].toLowerCase()];
if (!exts || !exts.length) {
return false;
}
return exts[0];
}
/**
* Lookup the MIME type for a file path/extension.
*
* @param {string} path
* @return {boolean|string}
*/
function lookup(path) {
if (!path || typeof path !== 'string') {
return false;
}
// get the extension ("ext" or ".ext" or full path)
var extension = extname('x.' + path).toLowerCase().substr(1);
if (!extension) {
return false;
}
return exports.types[extension] || false;
}
/**
* Populate the extensions and types maps.
* @private
*/
function populateMaps(extensions, types) {
// source preference (least -> most)
var preference = ['nginx', 'apache', undefined, 'iana'];
Object.keys(db).forEach(function forEachMimeType(type) {
var mime = db[type];
var exts = mime.extensions;
if (!exts || !exts.length) {
return;
}
// mime -> extensions
extensions[type] = exts;
// extension -> mime
for (var i = 0; i < exts.length; i++) {
var extension = exts[i];
if (types[extension]) {
var from = preference.indexOf(db[types[extension]].source);
var to = preference.indexOf(mime.source);
if (types[extension] !== 'application/octet-stream' && from > to || from === to && types[extension].substr(0, 12) === 'application/') {
// skip the remapping
continue;
}
}
// set the extension -> mime
types[extension] = type;
}
});
}
//# sourceMappingURL=index-compiled.js.map |
/* Copyright (c) 2014-2017 Richard Rodger and other contributors, MIT License */
var Seneca = require('seneca')
Seneca({tag: 'github'})
.test()
.use('monitor')
.use('entity')
.use('jsonfile-store', {folder: __dirname+'/../data'})
.use('../github.js')
.use('mesh', {
listen: [
{pin: 'role:github'},
{pin: 'role:info,need:part', model:'observe'}
]
})
.add('role:info,need:part', function (msg, reply) {
reply()
this.act(
'role:github,cmd:get', {name:msg.name},
function (err, mod) {
if (err) return
if (mod) {
return this.act('role:info,collect:part,part:github',
{name:msg.name,data:this.util.clean(mod.data$())})
}
this.act(
'role:npm,cmd:get', {name:msg.name},
function (err, mod) {
if (err) return
if (mod) {
this.act(
'role:github,cmd:get', {name:msg.name, giturl:mod.giturl},
function( err, mod ){
if( err ) return
if( mod ) {
this.act('role:info,collect:part,part:github',
{name:msg.name,data:this.util.clean(mod.data$())})
}
})
}
})
})
})
|
var session = require('express-session');
var passport = require('passport');
var sop = require('simple-object-path');
const authenticationMiddleware = function (req, res, next) {
if (req.isAuthenticated()) {
if (!req.cookies.username) {
res.cookie('username', req.user.username, { maxAge: 900000, httpOnly: true });
}
return next();
}
if (/json/.test(req.headers.accept)) {
res.send({ error: 'not logged in' });
return;
}
// redirect to URL if not logged in before request
if (req.session) {
req.session.returnTo = req.originalUrl || req.url;
}
res.redirect('./login');
};
function redisProtect(req, res, next) {
res.header('Cache-Control', 'no-cache');
const token = sop(req.session, 'passport/user/accessToken');
const user_id = sop(req.session, 'passport/user/user_id');
const id = sop(req.session, 'passport/user/id');
//console.log(req.session);
if (!token && !user_id && !id) {
const redirectUrl = 'https://auth.crosshj.com/';
const redirectTo = 'https://cents.crosshj.com' + req.originalUrl;
if (req.session) {
req.session.redirectTo = redirectTo;
}
return res.redirect(redirectUrl);
}
res.locals.token = token;
res.locals.user_id = user_id;
res.locals.id = id;
next();
}
function redisSession(settings) {
const RedisStore = require('connect-redis')(session);
return session({
secret: settings.cookieSecret,
name: 'gAuthSess',
store: new RedisStore({
host: 'redis',
port: 6379
}),
resave: false,
saveUninitialized: true,
cookie: {
path: '/',
domain: '.crosshj.com'
}
});
}
function fileStoreSession(settings) {
var store = ((sess) => {
const FileStore = require('session-file-store')(sess);
const fileStoreOptions = {
path: settings.folderLocation
};
const store = new FileStore(fileStoreOptions);
return store;
})(session);
return session({
secret: settings.cookieSecret,
store,
resave: false,
saveUninitialized: false
});
}
function mongoSession(settings) {
var store = ((sess) => {
var MongoDBStore = require('connect-mongodb-session')(sess);
const connectErrorCallback = (error) => {
if (error) {
console.log({ mongoConnectError: error });
}
};
var store = new MongoDBStore({
uri: 'mongodb://ubuntu:27017',
databaseName: 'cents',
collection: 'sessions'
}, connectErrorCallback);
store.on('error', connectErrorCallback);
return store;
})(session);
session({
secret: settings.cookieSecret,
store,
resave: false,
saveUninitialized: false
});
}
class AppSession {
constructor(app, store, settings) {
this.store = store;
const whichSession = {
mongo: mongoSession,
redis: redisSession,
file: fileStoreSession
}[store] || fileStoreSession;
this.express = whichSession(settings);
app.use(this.express);
app.use(passport.initialize());
app.use(passport.session());
if (store === 'mongo' || store === 'file') {
var authentication = require('./authentication');
authentication.init(app);
}
if (store === 'redis') {
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
}
const whichProtect = {
mongo: authenticationMiddleware,
redis: redisProtect,
file: authenticationMiddleware
}[store] || authenticationMiddleware;
this.protect = whichProtect;
}
}
module.exports = AppSession;
|
/**
* PageSchema middlewares
* @author heroic
*/
/**
* Module dependencies
*/
var xss = require('../xss');
module.exports = exports = function(schema) {
// 执行数据验证之前
schema
.pre('validate', function(next) {
xss(this, ['title', 'contentHtml']);
next();
});
// 执行数据保存之前
schema
.pre('save', function(next) {
// 每次编辑页面之后增加其版本号
if (!this.isNew) {
this.version += 1;
}
next();
});
}; |
(function () {
'use strict';
window.InlineShortcodeView_vc_single_image = window.InlineShortcodeView.extend( {
render: function () {
var model_id = this.model.get( 'id' );
window.InlineShortcodeView_vc_single_image.__super__.render.call( this );
vc.frame_window.vc_iframe.addActivity( function () {
if ( 'undefined' !== typeof (this.vc_image_zoom) ) {
this.vc_image_zoom( model_id );
}
} );
return this;
},
parentChanged: function () {
var model_id = this.model.get( 'id' );
window.InlineShortcodeView_vc_single_image.__super__.parentChanged.call( this );
if ( 'undefined' !== typeof (vc.frame_window.vc_image_zoom) ) {
_.defer( function () {
vc.frame_window.vc_image_zoom( model_id );
} );
}
return this;
}
} );
})(); |
// Generated by CoffeeScript 1.6.3
(function() {
window.load_compete = function() {
return $.getScript("compete/game.min.js", function() {
return $.getScript("compete/lib/API.js", function() {
return $.getScript("compete/lib/jquery-ui.js", function() {
return $.getScript("compete/lib/hintinit.js");
});
});
});
};
}).call(this);
|
module.exports = {
plugins: [
require.resolve("@babel/plugin-syntax-jsx")
]
} |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fillOpacity=".3" d="M18 9.52V6h-3.52L12 3.52 9.52 6H6v3.52L3.52 12 6 14.48V18h3.52L12 20.48 14.48 18H18v-3.52L20.48 12 18 9.52zM14.3 16l-.7-2h-3.2l-.7 2H7.8L11 7h2l3.2 9h-1.9zm-3.45-3.35h2.3L12 9z" /><path d="M11 7l-3.2 9h1.9l.7-2h3.2l.7 2h1.9L13 7h-2zm-.15 5.65L12 9l1.15 3.65h-2.3zM20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zm-2 5.79V18h-3.52L12 20.48 9.52 18H6v-3.52L3.52 12 6 9.52V6h3.52L12 3.52 14.48 6H18v3.52L20.48 12 18 14.48z" /></React.Fragment>
, 'BrightnessAutoTwoTone');
|
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var join = require('join-path');
var through = require('through2');
var mime = require('mime-types');
var onHeaders = require('on-headers');
var onFinished = require('on-finished');
var destroy = require('destroy');
module.exports = function (imports) {
var req = imports.req;
var res = imports.res;
var provider = imports.provider;
if (!res) {
throw new TypeError('response object required');
}
if (!provider) {
throw new TypeError('provider required');
}
// Set up helpers on response object
res.__ = {};
res.__.send = send;
res.__.sendFile = sendFile;
res.__.ext = ext;
res.__.status = status;
res.__.redirect = redirect;
var customExtensionType = false;
function send (data) {
var contentType = mime.contentType('html');
if (typeof data === 'object') {
data = JSON.stringify(data);
contentType = mime.contentType('json');
}
var len = Buffer.byteLength(data, 'utf8');
var etag = generateEtag(data, len);
onHeaders(res, function () {
// Only set this if we didn't specify a custom extension type
if (!customExtensionType && !res.getHeader('Content-Type')) {
res.setHeader('Content-Type', contentType);
}
res.setHeader('Content-Length', len);
if (etaggifyResponse(etag)) {
data = '';
}
});
// On next tick so it's chainable
process.nextTick(function () {
res.end(data);
});
return res;
}
function sendFile (pathname) {
var stream = through();
// Adjust pathname for serving a directory index file
if (provider.isDirectoryIndexSync(pathname) || pathname === '/') {
pathname = provider.asDirectoryIndex(pathname);
}
// Ensure we only serve files, not directories
provider.isFile(pathname, function (exists) {
if (!exists) {
var err = new Error('not found');
err.status = 404;
stream.emit('error', err);
}
else {
provider.createReadStream(pathname, imports)
.pipe(stream);
var contentType = mime.contentType(path.extname(pathname));
var stat = provider.statSync(pathname);
var etag = generateEtag(stat, stat.size);
onHeaders(res, function () {
res.setHeader('Content-Type', contentType);
if (!res.getHeader('Content-Length')) {
res.setHeader('Content-Length', stat.size);
}
etaggifyResponse(etag);
stream.emit('headers', res);
});
// Send file to resposne
stream.pipe(res);
}
});
// Handle the end of a response
onFinished(res, function () {
destroy(stream);
});
// Extend the stream so response helpers
// are chainable in any order
return stream;
}
function ext (extension) {
customExtensionType = true;
onHeaders(res, function () {
res.setHeader('Content-Type', mime.contentType(extension));
});
return res;
}
function status (code) {
res.statusCode = code;
return res;
}
function redirect (location, status) {
status = status || 301;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.writeHead(status, {
'Location': location
});
res.__.send('Redirecting to ' + location + ' ...');
}
function generateEtag (data, len) {
var isHead = req.method === 'HEAD';
var etag;
if (len !== undefined && (isHead || req.method === 'GET')) {
if (!res.getHeader('ETag') && provider.generateEtag) {
etag = provider.generateEtag(data);
}
}
return etag;
}
function etaggifyResponse (etag) {
// Set ETag header
if (etag) {
res.setHeader('ETag', etag);
}
var f = cacheIsFresh(req, res);
// Remove headers if Etag is fresh
if (f) {
res.statusCode = 304;
res.removeHeader('Content-Type');
res.removeHeader('Content-Length');
res.removeHeader('Transfer-Encoding');
}
return f;
}
function cacheIsFresh () {
var reqEtag = req.headers['if-none-match'];
var resEtag = res.getHeader('ETag');
// If etags disabled, don't want to assume
// that undefined etags are equal
if (reqEtag === undefined || resEtag === undefined) {
return false;
}
return reqEtag === resEtag;
}
return res;
}; |
module.exports.setTestTimers = function(calls) {
setTimeout(function() {
calls.push(1);
}, 100);
setInterval(function() {
calls.push(2);
}, 100);
setTimeout(function() {
calls.push(3);
}, 100);
setTimeout(function() {
calls.push(4);
}, 100);
setTimeout(function() {
calls.push(6);
}, 200);
setTimeout(function() {
calls.push(7);
}, 300);
setInterval(function() {
calls.push(5);
}, 100);
};
|
import hammerhead from '../../deps/hammerhead';
import testCafeCore from '../../deps/testcafe-core';
import testCafeUI from '../../deps/testcafe-ui';
import VisibleElementAutomation from '../visible-element-automation';
import { focusAndSetSelection, focusByRelatedElement } from '../../utils/utils';
import cursor from '../../cursor';
import nextTick from '../../utils/next-tick';
var Promise = hammerhead.Promise;
var extend = hammerhead.utils.extend;
var browserUtils = hammerhead.utils.browser;
var featureDetection = hammerhead.utils.featureDetection;
var eventSimulator = hammerhead.eventSandbox.eventSimulator;
var domUtils = testCafeCore.domUtils;
var styleUtils = testCafeCore.styleUtils;
var eventUtils = testCafeCore.eventUtils;
var arrayUtils = testCafeCore.arrayUtils;
var delay = testCafeCore.delay;
var selectElementUI = testCafeUI.selectElement;
export default class ClickAutomation extends VisibleElementAutomation {
constructor (element, clickOptions) {
super(element, clickOptions);
this.modifiers = clickOptions.modifiers;
this.caretPos = clickOptions.caretPos;
this.targetElementParentNodes = [];
this.activeElementBeforeMouseDown = null;
this.mouseDownElement = null;
this.eventState = {
mousedownPrevented: false,
blurRaised: false,
simulateDefaultBehavior: true,
clickElement: null
};
}
_bindMousedownHandler () {
var onmousedown = e => {
this.eventState.mousedownPrevented = e.defaultPrevented;
eventUtils.preventDefault(e);
eventUtils.unbind(this.element, 'mousedown', onmousedown);
};
eventUtils.bind(this.element, 'mousedown', onmousedown);
}
_bindBlurHandler (element) {
var onblur = () => {
this.eventState.blurRaised = true;
eventUtils.unbind(element, 'blur', onblur, true);
};
eventUtils.bind(element, 'blur', onblur, true);
}
_raiseTouchEvents (eventArgs) {
if (featureDetection.isTouchDevice) {
eventSimulator.touchstart(eventArgs.element, eventArgs.options);
eventSimulator.touchend(eventArgs.element, eventArgs.options);
}
}
_mousedown (eventArgs) {
this.targetElementParentNodes = domUtils.getParents(eventArgs.element);
this.mouseDownElement = eventArgs.element;
return cursor.leftButtonDown()
.then(() => {
this._raiseTouchEvents(eventArgs);
var activeElement = domUtils.getActiveElement();
this.activeElementBeforeMouseDown = activeElement;
// NOTE: In WebKit and IE, the mousedown event opens the select element's dropdown;
// therefore, we should prevent mousedown and hide the dropdown (B236416).
var needCloseSelectDropDown = (browserUtils.isWebKit || browserUtils.isIE) &&
domUtils.isSelectElement(this.element);
if (needCloseSelectDropDown)
this._bindMousedownHandler();
this._bindBlurHandler(activeElement);
this.eventState.simulateDefaultBehavior = eventSimulator.mousedown(eventArgs.element, eventArgs.options);
if (this.eventState.simulateDefaultBehavior === false)
this.eventState.simulateDefaultBehavior = needCloseSelectDropDown && !this.eventState.mousedownPrevented;
return this._ensureActiveElementBlur(activeElement);
})
.then(() => this._focus(eventArgs));
}
_ensureActiveElementBlur (element) {
// NOTE: In some cases, mousedown may lead to active element change (browsers raise blur).
// We simulate the blur event if the active element was changed after the mousedown, and
// the blur event does not get raised automatically (B239273, B253520)
return new Promise(resolve => {
var simulateBlur = domUtils.getActiveElement() !== element && !this.eventState.blurRaised;
if (!simulateBlur) {
resolve();
return;
}
if (browserUtils.isIE && browserUtils.version < 12) {
// NOTE: In whatever way an element is blurred from the client script, the
// blur event is raised asynchronously in IE (in MSEdge focus/blur is sync)
nextTick()
.then(() => {
if (!this.eventState.blurRaised)
eventSimulator.blur(element);
resolve();
});
}
else {
eventSimulator.blur(element);
resolve();
}
});
}
_focus (eventArgs) {
if (this.eventState.simulateDefaultBehavior === false)
return Promise.resolve();
// NOTE: If a target element is a contentEditable element, we need to call focusAndSetSelection directly for
// this element. Otherwise, if the element obtained by elementFromPoint is a child of the contentEditable
// element, a selection position may be calculated incorrectly (by using the caretPos option).
var elementForFocus = domUtils.isContentEditableElement(this.element) ? this.element : eventArgs.element;
// NOTE: IE doesn't perform focus if active element has been changed while executing mousedown
var simulateFocus = !browserUtils.isIE || this.activeElementBeforeMouseDown === domUtils.getActiveElement();
return focusAndSetSelection(elementForFocus, simulateFocus, this.caretPos);
}
static _getElementForClick (mouseDownElement, topElement, mouseDownElementParentNodes) {
var topElementParentNodes = domUtils.getParents(topElement);
var areElementsSame = domUtils.isTheSameNode(topElement, mouseDownElement);
// NOTE: Mozilla Firefox always skips click, if an element under cursor has been changed after mousedown.
if (browserUtils.isFirefox)
return areElementsSame ? mouseDownElement : null;
if (!areElementsSame) {
if (mouseDownElement.contains(topElement) && !domUtils.isEditableFormElement(topElement))
return mouseDownElement;
if (topElement.contains(mouseDownElement))
return topElement;
// NOTE: If elements are not in the parent-child relationships,
// non-ff browsers raise the `click` event for their common parent.
return arrayUtils.getCommonElement(topElementParentNodes, mouseDownElementParentNodes);
}
// NOTE: In case the target element and the top element are the same,
// non-FF browsers are dispatching the `click` event if the target
// element hasn't changed its position in the DOM after mousedown.
return arrayUtils.equals(mouseDownElementParentNodes, topElementParentNodes) ? mouseDownElement : null;
}
_mouseup (eventArgs) {
return cursor
.buttonUp()
.then(() => this._getElementForEvent(eventArgs))
.then(element => {
eventArgs.element = element;
this.eventState.clickElement = ClickAutomation._getElementForClick(this.mouseDownElement, element,
this.targetElementParentNodes);
eventSimulator.mouseup(element, eventArgs.options);
});
}
_click (eventArgs) {
if (domUtils.isOptionElement(eventArgs.element))
return eventArgs.element;
if (this.eventState.clickElement)
eventSimulator.click(this.eventState.clickElement, eventArgs.options);
if (!domUtils.isElementFocusable(eventArgs.element))
focusByRelatedElement(eventArgs.element);
// NOTE: Emulating the click event on the 'select' element doesn't expand the
// dropdown with options (except chrome), therefore we should emulate it.
var isSelectElement = domUtils.isSelectElement(eventArgs.element);
var isSelectWithDropDown = isSelectElement && styleUtils.getSelectElementSize(eventArgs.element) === 1;
if (isSelectWithDropDown && this.eventState.simulateDefaultBehavior !== false) {
if (selectElementUI.isOptionListExpanded(eventArgs.element))
selectElementUI.collapseOptionList();
else
selectElementUI.expandOptionList(eventArgs.element);
}
return eventArgs;
}
run (useStrictElementCheck) {
var eventArgs = null;
return this
._ensureElement(useStrictElementCheck)
.then(({ element, clientPoint, screenPoint }) => {
eventArgs = {
point: clientPoint,
screenPoint: screenPoint,
element: element,
options: extend({
clientX: clientPoint.x,
clientY: clientPoint.y
}, this.modifiers)
};
// NOTE: we should raise mouseup event with 'mouseActionStepDelay' after we trigger
// mousedown event regardless of how long mousedown event handlers were executing
return Promise.all([delay(this.automationSettings.mouseActionStepDelay), this._mousedown(eventArgs)]);
})
.then(() => this._mouseup(eventArgs))
.then(() => this._click(eventArgs));
}
}
|
$(function()
{
/* set navbar */
var $header = $('body > header');
$header.load('dashboard/menus.html', function()
{
if(!$('#navbar').length)
{
$('body').addClass('without-navbar');
return;
}
var tab = $header.data('tab') || 'index',
$navbarCollapse = $('#navbar-collapse');
if(tab != 'index')
{
var $navTab = $navbarCollapse.find('[data-tab="' + tab + '"]');
$navTab.removeClass('collapsed');
document.title = $navTab.find('.nav-heading').text() + ' - ' + document.title;
}
$navbarCollapse.find('.nav > li > a').each(function()
{
var $this = $(this);
var href = $this.attr('href');
var target = href.substring(href.indexOf('#'), href.length);
$this.attr('data-target', target).attr('href', $this.attr('href'));
});
$('body').addClass('with-navbar').scrollspy({target: '#navbar-collapse'});
// navbar collapse
$navbarCollapse.find('.nav > .nav-heading').click(function()
{
var $nav = $(this).closest('.nav');
if($nav.hasClass('collapsed'))
{
$('.navbar-collapsed .nav').not($nav).children('li:not(.nav-heading)').slideUp('fast', function(){
$(this).closest('.nav').addClass('collapsed');
});
if($(window).width() < 767)
{
}
$nav.removeClass('collapsed').children('li:not(.nav-heading)').slideDown('fast');
}
else
{
$nav.children('li:not(.nav-heading)').slideUp('fast', function(){$nav.addClass('collapsed');});
}
});
});
}); |
define(["dojox/main", "dojo/_base/lang", "dojo/_base/array", "dojo/date", "dojo/i18n", "dojo/regexp", "dojo/string", "./Date", "dojo/i18n!dojo/cldr/nls/persian"],
function(dojox, lang, arr, dd, i18n, regexp, string, IDate, bundle){
var ilocale = lang.getObject("date.persian.locale", true, dojox);
// dojo.requireLocalization("dojo.cldr", "persian");
// Format a pattern without literals
function formatPattern(dateObject, bundle, locale, fullYear, pattern){
return pattern.replace(/([a-z])\1*/ig, function(match){
var s, pad;
var c = match.charAt(0);
var l = match.length;
var widthList = ["abbr", "wide", "narrow"];
switch(c){
case 'G':
s = bundle["eraAbbr"][0];
break;
case 'y':
s = String(dateObject.getFullYear());
break;
case 'M':
var m = dateObject.getMonth();
if(l<3){
s = m+1; pad = true;
}else{
var propM = ["months", "format", widthList[l-3]].join("-");
s = bundle[propM][m];
}
break;
case 'd':
s = dateObject.getDate(true); pad = true;
break;
case 'E':
var d = dateObject.getDay();
if(l<3){
s = d+1; pad = true;
}else{
var propD = ["days", "format", widthList[l-3]].join("-");
s = bundle[propD][d];
}
break;
case 'a':
var timePeriod = (dateObject.getHours() < 12) ? 'am' : 'pm';
s = bundle['dayPeriods-format-wide-' + timePeriod];
break;
case 'h':
case 'H':
case 'K':
case 'k':
var h = dateObject.getHours();
switch (c){
case 'h': // 1-12
s = (h % 12) || 12;
break;
case 'H': // 0-23
s = h;
break;
case 'K': // 0-11
s = (h % 12);
break;
case 'k': // 1-24
s = h || 24;
break;
}
pad = true;
break;
case 'm':
s = dateObject.getMinutes(); pad = true;
break;
case 's':
s = dateObject.getSeconds(); pad = true;
break;
case 'S':
s = Math.round(dateObject.getMilliseconds() * Math.pow(10, l-3)); pad = true;
break;
case 'z':
// We only have one timezone to offer; the one from the browser
s = dd.getTimezoneName(dateObject.toGregorian());
if(s){ break; }
l = 4;
// fallthrough... use GMT if tz not available
case 'Z':
var offset = dateObject.toGregorian().getTimezoneOffset();
var tz = [
(offset <= 0 ? "+" : "-"),
string.pad(Math.floor(Math.abs(offset) / 60), 2),
string.pad(Math.abs(offset) % 60, 2)
];
if(l == 4){
tz.splice(0, 0, "GMT");
tz.splice(3, 0, ":");
}
s = tz.join("");
break;
default:
throw new Error("dojox.date.persian.locale.formatPattern: invalid pattern char: "+pattern);
}
if(pad){ s = string.pad(s, l); }
return s;
});
}
// based on and similar to dojo.date.locale.format
ilocale.format = function(/*dojox/date/persian/Date*/dateObject, /*Object?*/options){
// summary:
// Format a Date object as a String, using settings.
options = options || {};
var locale = i18n.normalizeLocale(options.locale);
var formatLength = options.formatLength || 'short';
var bundle = ilocale._getPersianBundle(locale);
var str = [];
var sauce = lang.hitch(this, formatPattern, dateObject, bundle, locale, options.fullYear);
if(options.selector == "year"){
var year = dateObject.getFullYear();
return year;
}
if(options.selector != "time"){
var datePattern = options.datePattern || bundle["dateFormat-"+formatLength];
if(datePattern){str.push(_processPattern(datePattern, sauce));}
}
if(options.selector != "date"){
var timePattern = options.timePattern || bundle["timeFormat-"+formatLength];
if(timePattern){str.push(_processPattern(timePattern, sauce));}
}
var result = str.join(" "); //TODO: use locale-specific pattern to assemble date + time
return result; // String
};
ilocale.regexp = function(/*object?*/options){
// summary:
// Builds the regular needed to parse a persian.Date
// based on and similar to dojo.date.locale.regexp
return ilocale._parseInfo(options).regexp; // String
};
ilocale._parseInfo = function(/*oblect?*/options){
/* based on and similar to dojo.date.locale._parseInfo */
options = options || {};
var locale = i18n.normalizeLocale(options.locale);
var bundle = ilocale._getPersianBundle(locale);
var formatLength = options.formatLength || 'short';
var datePattern = options.datePattern || bundle["dateFormat-" + formatLength];
var timePattern = options.timePattern || bundle["timeFormat-" + formatLength];
var pattern;
if(options.selector == 'date'){
pattern = datePattern;
}else if(options.selector == 'time'){
pattern = timePattern;
}else{
pattern = (typeof (timePattern) == "undefined") ? datePattern : datePattern + ' ' + timePattern;
}
var tokens = [];
var re = _processPattern(pattern, lang.hitch(this, _buildDateTimeRE, tokens, bundle, options));
return {regexp: re, tokens: tokens, bundle: bundle};
};
ilocale.parse = function(/*String*/value, /*Object?*/options){
// summary:
// This function parse string date value according to options
// based on and similar to dojo.date.locale.parse
value = value.replace(/[\u200E\u200F\u202A\u202E]/g, ""); //remove bidi non-printing chars
if(!options){ options={}; }
var info = ilocale._parseInfo(options);
var tokens = info.tokens, bundle = info.bundle;
var regexp = info.regexp.replace(/[\u200E\u200F\u202A\u202E]/g, ""); //remove bidi non-printing chars from the pattern
var re = new RegExp("^" + regexp + "$");
var match = re.exec(value);
var locale = i18n.normalizeLocale(options.locale);
if(!match){ return null; } // null
var date, date1;
var result = [1389,0,1,0,0,0,0]; //FIXME: persian date for [1970,0,1,0,0,0,0] used in gregorian locale
var amPm = "";
var mLength = 0;
var widthList = ["abbr", "wide", "narrow"];
var valid = arr.every(match, function(v, i){
if(!i){return true;}
var token=tokens[i-1];
var l=token.length;
switch(token.charAt(0)){
case 'y':
result[0] = Number(v);
break;
case 'M':
if(l>2){
var months = bundle['months-format-' + widthList[l-3]].concat();
if(!options.strict){
//Tolerate abbreviating period in month part
//Case-insensitive comparison
v = v.replace(".","").toLowerCase();
months = arr.map(months, function(s){ return s ? s.replace(".","").toLowerCase() : s; } );
}
v = arr.indexOf(months, v);
if(v == -1){
return false;
}
mLength = l;
}else{
v--;
}
result[1] = Number(v);
break;
case 'D':
result[1] = 0;
// fallthrough...
case 'd':
result[2] = Number(v);
break;
case 'a': //am/pm
var am = options.am || bundle['dayPeriods-format-wide-am'],
pm = options.pm || bundle['dayPeriods-format-wide-pm'];
if(!options.strict){
var period = /\./g;
v = v.replace(period,'').toLowerCase();
am = am.replace(period,'').toLowerCase();
pm = pm.replace(period,'').toLowerCase();
}
if(options.strict && v != am && v != pm){
return false;
}
// we might not have seen the hours field yet, so store the state and apply hour change later
amPm = (v == pm) ? 'p' : (v == am) ? 'a' : '';
break;
case 'K': //hour (1-24)
if(v == 24){ v = 0; }
// fallthrough...
case 'h': //hour (1-12)
case 'H': //hour (0-23)
case 'k': //hour (0-11)
//in the 12-hour case, adjusting for am/pm requires the 'a' part
//which could come before or after the hour, so we will adjust later
result[3] = Number(v);
break;
case 'm': //minutes
result[4] = Number(v);
break;
case 's': //seconds
result[5] = Number(v);
break;
case 'S': //milliseconds
result[6] = Number(v);
}
return true;
});
var hours = +result[3];
if(amPm === 'p' && hours < 12){
result[3] = hours + 12; //e.g., 3pm -> 15
}else if(amPm === 'a' && hours == 12){
result[3] = 0; //12am -> 0
}
var dateObject = new IDate(result[0], result[1], result[2], result[3], result[4], result[5], result[6]);
return dateObject;
};
function _processPattern(pattern, applyPattern, applyLiteral, applyAll){
// summary:
// Process a pattern with literals in it
// Break up on single quotes, treat every other one as a literal, except '' which becomes '
var identity = function(x){return x;};
applyPattern = applyPattern || identity;
applyLiteral = applyLiteral || identity;
applyAll = applyAll || identity;
//split on single quotes (which escape literals in date format strings)
//but preserve escaped single quotes (e.g., o''clock)
var chunks = pattern.match(/(''|[^'])+/g);
var literal = pattern.charAt(0) == "'";
arr.forEach(chunks, function(chunk, i){
if(!chunk){
chunks[i]='';
}else{
chunks[i]=(literal ? applyLiteral : applyPattern)(chunk);
literal = !literal;
}
});
return applyAll(chunks.join(''));
}
function _buildDateTimeRE (tokens, bundle, options, pattern){
// based on and similar to dojo.date.locale._buildDateTimeRE
pattern = regexp.escapeString(pattern);
var locale = i18n.normalizeLocale(options.locale);
return pattern.replace(/([a-z])\1*/ig, function(match){
// Build a simple regexp. Avoid captures, which would ruin the tokens list
var s;
var c = match.charAt(0);
var l = match.length;
var p2 = '', p3 = '';
if(options.strict){
if(l > 1){ p2 = '0' + '{'+(l-1)+'}'; }
if(l > 2){ p3 = '0' + '{'+(l-2)+'}'; }
}else{
p2 = '0?'; p3 = '0{0,2}';
}
switch(c){
case 'y':
s = '\\d+';
break;
case 'M':
s = (l>2) ? '\\S+ ?\\S+' : p2+'[1-9]|1[0-2]';
break;
case 'd':
s = '[12]\\d|'+p2+'[1-9]|3[01]';
break;
case 'E':
s = '\\S+';
break;
case 'h': //hour (1-12)
s = p2+'[1-9]|1[0-2]';
break;
case 'k': //hour (0-11)
s = p2+'\\d|1[01]';
break;
case 'H': //hour (0-23)
s = p2+'\\d|1\\d|2[0-3]';
break;
case 'K': //hour (1-24)
s = p2+'[1-9]|1\\d|2[0-4]';
break;
case 'm':
case 's':
s = p2+'\\d|[0-5]\\d';
break;
case 'S':
s = '\\d{'+l+'}';
break;
case 'a':
var am = options.am || bundle['dayPeriods-format-wide-am'],
pm = options.pm || bundle['dayPeriods-format-wide-pm'];
if(options.strict){
s = am + '|' + pm;
}else{
s = am + '|' + pm;
if(am != am.toLowerCase()){ s += '|' + am.toLowerCase(); }
if(pm != pm.toLowerCase()){ s += '|' + pm.toLowerCase(); }
}
break;
default:
s = ".*";
}
if(tokens){ tokens.push(match); }
return "(" + s + ")"; // add capture
}).replace(/[\xa0 ]/g, "[\\s\\xa0]"); // normalize whitespace. Need explicit handling of \xa0 for IE. */
}
var _customFormats = [];
ilocale.addCustomFormats = function(/*String*/packageName, /*String*/bundleName){
// summary:
// Add a reference to a bundle containing localized custom formats to be
// used by date/time formatting and parsing routines.
_customFormats.push({pkg:packageName,name:bundleName});
};
ilocale._getPersianBundle = function(/*String*/locale){
var persian = {};
arr.forEach(_customFormats, function(desc){
var bundle = i18n.getLocalization(desc.pkg, desc.name, locale);
persian = lang.mixin(persian, bundle);
}, this);
return persian; /*Object*/
};
ilocale.addCustomFormats("dojo.cldr","persian");
ilocale.getNames = function(/*String*/item, /*String*/type, /*String?*/context, /*String?*/locale, /*dojox/date/persian/Date?*/date){
// summary:
// Used to get localized strings from dojo.cldr for day or month names.
var label;
var lookup = ilocale._getPersianBundle(locale);
var props = [item, context, type];
if(context == 'standAlone'){
var key = props.join('-');
label = lookup[key];
// Fall back to 'format' flavor of name
if(label[0] == 1){ label = undefined; } // kludge, in the absence of real aliasing support in dojo.cldr
}
props[1] = 'format';
// return by copy so changes won't be made accidentally to the in-memory model
return (label || lookup[props.join('-')]).concat(); /*Array*/
};
ilocale.weekDays = ilocale.getNames('days', 'wide', 'format');
ilocale.months = ilocale.getNames('months', 'wide', 'format');
return ilocale;
});
|
/**
* @license
* pathfinding-visualiser <http://github.com/Tyriar/pathfinding-visualiser>
* Copyright 2014 Daniel Imms <http://www.growingwiththeweb.com>
* Released under the MIT license <http://github.com/Tyriar/pathfinding-visualiser/blob/master/LICENSE>
*/
(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['a-star-heap', 'binary-heap'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('./a-star-heap'),
require('../../bower_components/js-data-structures/lib/binary-heap'));
}
}(this, function (aStarHeap, BinaryHeap) {
'use strict';
var module = {};
module.run = function (map, callback) {
aStarHeap.run(map, callback, BinaryHeap, function (heap) {
var list = heap.list;
for (var i = 0; i < list.length; i++) {
list[i] = list[i].value;
}
return list;
});
};
return module;
}));
|
/*
======================================
Custom dashboard telemetry data filter
======================================
*/
// This filter is used to change telemetry data
// before it is displayed on the dashboard.
// For example, you may convert km/h to mph, kilograms to tons, etc.
// "data" object is an instance of the Ets2TelemetryData class
// defined in dashboard-core.ts (or see JSON response in the server's API).
Funbit.Ets.Telemetry.Dashboard.prototype.filter = function (data) {
// If the game isn't connected, don't both calculating anything.
if (!data.game.connected) {
return data;
}
// Process DOM changes here now that we have data. We should only do this once.
if (!g_processedDomChanges) {
processDomChanges(data);
}
data.isEts2 = g_runningGame == 'ETS2';
data.isAts = !data.isEts2;
// Logic consistent between ETS2 and ATS
data.truckSpeedRounded = Math.abs(data.truck.speed > 0
? Math.floor(data.truck.speed)
: Math.round(data.truck.speed));
data.truckSpeedMph = data.truck.speed * 0.621371;
data.truckSpeedMphRounded = Math.abs(Math.floor(data.truckSpeedMph));
var distanceUnits = g_skinConfig[g_configPrefix].distanceUnits;
if (data.truck.cruiseControlOn && distanceUnits === 'mi') {
data.truck.cruiseControlSpeed = Math.round(data.truck.cruiseControlSpeed * .621371);
}
if (data.truck.shifterType === "automatic" || data.truck.shifterType === "arcade") {
data.gear = data.truck.displayedGear > 0 ? 'A' + data.truck.displayedGear : (data.truck.displayedGear < 0 ? 'R' + Math.abs(data.truck.displayedGear) : 'N');
} else {
data.gear = data.truck.displayedGear > 0 ? data.truck.displayedGear : (data.truck.displayedGear < 0 ? 'R' + Math.abs(data.truck.displayedGear) : 'N');
}
data.currentFuelPercentage = (data.truck.fuel / data.truck.fuelCapacity) * 100;
data.scsTruckDamage = getDamagePercentage(data);
data.scsTruckDamageRounded = Math.floor(data.scsTruckDamage);
data.wearTrailerRounded = Math.floor(data.trailer.wear * 100);
data.gameTime12h = getTime(data.game.time, 12);
var originalTime = data.game.time;
data.game.time = getTime(data.game.time, 24);
var tons = (data.trailer.mass / 1000.0).toFixed(2);
if (tons.substr(tons.length - 2) === "00") {
tons = parseInt(tons);
}
data.trailerMassTons = data.trailer.attached ? (tons + ' t') : '';
data.trailerMassKg = data.trailer.attached ? data.trailer.mass + ' kg' : '';
data.trailerMassLbs = data.trailer.attached ? Math.round(data.trailer.mass * 2.20462) + ' lb' : '';
data.game.nextRestStopTimeArray = getDaysHoursMinutesAndSeconds(data.game.nextRestStopTime);
data.game.nextRestStopTime = processTimeDifferenceArray(data.game.nextRestStopTimeArray);
data.navigation.speedLimitMph = data.navigation.speedLimit * .621371;
data.navigation.speedLimitMphRounded = Math.round(data.navigation.speedLimitMph);
data.navigation.estimatedDistanceKm = data.navigation.estimatedDistance / 1000;
data.navigation.estimatedDistanceMi = data.navigation.estimatedDistanceKm * .621371;
data.navigation.estimatedDistanceKmRounded = Math.floor(data.navigation.estimatedDistanceKm);
data.navigation.estimatedDistanceMiRounded = Math.floor(data.navigation.estimatedDistanceMi);
var timeToDestinationArray = getDaysHoursMinutesAndSeconds(data.navigation.estimatedTime);
data.navigation.estimatedTime = addTime(originalTime,
timeToDestinationArray[0],
timeToDestinationArray[1],
timeToDestinationArray[2],
timeToDestinationArray[3]).toISOString();
var estimatedTime24h = data.navigation.estimatedTime
data.navigation.estimatedTime = getTime(data.navigation.estimatedTime, 24);
data.navigation.estimatedTime12h = getTime(estimatedTime24h, 12);
data.navigation.timeToDestination = processTimeDifferenceArray(timeToDestinationArray);
// ETS2-specific logic
data.isWorldOfTrucksContract = isWorldOfTrucksContract(data);
data.job.remainingTimeArray = getDaysHoursMinutesAndSeconds(data.job.remainingTime);
data.job.remainingTime = processTimeDifferenceArray(data.job.remainingTimeArray);
if (data.isEts2) {
data.jobIncome = getEts2JobIncome(data.job.income);
}
// ATS-specific logic
if (data.isAts) {
data.jobIncome = getAtsJobIncome(data.job.income);
}
$('#_map').find('._no-map').hide();
// Non-WoT stuff here
if (!data.isWorldOfTrucksContract || data.isAts) {
data.jobDeadlineTime12h = getTime(data.job.deadlineTime, 12);
data.job.deadlineTime = getTime(data.job.deadlineTime, 24);
}
// return changed data to the core for rendering
return data;
};
Funbit.Ets.Telemetry.Dashboard.prototype.render = function (data) {
// If the game isn't connected, don't both calculating anything.
if (!data.game.connected) {
return data;
}
if (data.game.gameName != null) {
g_lastRunningGame = g_runningGame;
g_runningGame = data.game.gameName;
if (g_runningGame != g_lastRunningGame
&& g_lastRunningGame !== undefined) {
setLocalStorageItem('currentTab', $('._tabs').find('article:visible:first').attr('id'));
location.reload();
}
}
// data - same data object as in the filter function
$('.fillingIcon.truckDamage .top').css('height', (100 - data.scsTruckDamage) + '%');
$('.fillingIcon.trailerDamage .top').css('height', (100 - data.trailer.wear * 100) + '%');
$('.fillingIcon.fuel .top').css('height', (100 - data.currentFuelPercentage) + '%');
$('.fillingIcon.rest .top').css('height', (100 - getFatiguePercentage(data.game.nextRestStopTimeArray[1], data.game.nextRestStopTimeArray[2])) + '%');
// Process DOM for connection
if (data.game.connected) {
$('#_overlay').hide();
} else {
$('#_overlay').show();
}
if (data.truck.cruiseControlOn) {
$('.cruiseControl').show();
$('.noCruiseControl').hide();
$('._speed').css('color', 'lime');
} else {
$('.cruiseControl').hide();
$('.noCruiseControl').show();
$('._speed').css('color', 'white');
}
// Process DOM for job
if (data.trailer.attached) {
$('.hasJob').show();
$('.noJob').hide();
} else {
$('.hasJob').hide();
$('.noJob').show();
}
// Process map location only if the map has been rendered
if (g_map) {
// X is longitude-ish, Y is altitude-ish, Z is latitude-ish.
// http://forum.scssoft.com/viewtopic.php?p=422083#p422083
updatePlayerPositionAndRotation(
data.truck.placement.x,
data.truck.placement.z,
data.truck.placement.heading,
data.truck.speed
);
}
// If speed limit is "0", hide the speed limit display
if (data.navigation.speedLimit === 0) {
$('#speed-limit').hide();
} else {
$('#speed-limit').css('display', 'flex');
}
// Set skin to World of Trucks mode if this is a World of Trucks contract
if (data.isWorldOfTrucksContract) {
$('#expected > p[data-mra-text="Expected"]').text(g_translations.Remains);
$('#expected > p > span.job-deadlineTime').text(g_translations.WorldOfTrucksContract)
.css('color', '#0CAFF0');
$('#remains > p').css('visibility', 'hidden');
} else {
$('#expected > p[data-mra-text="Expected"]').text(g_translations.Expected);
$('#expected > p > span.job-deadlineTime').css('color', '#fff');
$('#remains > p').css('visibility', '');
}
// Set the current game attribute for any properties that are game-specific
$('.game-specific').attr('data-game-name', data.game.gameName);
// Update red bar if speeding
updateSpeedIndicator(data.navigation.speedLimit, data.truck.speed);
// Update UI if in special transport mission
updateDisplayForSpecialTransport(data.trailer.id);
return data;
}
Funbit.Ets.Telemetry.Dashboard.prototype.initialize = function (skinConfig) {
//
// skinConfig - a copy of the skin configuration from config.json
//
// this function is called before everything else,
// so you may perform any DOM or resource initializations here
g_skinConfig = skinConfig;
g_pathPrefix = 'skins/' + g_skinConfig.name;
// Process language JSON
$.getJSON(g_pathPrefix + '/language/' + g_skinConfig.language, function(json) {
g_translations = json;
$.each(json, function(key, value) {
updateLanguage(key, value);
});
});
// Check for updates
if (g_skinConfig.checkForUpdates) {
$.get('https://meatlayer.github.io/ets2-mobile-route-advisor/latest-version.html', function(data) {
var latestVersion = data.trim();
if (latestVersion != g_currentVersion) {
$('#update-status').show();
}
});
}
// Set the version number on the about page
versionText = $('#version').text();
$('#version').text(versionText + g_currentVersion);
var tabToShow = getLocalStorageItem('currentTab', '_cargo');
if (tabToShow == null) {
tabToShow = '_cargo';
}
removeLocalStorageItem('currentTab');
showTab(tabToShow);
}
function getDaysHoursMinutesAndSeconds(time) {
var dateTime = new Date(time);
var days = dateTime.getUTCDate();
var hour = dateTime.getUTCHours();
var minute = dateTime.getUTCMinutes();
var second = dateTime.getUTCSeconds();
return [days, hour, minute, second];
}
function addTime(time, days, hours, minutes, seconds) {
var dateTime = new Date(time);
return dateTime.addDays(days)
.addHours(hours)
.addMinutes(minutes)
.addSeconds(seconds);
}
function getFatiguePercentage(hoursUntilRest, minutesUntilRest) {
var FULLY_RESTED_TIME_REMAINING_IN_MILLISECONDS = 11*60*60*1000; // 11 hours * 60 min * 60 sec * 1000 milliseconds
if (hoursUntilRest <= 0 && minutesUntilRest <= 0) {
return 100;
}
var hoursInMilliseconds = hoursUntilRest * 60 * 60 * 1000; // # hours * 60 min * 60 sec * 1000 milliseconds
var minutesInMilliseconds = minutesUntilRest * 60 * 1000; // # minutes * 60 sec * 1000 milliseconds
return 100 - (((hoursInMilliseconds + minutesInMilliseconds) / FULLY_RESTED_TIME_REMAINING_IN_MILLISECONDS) * 100);
}
function processTimeDifferenceArray(hourMinuteArray) {
var day = hourMinuteArray[0];
var hours = hourMinuteArray[1];
var minutes = hourMinuteArray[2];
hours += (day - 1) * 24;
if (hours <= 0 && minutes <= 0) {
minutes = g_translations.XMinutes.replace('{0}', 0);
return minutes;
}
if (hours === 1) {
hours = g_translations.XHour.replace('{0}', hours);
} else if (hours === 0) {
hours = '';
} else {
hours = g_translations.XHours.replace('{0}', hours);
}
if (minutes === 1) {
minutes = g_translations.XMinute.replace('{0}', minutes);
} else {
minutes = g_translations.XMinutes.replace('{0}', minutes);
}
return hours + ' ' + minutes;
}
function getTime(gameTime, timeUnits) {
var currentTime = new Date(gameTime);
var currentPeriod = timeUnits === 12 ? ' AM' : '';
var currentHours = currentTime.getUTCHours();
var currentMinutes = currentTime.getUTCMinutes();
var formattedMinutes = currentMinutes < 10 ? '0' + currentMinutes : currentMinutes;
var currentDay = '';
switch (currentTime.getUTCDay()) {
case 0:
currentDay = g_translations.SundayAbbreviated;
break;
case 1:
currentDay = g_translations.MondayAbbreviated;
break;
case 2:
currentDay = g_translations.TuesdayAbbreviated;
break;
case 3:
currentDay = g_translations.WednesdayAbbreviated;
break;
case 4:
currentDay = g_translations.ThursdayAbbreviated;
break;
case 5:
currentDay = g_translations.FridayAbbreviated;
break;
case 6:
currentDay = g_translations.SaturdayAbbreviated;
break;
}
if (currentHours > 12 && timeUnits === 12) {
currentHours -= 12;
currentPeriod = ' PM';
}
if (currentHours === 0 && timeUnits === 12) {
currentHours = 12;
}
var formattedHours = currentHours < 10 && timeUnits === 24 ? '0' + currentHours : currentHours;
return currentDay + ' ' + formattedHours + ':' + formattedMinutes + currentPeriod;
}
function updateLanguage(key, value) {
$('[data-mra-text="' + key + '"]').text(value);
}
function getEts2JobIncome(income) {
/*
See https://github.com/mike-koch/ets2-mobile-route-advisor/wiki/Side-Notes#currency-code-multipliers
for more information.
*/
var currencyCode = g_skinConfig[g_configPrefix].currencyCode;
var currencyCodes = [];
currencyCodes['EUR'] = buildCurrencyCode(1, '', '€', '');
currencyCodes['GBP'] = buildCurrencyCode(0.8, '', '£', '');
currencyCodes['CHF'] = buildCurrencyCode(1.2, '', '', ' CHF');
currencyCodes['CZK'] = buildCurrencyCode(25, '', '', ' Kč');
currencyCodes['PLN'] = buildCurrencyCode(4.2, '', '', ' zł');
currencyCodes['HUF'] = buildCurrencyCode(293, '', '', ' Ft');
currencyCodes['DKK'] = buildCurrencyCode(7.5, '', '', ' kr');
currencyCodes['SEK'] = buildCurrencyCode(9.4, '', '', ' kr');
currencyCodes['NOK'] = buildCurrencyCode(8.6, '', '', ' kr');
var code = currencyCodes[currencyCode];
if (code === undefined) {
var errorText = "Configuration Issue: The currency code '" + currencyCode + "' is invalid. Reverted to 'EUR'.";
code = currencyCodes['EUR'];
console.error(errorText);
}
return formatIncome(income, code);
}
function buildCurrencyCode(multiplier, symbolOne, symbolTwo, symbolThree) {
return {
"multiplier": multiplier,
"symbolOne": symbolOne,
"symbolTwo": symbolTwo,
"symbolThree": symbolThree
};
}
function formatIncome(income, currencyCode) {
/* Taken directly from economy_data.sii:
- {0} First prefix (no currency codes currently use this)
- {1} Second prefix (such as euro, pound, dollar, etc)
- {2} The actual income, already converted into the proper currency
- {3} Third prefix (such as CHF, Ft, or kr)
*/
var incomeFormat = "{0}{1} {2}.- {3}";
income *= currencyCode.multiplier;
return incomeFormat.replace('{0}', currencyCode.symbolOne)
.replace('{1}', currencyCode.symbolTwo)
.replace('{2}', income)
.replace('{3}', currencyCode.symbolThree);
}
function getAtsJobIncome(income) {
/*
See https://github.com/mike-koch/ets2-mobile-route-advisor/wiki/Side-Notes#currency-code-multipliers
for more information.
*/
var currencyCode = g_skinConfig[g_configPrefix].currencyCode;
var currencyCodes = [];
currencyCodes['USD'] = buildCurrencyCode(1, '', '$', '');
currencyCodes['EUR'] = buildCurrencyCode(.75, '', '€', '');
var code = currencyCodes[currencyCode];
if (code === undefined) {
var errorText = "Configuration Issue: The currency code '" + currencyCode + "' is invalid. Reverted to 'USD'.";
code = currencyCodes['USD'];
console.error(errorText);
}
return formatIncome(income, code);
}
function getDamagePercentage(data) {
// Return the max value of all damage percentages.
return Math.max(data.truck.wearEngine,
data.truck.wearTransmission,
data.truck.wearCabin,
data.truck.wearChassis,
data.truck.wearWheels) * 100;
}
function showTab(tabName) {
$('._active_tab').removeClass('_active_tab');
$('#' + tabName).addClass('_active_tab');
$('._active_tab_button').removeClass('_active_tab_button');
$('#' + tabName + '_button').addClass('_active_tab_button');
}
/** Returns the difference between two dates in ISO 8601 format in an [hour, minutes] array */
function getTimeDifference(begin, end) {
var beginDate = new Date(begin);
var endDate = new Date(end);
var MILLISECONDS_IN_MINUTE = 60*1000;
var MILLISECONDS_IN_HOUR = MILLISECONDS_IN_MINUTE*60;
var MILLISECONDS_IN_DAY = MILLISECONDS_IN_HOUR*24;
var hours = Math.floor((endDate - beginDate) % MILLISECONDS_IN_DAY / MILLISECONDS_IN_HOUR) // number of hours
var minutes = Math.floor((endDate - beginDate) % MILLISECONDS_IN_DAY % MILLISECONDS_IN_HOUR / MILLISECONDS_IN_MINUTE) // number of minutes
return [hours, minutes];
}
function isWorldOfTrucksContract(data) {
var WORLD_OF_TRUCKS_DEADLINE_TIME = "0001-01-01T00:00:00Z";
var WORLD_OF_TRUCKS_REMAINING_TIME = "0001-01-01T00:00:00Z";
return data.job.deadlineTime === WORLD_OF_TRUCKS_DEADLINE_TIME
&& data.job.remainingTime === WORLD_OF_TRUCKS_REMAINING_TIME;
}
// Wrapper function to set an item to local storage.
function setLocalStorageItem(key, value) {
if (typeof(Storage) !== "undefined" && localStorage != null) {
localStorage.setItem(key, value);
}
}
// Wrapper function to get an item from local storage, or default if local storage is not supported.
function getLocalStorageItem(key, defaultValue) {
if (typeof(Storage) !== "undefined" && localStorage != null) {
return localStorage.getItem(key);
}
return defaultValue;
}
// Wrapper function to remove an item from local storage
function removeLocalStorageItem(key) {
if (typeof(Storage) !== "undefined" && localStorage != null) {
return localStorage.removeItem(key);
}
}
function processDomChanges(data) {
g_configPrefix = 'ets2';
if (data.game.gameName != null) {
g_configPrefix = data.game.gameName.toLowerCase();
}
// Initialize JavaScript if ETS2
var mapPack = g_skinConfig[g_configPrefix].mapPack;
// Process map pack JSON
$.getJSON(g_pathPrefix + '/maps/' + mapPack + '/config.json', function(json) {
g_mapPackConfig = json;
loadScripts(mapPack, 0, g_mapPackConfig.scripts);
});
// Process Speed Units
var distanceUnits = g_skinConfig[g_configPrefix].distanceUnits;
if (distanceUnits === 'km') {
$('.speedUnits').text('km/h');
$('.distanceUnits').text('km');
$('.truckSpeedRoundedKmhMph').addClass('truckSpeedRounded').removeClass('truckSpeedRoundedKmhMph');
$('.speedLimitRoundedKmhMph').addClass('navigation-speedLimit').removeClass('speedLimitRoundedKmhMph');
$('.navigationEstimatedDistanceKmMi').addClass('navigation-estimatedDistanceKmRounded').removeClass('navigationEstimatedDistanceKmMi');
} else if (distanceUnits === 'mi') {
$('.speedUnits').text('mph');
$('.distanceUnits').text('mi');
$('.truckSpeedRoundedKmhMph').addClass('truckSpeedMphRounded').removeClass('truckSpeedRoundedKmhMph');
$('.speedLimitRoundedKmhMph').addClass('navigation-speedLimitMphRounded').removeClass('speedLimitRoundedKmhMph');
$('.navigationEstimatedDistanceKmMi').addClass('navigation-estimatedDistanceMiRounded').removeClass('navigationEstimatedDistanceKmMi');
}
// Process kg vs tons
var weightUnits = g_skinConfig[g_configPrefix].weightUnits;
if (weightUnits === 'kg') {
$('.trailerMassKgOrT').addClass('trailerMassKg').removeClass('trailerMassKgOrT');
} else if (weightUnits === 't') {
$('.trailerMassKgOrT').addClass('trailerMassTons').removeClass('trailerMassKgOrT');
} else if (weightUnits === 'lb') {
$('.trailerMassKgOrT').addClass('trailerMassLbs').removeClass('trailerMassKgOrT');
}
// Process 12 vs 24 hr time
var timeFormat = g_skinConfig[g_configPrefix].timeFormat;
if (timeFormat === '12h') {
$('.game-time').addClass('gameTime12h').removeClass('game-time');
$('.job-deadlineTime').addClass('jobDeadlineTime12h').removeClass('job-deadlineTime');
$('.navigation-estimatedTime').addClass('navigation-estimatedTime12h').removeClass('navigation-estimatedTime');
}
g_processedDomChanges = true;
}
function loadScripts(mapPack, index, array) {
$.getScript(g_pathPrefix + '/maps/' + mapPack + '/' + array[index], function() {
var nextIndex = index + 1;
if (nextIndex != array.length) {
loadScripts(mapPack, nextIndex, array);
} else {
if (buildMap('_map')) {
$('article > p.loading-text').hide();
}
}
});
}
function goToMap() {
showTab('_map');
if (g_configPrefix === 'ets2') {
g_map.updateSize();
}
else if (g_configPrefix === 'ats') {
g_map.updateSize();
}
}
function updateSpeedIndicator(speedLimit, currentSpeed) {
/*
The game starts the red indication at 1 km/h over, and stays a solid red at 8 km/h over (...I think).
*/
var MAX_SPEED_FOR_FULL_RED = 8;
var difference = parseInt(currentSpeed) - speedLimit;
var opacity = 0;
if (difference > 0 && speedLimit != 0) {
var opacity = difference / MAX_SPEED_FOR_FULL_RED;
}
var style = 'linear-gradient(to bottom, rgba(127,0,0,{0}) 0%, rgba(255,0,0,{0}) 50%, rgba(127,0,0,{0}) 100%)';
style = style.split('{0}').join(opacity);
$('.dashboard').find('aside').find('div._speed').css('background', style);
}
function updateDisplayForSpecialTransport(trailerId) {
var specialTransportCargos = ['boiler_parts', 'cat_785c', 'condensator', 'ex_bucket', 'heat_exch', 'lattice', 'm_59_80_r63', 'mystery_box', 'mystery_cyl', 'pilot_boat', 'silo'];
if (specialTransportCargos.indexOf(trailerId) === -1) {
$('.dashboard').find('aside').removeClass('special-transport').end()
.find('nav').removeClass('special-transport');
} else {
$('.dashboard').find('aside').addClass('special-transport').end()
.find('nav').addClass('special-transport');
}
}
Date.prototype.addDays = function(d) {
this.setUTCDate(this.getUTCDate() + d - 1);
return this;
}
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Date.prototype.addMinutes = function(m) {
this.setTime(this.getTime() + (m*60*1000));
return this;
}
Date.prototype.addSeconds = function(s) {
this.setTime(this.getTime() + (s*1000));
return this;
}
// Global vars
// Gets updated to the actual path in initialize function.
var g_pathPrefix;
// Loaded with the JSON object for the choosen language.
var g_translations;
// A copy of the skinConfig object.
var g_skinConfig;
// The current version of ets2-mobile-route-advisor
var g_currentVersion = '3.6.1';
// The currently running game
var g_runningGame;
// The prefix for game-specific settings (either "ets2" or "ats")
var g_configPrefix;
// The running game the last time we checked
var g_lastRunningGame;
// The map pack configuration for the ets2 and ats map packs
var g_mapPackConfig;
// Checked if we have processed the DOM changes already.
var g_processedDomChanges;
var g_map;
|
var searchData=
[
['gesturemanager_2ecpp',['gesturemanager.cpp',['../gesturemanager_8cpp.html',1,'']]],
['gesturemanager_2eh',['gesturemanager.h',['../gesturemanager_8h.html',1,'']]]
];
|
import { client } from '../plugins/Platform.js'
import { createDirective } from '../utils/private/create.js'
import { addEvt, cleanEvt, position, leftClick, stopAndPrevent, noop } from '../utils/event.js'
import { clearSelection } from '../utils/private/selection.js'
import getSSRProps from '../utils/private/noop-ssr-directive-transform.js'
export default createDirective(__QUASAR_SSR_SERVER__
? { name: 'touch-hold', getSSRProps }
: {
name: 'touch-hold',
beforeMount (el, binding) {
const { modifiers } = binding
// early return, we don't need to do anything
if (modifiers.mouse !== true && client.has.touch !== true) {
return
}
const ctx = {
handler: binding.value,
noop,
mouseStart (evt) {
if (typeof ctx.handler === 'function' && leftClick(evt) === true) {
addEvt(ctx, 'temp', [
[ document, 'mousemove', 'move', 'passiveCapture' ],
[ document, 'click', 'end', 'notPassiveCapture' ]
])
ctx.start(evt, true)
}
},
touchStart (evt) {
if (evt.target !== void 0 && typeof ctx.handler === 'function') {
const target = evt.target
addEvt(ctx, 'temp', [
[ target, 'touchmove', 'move', 'passiveCapture' ],
[ target, 'touchcancel', 'end', 'notPassiveCapture' ],
[ target, 'touchend', 'end', 'notPassiveCapture' ]
])
ctx.start(evt)
}
},
start (evt, mouseEvent) {
ctx.origin = position(evt)
const startTime = Date.now()
if (client.is.mobile === true) {
document.body.classList.add('non-selectable')
clearSelection()
ctx.styleCleanup = withDelay => {
ctx.styleCleanup = void 0
const remove = () => {
document.body.classList.remove('non-selectable')
}
if (withDelay === true) {
clearSelection()
setTimeout(remove, 10)
}
else { remove() }
}
}
ctx.triggered = false
ctx.sensitivity = mouseEvent === true
? ctx.mouseSensitivity
: ctx.touchSensitivity
ctx.timer = setTimeout(() => {
clearSelection()
ctx.triggered = true
ctx.handler({
evt,
touch: mouseEvent !== true,
mouse: mouseEvent === true,
position: ctx.origin,
duration: Date.now() - startTime
})
}, ctx.duration)
},
move (evt) {
const { top, left } = position(evt)
if (
Math.abs(left - ctx.origin.left) >= ctx.sensitivity
|| Math.abs(top - ctx.origin.top) >= ctx.sensitivity
) {
clearTimeout(ctx.timer)
}
},
end (evt) {
cleanEvt(ctx, 'temp')
// delay needed otherwise selection still occurs
ctx.styleCleanup !== void 0 && ctx.styleCleanup(ctx.triggered)
if (ctx.triggered === true) {
evt !== void 0 && stopAndPrevent(evt)
}
else {
clearTimeout(ctx.timer)
}
}
}
// duration in ms, touch in pixels, mouse in pixels
const data = [ 600, 5, 7 ]
if (typeof binding.arg === 'string' && binding.arg.length > 0) {
binding.arg.split(':').forEach((val, index) => {
const v = parseInt(val, 10)
v && (data[ index ] = v)
})
}
[ ctx.duration, ctx.touchSensitivity, ctx.mouseSensitivity ] = data
el.__qtouchhold = ctx
modifiers.mouse === true && addEvt(ctx, 'main', [
[ el, 'mousedown', 'mouseStart', `passive${ modifiers.mouseCapture === true ? 'Capture' : '' }` ]
])
client.has.touch === true && addEvt(ctx, 'main', [
[ el, 'touchstart', 'touchStart', `passive${ modifiers.capture === true ? 'Capture' : '' }` ],
[ el, 'touchend', 'noop', 'notPassiveCapture' ]
])
},
updated (el, binding) {
const ctx = el.__qtouchhold
if (ctx !== void 0 && binding.oldValue !== binding.value) {
typeof binding.value !== 'function' && ctx.end()
ctx.handler = binding.value
}
},
beforeUnmount (el) {
const ctx = el.__qtouchhold
if (ctx !== void 0) {
cleanEvt(ctx, 'main')
cleanEvt(ctx, 'temp')
clearTimeout(ctx.timer)
ctx.styleCleanup !== void 0 && ctx.styleCleanup()
delete el.__qtouchhold
}
}
}
)
|
var searchData=
[
['meter',['METER',['../ui_tags_8h.html#a4c2663345bc4b0d87f3538ad57d756fdae2e6be25b55c130066f8efb3490b3826',1,'uiTags.h']]],
['moving',['MOVING',['../player_state_8h.html#a3c730f37b1b3a893159bada67637fdb1a16ebdcb23eb5337fd5bc598fa8d6035d',1,'playerState.h']]]
];
|
(function(){
try {
if(localStorage.mainOrder === "undefined" || localStorage.sideOrder === "undefined") {
localStorage.removeItem('mainOrder');
localStorage.removeItem('sideOrder');
}
var unmask = function () {
var s = $('.splash-input').val();
return s.slice(1,4) + s.slice(6,9) + s.slice(10);
};
timeCheck = function () {
var now = moment();
var isBetween = function (m, first, second) {
return m.isAfter(first) && m.isBefore(second);
};
var time = function (h, m) {
return moment(now).hour(h).minute(m);
};
var weekday = parseInt(now.format('d')); //sun=0, mon=1 ..
if(isBetween(now, time(11,30), time(14,0)) && weekday < 6 && weekday > 0) {
return "Summies Lunch";
}
if(isBetween(now, time(17,30), time(21,0))) {
return "Summies Dinner";
}
if(isBetween(now, time(21,30), time(23,59))) {
return "Late Night";
}
if(isBetween(now, time(00,00), time(01,00))) {
return "Late Night";
}
return "No";
};
data = [];
started = false;
//define new router class
var AppRouter = Backbone.Router.extend ({
routes: {
'' : function () {
started = true;
$('.header>div').hide();
$('#first-header').show();
$('.splash-container').hide();
$('.first-container').show();
},
'mainOrder': function () {
if(!started) {this.navigate('',{trigger:true});return;}
var router = this;
$.getJSON('/menu/' + unmask(), function (d) {
data = d;
console.log('Menu for user fetched.');
});
var searched = fuzzy.filter($('#second-header input').val(), data.map(function (i) {
return i.item;
})).map(function(el) {
return _(data).findWhere({item: el.string});
});
var router = this;
var num = $('.splash-input').val();
if(num.length !== 14) {
this.navigate("", {trigger: true});
return;
}
num = num.match(/\d/g).join("");
$('.second-container').show();
$('.header>div').hide();
$('#second-header').show();
$('.first-container').addClass('flip');
setTimeout(function () {
$('.first-container').hide();
$('.first-container').removeClass('flip');
}, 500);
var itemstemplate = $('.second-container #items-template');
var itemlist = $('.second-container .item-list');
var processed = _(searched).where({side: false});
var switcher = $('.foody-switcher span').text();
var filters = [];
if($('.vegan').hasClass('foody-checked')){
filters.push("vegan");
}
if($('.gluten-free').hasClass('foody-checked')){
filters.push("gluten-free");
}
//Filters
processed = processed.filter(function (i) {
return _.isEqual(filters, _.intersection(filters, i.filter));
});
//Sorting
processed = _(processed).sortBy(function (i) {
if(switcher === "Cheapest") {
return i.price;
}
if(switcher === "Prev Orders") {
return i.prev;
}
return 5 - i.rating_avg;
});
itemlist.html(_.template(itemstemplate.html(), {items: processed}));
$('.second-container .item-list .pure-g').click(function (e) {
$('.second-container .item-list .pure-g').removeClass('selected');
var t = $(e.currentTarget);
t.addClass('selected');
localStorage.mainOrder = t.data('id');
router.navigate('sides', {trigger: true});
});
},
'sides': function () {
if(!started) {this.navigate('',{trigger:true});return;}
var router = this;
var selectedItem = $('.second-container .item-list .pure-g.selected');
if(selectedItem.length !== 1) {
this.navigate('mainOrder', {trigger: true});
}
$('#third-header .pure-menu-heading').html('Sides for <b>' + selectedItem.find('h3').text() + '</b>');
$('.header>div').hide();
$('#third-header').show();
$('.second-container').addClass('flip');
setTimeout(function () {
$('.splash-container').hide();
$('.second-container').removeClass('flip');
$('.third-container').show();
}, 500);
var itemstemplate = $('.third-container #items-template');
var itemlist = $('.third-container .item-list');
var processed = _(data).where({side: true});
itemlist.html(_.template(itemstemplate.html(), {items: processed}));
$('.third-container .item-list .pure-g').click(function (e) {
$('.third-container .item-list .pure-g').removeClass('selected');
var t = $(e.currentTarget);
t.addClass('selected');
localStorage.sideOrder = t.data('id');
router.navigate('special', {trigger: true});
});
},
'special': function () {
if(!started) {this.navigate('',{trigger:true});return;}
var selectedItem = $('.third-container .item-list .pure-g.selected');
if(selectedItem.length !== 1) {
this.navigate('sides', {trigger: true});
}
$('.header>div').hide();
$('#fourth-header').show();
$('.third-container').addClass('flip');
setTimeout(function () {
$('.splash-container').hide();
$('.third-container').removeClass('flip');
$('.fourth-container').show();
}, 500);
var itemstemplate = $('.fourth-container #items-template');
var itemlist = $('.fourth-container .item-list');
var mainOrder = $('.second-container .item-list .pure-g.selected');
var sideOrder = $('.third-container .item-list .pure-g.selected');
if(mainOrder.length < 1 || sideOrder.length < 1) {
this.navigate('', {trigger: true});
}
itemlist.html(_.template(itemstemplate.html(), {
mainOrder: mainOrder.find('h3').text(),
sideOrder: sideOrder.find('h3').text(),
mainPrice: parseFloat(mainOrder.data('price')),
sidePrice: parseFloat(sideOrder.data('price'))
}));
var prevOption = localStorage.prevOption;
$('textarea').val(_.isUndefined(prevOption) ? '' : prevOption);
$('textarea').keyup(function (e) {
localStorage.prevOption = $('textarea').val();
});
},
sending: function () {
if(!started) {this.navigate('',{trigger:true});return;}
$('.header>div').hide();
$('#first-header').show();
$('.fourth-container').addClass('flip');
setTimeout(function () {
$('.splash-container').hide();
$('.fourth-container').removeClass('flip');
$('.fifth-container').show();
}, 500);
console.log("sending");
var cb = function () {
$('.sending').hide();
$('.sent').show();
$('.fifth-container p').show();
};
// setTimeout(cb, 2000);
var orderedMain = _(data).findWhere({_id: localStorage.mainOrder});
var orderedSide = _(data).findWhere({_id: localStorage.sideOrder});
if(orderedSide.menu !== orderedMain.menu) {
console.log('You selected items from different menus.');
return;
}
var toSend = {
destination: orderedMain.menu,
item_id: localStorage.mainOrder,
side_id: localStorage.sideOrder,
special: localStorage.prevOption,
number: unmask()
};
console.log(toSend);
$.ajax({
type: "POST",
url: "/order",
data: toSend,
}).done(function( msg ) {
console.log(msg);
cb();
});
},
'repeatLastOrder': function () {
if(!started) {this.navigate('',{trigger:true});return;}
if(_.isNull(localStorage.getItem('mainOrder')) || _.isNull(localStorage.getItem('sideOrder'))) {
this.navigate('mainOrder', {trigger: true});
return;
}
$('.header>div').hide();
$('#fourth-header').show();
$('.first-container').addClass('flip');
setTimeout(function () {
$('.splash-container').hide();
$('.first-container').removeClass('flip');
$('.fourth-container').show();
}, 500);
var itemstemplate = $('.fourth-container #items-template');
var itemlist = $('.fourth-container .item-list');
var mainOrder = _(data).findWhere({_id: localStorage.mainOrder});
var sideOrder = _(data).findWhere({_id: localStorage.sideOrder});
itemlist.html(_.template(itemstemplate.html(), {
mainOrder: mainOrder.item,
sideOrder: sideOrder.item,
mainPrice: mainOrder.price,
sidePrice: sideOrder.price
}));
var prevOption = localStorage.prevOption;
$('textarea').val(_.isUndefined(prevOption) ? '' : prevOption);
$('textarea').keyup(function (e) {
localStorage.prevOption = $('textarea').val();
});
},
'rate': function () {
if(!started) {this.navigate('',{trigger:true});return;}
var itemstemplate = $('.rate-container #items-template');
var itemlist = $('.rate-container .item-list');
var searched = _(fuzzy.filter($('#rate-header input').val(), data.map(function (i) {
return i.item;
})).map(function(el) {
return _(data).findWhere({item: el.string});
})).sortBy(function (i) {
return 5 - i.rating_avg;
});
$('.header>div').hide();
$('#rate-header').show();
$('.first-container').addClass('flip');
setTimeout(function () {
$('.splash-container').hide();
$('.first-container').removeClass('flip');
$('.rate-container').show();
}, 500);
var router = this;
itemlist.html(_.template(itemstemplate.html(), {items: searched}));
$('.rate-container select.point').change(function (e) {
var id = $(e.currentTarget).data('id');
var pt = $(e.currentTarget).val();
$.ajax({
type: "POST",
url: "/ratings",
data: {item: id, rate: pt}
}).done(function( msg ) {
data = data.map(function (i) {
if(i._id === id) {
i.rating_avg = parseFloat(msg);
}
return i;
});
router.navigate("");
router.navigate("rate", {trigger: true});
});
})
}
}
});
$(document).ready(function () {
$('#first-header a').prepend('<b>' + timeCheck() + '</b> ')
var prevTel = localStorage.prevTel;
$('.splash-input').val(_.isUndefined(prevTel) ? '' : prevTel);
$('.splash-input').keyup(function (e) {
localStorage.prevTel = $('.splash-input').val();
});
var tel = unmask();
var url;
if(tel === "") {
url = "/menu/0";
} else {
url = "/menu/" + unmask();
}
$.getJSON(url, function (d) {
data = d;
});
$('#second-header input').keyup(function () {
appRouter.navigate("");
appRouter.navigate("mainOrder", {trigger: true});
});
$('#rate-header input').keyup(function () {
appRouter.navigate("");
appRouter.navigate("rate", {trigger: true});
});
$('.foody-checkbox').click(function (e) {
var t = $(e.currentTarget);
t.toggleClass("foody-checked");
t.find('.fa').toggleClass('fa-check-square-o');
t.find('.fa').toggleClass('fa-square-o');
appRouter.navigate("");
appRouter.navigate("mainOrder", {trigger: true});
});
$('.foody-switcher').click(function (e) {
var t = $(e.currentTarget);
var content = ["Best Rated", "Cheapest", "Prev Orders"];
var current = t.find('span').text();
current = content.indexOf(current);
if(current === 2) {
current = -1;
}
var next = content[current + 1];
t.find('span').text(next);
appRouter.navigate("");
appRouter.navigate("mainOrder", {trigger: true});
});
var appRouter = new AppRouter();
Backbone.history.start();
appRouter.navigate('#');
});
} catch(e) {
console.log(e);
Backbone.history.navigate('#');
}
})();
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 12.2.1-28-s
description: >
arguments as local var identifier assigned to throws SyntaxError
in strict mode
flags: [onlyStrict]
includes: [runTestCase.js]
---*/
function testcase() {
'use strict';
try {
eval('function foo() { var a, arguments = 42;}');
return false;
}
catch (e) {
return (e instanceof SyntaxError);
}
}
runTestCase(testcase);
|
import React from "react";
import PropTypes from "prop-types";
import FilterInput from "./FilterInput";
import ToolbarLayout from "./ToolbarLayout";
const BlueprintToolbar = (props) => (
<ToolbarLayout
filters={props.filters}
filterRemoveValue={props.filterRemoveValue}
filterClearValues={props.filterClearValues}
>
<FilterInput emptyState={props.emptyState} filters={props.filters} filterAddValue={props.filterAddValue} />
<div className="form-group">
{(props.componentsSortKey === "name" && props.componentsSortValue === "DESC" && (
<button
className="btn btn-link"
type="button"
disabled={props.emptyState}
onClick={() => {
props.componentsSortSetValue("ASC");
props.dependenciesSortSetValue("ASC");
}}
>
<span className="fa fa-sort-alpha-asc" />
</button>
)) ||
(props.componentsSortKey === "name" && props.componentsSortValue === "ASC" && (
<button
className="btn btn-link"
type="button"
disabled={props.emptyState}
onClick={() => {
props.componentsSortSetValue("DESC");
props.dependenciesSortSetValue("DESC");
}}
>
<span className="fa fa-sort-alpha-desc" />
</button>
))}
</div>
{props.showUndoRedo && props.undo !== undefined && (
<div className="form-group">
{(props.pastLength > 0 && (
<button
className="btn btn-link"
type="button"
onClick={() => {
props.undo();
}}
data-button="undo"
>
<span className="fa fa-undo" aria-hidden="true" />
</button>
)) || (
<button className="btn btn-link disabled" type="button" data-button="undo">
<span className="fa fa-undo" aria-hidden="true" />
</button>
)}
{(props.futureLength > 0 && (
<button
className="btn btn-link"
type="button"
onClick={() => {
props.redo(props.blueprintId, false);
}}
data-button="redo"
>
<span className="fa fa-repeat" aria-hidden="true" />
</button>
)) || (
<button className="btn btn-link disabled" type="button" data-button="redo">
<span className="fa fa-repeat" aria-hidden="true" />
</button>
)}
</div>
)}
</ToolbarLayout>
);
BlueprintToolbar.propTypes = {
filters: PropTypes.shape({
defaultFilterType: PropTypes.string,
filterTypes: PropTypes.arrayOf(PropTypes.object),
filterValues: PropTypes.arrayOf(PropTypes.object),
}),
filterAddValue: PropTypes.func,
filterRemoveValue: PropTypes.func,
filterClearValues: PropTypes.func,
emptyState: PropTypes.bool,
componentsSortKey: PropTypes.string,
componentsSortSetValue: PropTypes.func,
componentsSortValue: PropTypes.string,
dependenciesSortSetValue: PropTypes.func,
undo: PropTypes.func,
pastLength: PropTypes.number,
futureLength: PropTypes.number,
redo: PropTypes.func,
blueprintId: PropTypes.string,
showUndoRedo: PropTypes.bool,
};
BlueprintToolbar.defaultProps = {
filters: {},
filterAddValue() {},
filterRemoveValue() {},
filterClearValues() {},
emptyState: false,
componentsSortKey: "",
componentsSortSetValue() {},
componentsSortValue: "",
dependenciesSortSetValue() {},
undo() {},
pastLength: 0,
futureLength: 0,
redo() {},
blueprintId: "",
showUndoRedo: false,
};
export default BlueprintToolbar;
|
version https://git-lfs.github.com/spec/v1
oid sha256:7745d8428b03a50c36201da71a1a4b014c4cc2d51ca3e04d0f348277bca2e6fb
size 18615
|
var fn = require('./a.tpl.js');
console.log(fn({
a: '<h2>fdafad</h2>',
b: 2,
c: 2322
}));
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var IoIosPaperOutline = function IoIosPaperOutline(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm8.8 5h26.2v27.6c0 1.3-1.1 2.4-2.4 2.4h-25.2c-1.3 0-2.4-1.1-2.4-2.4v-23.8h2.5v1.2h-1.2v22.6c0 0.6 0.5 1.2 1.1 1.2h25.2c0.6 0 1.1-0.6 1.1-1.2v-26.3h-23.7v25h-1.2v-26.3z m3.7 5v-1.2h10v1.2h-10z m0 6.3v-1.3h18.8v1.3h-18.8z m0 6.2v-1.2h15v1.2h-15z m0 6.3v-1.3h18.8v1.3h-18.8z' })
)
);
};
exports.default = IoIosPaperOutline;
module.exports = exports['default']; |
import { Form } from '../../../../src';
const struct = [
'tags[]',
'tags[].id',
'tags[].name',
];
const fields = [{
name: 'tags',
label: 'Tags!!!',
}, {
name: 'other',
label: 'Other!!!',
fields: [{
name: 'nested',
value: 'nested-value',
}],
}];
class NewForm extends Form {
hooks() {
return {
onInit() {
this.$('tags').add([{
id: 'x',
name: 'y',
}]);
// EQUIVALENT
// this.$('tags').add();
// this.$('tags[0]').set({
// id: 'x',
// name: 'y',
// });
// EQUIVALENT
// this.update({
// tags: [{
// id: 'x',
// name: 'y',
// }],
// });
},
};
}
}
export default new NewForm({ struct, fields }, { name: 'Fixes-Q1' });
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*
Graph of nodes with outlets
*/
var Graph;
Graph = (function() {
Graph.index = 0;
Graph.id = function(name) {
return ++Graph.index;
};
Graph.IN = 0;
Graph.OUT = 1;
function Graph(nodes, parent) {
this.parent = parent != null ? parent : null;
this.id = Graph.id();
this.nodes = [];
nodes && this.add(nodes);
}
Graph.prototype.inputs = function() {
var inputs, node, outlet, _i, _j, _len, _len1, _ref, _ref1;
inputs = [];
_ref = this.nodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
_ref1 = node.inputs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
if (outlet.input === null) {
inputs.push(outlet);
}
}
}
return inputs;
};
Graph.prototype.outputs = function() {
var node, outlet, outputs, _i, _j, _len, _len1, _ref, _ref1;
outputs = [];
_ref = this.nodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
_ref1 = node.outputs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
if (outlet.output.length === 0) {
outputs.push(outlet);
}
}
}
return outputs;
};
Graph.prototype.getIn = function(name) {
var outlet;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.inputs();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
if (outlet.name === name) {
_results.push(outlet);
}
}
return _results;
}).call(this))[0];
};
Graph.prototype.getOut = function(name) {
var outlet;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.outputs();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
if (outlet.name === name) {
_results.push(outlet);
}
}
return _results;
}).call(this))[0];
};
Graph.prototype.add = function(node, ignore) {
var _i, _len, _node;
if (node.length) {
for (_i = 0, _len = node.length; _i < _len; _i++) {
_node = node[_i];
this.add(_node);
}
return;
}
if (node.graph && !ignore) {
throw new Error("Adding node to two graphs at once");
}
node.graph = this;
return this.nodes.push(node);
};
Graph.prototype.remove = function(node, ignore) {
var _i, _len, _node;
if (node.length) {
for (_i = 0, _len = node.length; _i < _len; _i++) {
_node = node[_i];
this.remove(_node);
}
return;
}
if (node.graph !== this) {
throw new Error("Removing node from wrong graph.");
}
ignore || node.disconnect();
this.nodes.splice(this.nodes.indexOf(node), 1);
return node.graph = null;
};
Graph.prototype.adopt = function(node) {
var _i, _len, _node;
if (node.length) {
for (_i = 0, _len = node.length; _i < _len; _i++) {
_node = node[_i];
this.adopt(_node);
}
return;
}
node.graph.remove(node, true);
return this.add(node, true);
};
return Graph;
})();
module.exports = Graph;
},{}],2:[function(require,module,exports){
exports.Graph = require('./graph');
exports.Node = require('./node');
exports.Outlet = require('./outlet');
exports.IN = exports.Graph.IN;
exports.OUT = exports.Graph.OUT;
},{"./graph":1,"./node":3,"./outlet":4}],3:[function(require,module,exports){
var Graph, Node, Outlet;
Graph = require('./graph');
Outlet = require('./outlet');
/*
Node in graph.
*/
Node = (function() {
Node.index = 0;
Node.id = function(name) {
return ++Node.index;
};
function Node(owner, outlets) {
this.owner = owner;
this.graph = null;
this.inputs = [];
this.outputs = [];
this.all = [];
this.outlets = null;
this.id = Node.id();
this.setOutlets(outlets);
}
Node.prototype.getIn = function(name) {
var outlet;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.inputs;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
if (outlet.name === name) {
_results.push(outlet);
}
}
return _results;
}).call(this))[0];
};
Node.prototype.getOut = function(name) {
var outlet;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.outputs;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
if (outlet.name === name) {
_results.push(outlet);
}
}
return _results;
}).call(this))[0];
};
Node.prototype.get = function(name) {
return this.getIn(name) || this.getOut(name);
};
Node.prototype.setOutlets = function(outlets) {
var existing, hash, key, match, outlet, _i, _j, _k, _len, _len1, _len2, _ref;
if (outlets != null) {
if (this.outlets == null) {
this.outlets = {};
for (_i = 0, _len = outlets.length; _i < _len; _i++) {
outlet = outlets[_i];
if (!(outlet instanceof Outlet)) {
outlet = Outlet.make(outlet);
}
this._add(outlet);
}
return;
}
hash = function(outlet) {
return [outlet.name, outlet.inout, outlet.type].join('-');
};
match = {};
for (_j = 0, _len1 = outlets.length; _j < _len1; _j++) {
outlet = outlets[_j];
match[hash(outlet)] = true;
}
_ref = this.outlets;
for (key in _ref) {
outlet = _ref[key];
key = hash(outlet);
if (match[key]) {
match[key] = outlet;
} else {
this._remove(outlet);
}
}
for (_k = 0, _len2 = outlets.length; _k < _len2; _k++) {
outlet = outlets[_k];
existing = match[hash(outlet)];
if (existing instanceof Outlet) {
this._morph(existing, outlet);
} else {
if (!(outlet instanceof Outlet)) {
outlet = Outlet.make(outlet);
}
this._add(outlet);
}
}
this;
}
return this.outlets;
};
Node.prototype.connect = function(node, empty, force) {
var dest, dests, hint, hints, list, outlets, source, sources, type, typeHint, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2;
outlets = {};
hints = {};
typeHint = function(outlet) {
return type + '/' + outlet.hint;
};
_ref = node.inputs;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
dest = _ref[_i];
if (!force && dest.input) {
continue;
}
type = dest.type;
hint = typeHint(dest);
if (!hints[hint]) {
hints[hint] = dest;
}
outlets[type] = list = outlets[type] || [];
list.push(dest);
}
sources = this.outputs;
sources = sources.filter(function(outlet) {
return !(empty && outlet.output.length);
});
_ref1 = sources.slice();
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
source = _ref1[_j];
type = source.type;
hint = typeHint(source);
dests = outlets[type];
if (dest = hints[hint]) {
source.connect(dest);
delete hints[hint];
dests.splice(dests.indexOf(dest), 1);
sources.splice(sources.indexOf(source), 1);
}
}
if (!sources.length) {
return this;
}
_ref2 = sources.slice();
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
source = _ref2[_k];
type = source.type;
dests = outlets[type];
if (dests && dests.length) {
source.connect(dests.shift());
}
}
return this;
};
Node.prototype.disconnect = function(node) {
var outlet, _i, _j, _len, _len1, _ref, _ref1;
_ref = this.inputs;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
outlet.disconnect();
}
_ref1 = this.outputs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
outlet.disconnect();
}
return this;
};
Node.prototype._key = function(outlet) {
return [outlet.name, outlet.inout].join('-');
};
Node.prototype._add = function(outlet) {
var key;
key = this._key(outlet);
if (outlet.node) {
throw new Error("Adding outlet to two nodes at once.");
}
if (this.outlets[key]) {
throw new Error("Adding two identical outlets to same node. (" + key + ")");
}
outlet.node = this;
if (outlet.inout === Graph.IN) {
this.inputs.push(outlet);
}
if (outlet.inout === Graph.OUT) {
this.outputs.push(outlet);
}
this.all.push(outlet);
return this.outlets[key] = outlet;
};
Node.prototype._morph = function(existing, outlet) {
var key;
key = this._key(outlet);
delete this.outlets[key];
existing.morph(outlet);
key = this._key(outlet);
return this.outlets[key] = outlet;
};
Node.prototype._remove = function(outlet) {
var inout, key;
key = this._key(outlet);
inout = outlet.inout;
if (outlet.node !== this) {
throw new Error("Removing outlet from wrong node.");
}
outlet.disconnect();
outlet.node = null;
delete this.outlets[key];
if (outlet.inout === Graph.IN) {
this.inputs.splice(this.inputs.indexOf(outlet), 1);
}
if (outlet.inout === Graph.OUT) {
this.outputs.splice(this.outputs.indexOf(outlet), 1);
}
this.all.splice(this.all.indexOf(outlet), 1);
return this;
};
return Node;
})();
module.exports = Node;
},{"./graph":1,"./outlet":4}],4:[function(require,module,exports){
var Graph, Outlet;
Graph = require('./graph');
/*
In/out outlet on node
*/
Outlet = (function() {
Outlet.make = function(outlet, extra) {
var key, meta, value, _ref;
if (extra == null) {
extra = {};
}
meta = extra;
if (outlet.meta != null) {
_ref = outlet.meta;
for (key in _ref) {
value = _ref[key];
meta[key] = value;
}
}
return new Outlet(outlet.inout, outlet.name, outlet.hint, outlet.type, meta);
};
Outlet.index = 0;
Outlet.id = function(name) {
return "_io_" + (++Outlet.index) + "_" + name;
};
Outlet.hint = function(name) {
name = name.replace(/^_io_[0-9]+_/, '');
name = name.replace(/_i_o$/, '');
return name = name.replace(/(In|Out|Inout|InOut)$/, '');
};
function Outlet(inout, name, hint, type, meta, id) {
this.inout = inout;
this.name = name;
this.hint = hint;
this.type = type;
this.meta = meta != null ? meta : {};
this.id = id;
if (this.hint == null) {
this.hint = Outlet.hint(name);
}
this.node = null;
this.input = null;
this.output = [];
if (this.id == null) {
this.id = Outlet.id(this.hint);
}
}
Outlet.prototype.morph = function(outlet) {
this.inout = outlet.inout;
this.name = outlet.name;
this.hint = outlet.hint;
this.type = outlet.type;
return this.meta = outlet.meta;
};
Outlet.prototype.dupe = function(name) {
var outlet;
if (name == null) {
name = this.id;
}
outlet = Outlet.make(this);
outlet.name = name;
return outlet;
};
Outlet.prototype.connect = function(outlet) {
if (this.inout === Graph.IN && outlet.inout === Graph.OUT) {
return outlet.connect(this);
}
if (this.inout !== Graph.OUT || outlet.inout !== Graph.IN) {
throw new Error("Can only connect out to in.");
}
if (outlet.input === this) {
return;
}
outlet.disconnect();
outlet.input = this;
return this.output.push(outlet);
};
Outlet.prototype.disconnect = function(outlet) {
var index, _i, _len, _ref;
if (this.input) {
this.input.disconnect(this);
}
if (this.output.length) {
if (outlet) {
index = this.output.indexOf(outlet);
if (index >= 0) {
this.output.splice(index, 1);
return outlet.input = null;
}
} else {
_ref = this.output;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
outlet.input = null;
}
return this.output = [];
}
}
};
return Outlet;
})();
module.exports = Outlet;
},{"./graph":1}],5:[function(require,module,exports){
var Block, Graph, Layout, OutletError, Program, debug;
Graph = require('../graph');
Program = require('../linker').Program;
Layout = require('../linker').Layout;
debug = false;
Block = (function() {
Block.previous = function(outlet) {
var _ref;
return (_ref = outlet.input) != null ? _ref.node.owner : void 0;
};
function Block() {
var _ref;
if (this.namespace == null) {
this.namespace = Program.entry();
}
this.node = new Graph.Node(this, (_ref = typeof this.makeOutlets === "function" ? this.makeOutlets() : void 0) != null ? _ref : {});
}
Block.prototype.refresh = function() {
var _ref;
return this.node.setOutlets((_ref = typeof this.makeOutlets === "function" ? this.makeOutlets() : void 0) != null ? _ref : {});
};
Block.prototype.clone = function() {
return new Block;
};
Block.prototype.compile = function(language, namespace) {
var program;
program = new Program(language, namespace != null ? namespace : Program.entry(), this.node.graph);
this.call(program, 0);
return program.assemble();
};
Block.prototype.link = function(language, namespace) {
var layout, module;
module = this.compile(language, namespace);
layout = new Layout(language, this.node.graph);
this._include(module, layout, 0);
this["export"](layout, 0);
return layout.link(module);
};
Block.prototype.call = function(program, depth) {};
Block.prototype.callback = function(layout, depth, name, external, outlet) {};
Block.prototype["export"] = function(layout, depth) {};
Block.prototype._info = function(suffix) {
var string, _ref, _ref1;
string = (_ref = (_ref1 = this.node.owner.snippet) != null ? _ref1._name : void 0) != null ? _ref : this.node.owner.namespace;
if (suffix != null) {
return string += '.' + suffix;
}
};
Block.prototype._outlet = function(def, props) {
var outlet;
outlet = Graph.Outlet.make(def, props);
outlet.meta.def = def;
return outlet;
};
Block.prototype._call = function(module, program, depth) {
return program.call(this.node, module, depth);
};
Block.prototype._require = function(module, program) {
return program.require(this.node, module);
};
Block.prototype._inputs = function(module, program, depth) {
var arg, outlet, _i, _len, _ref, _ref1, _results;
_ref = module.main.signature;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
outlet = this.node.get(arg.name);
_results.push((_ref1 = Block.previous(outlet)) != null ? _ref1.call(program, depth + 1) : void 0);
}
return _results;
};
Block.prototype._callback = function(module, layout, depth, name, external, outlet) {
return layout.callback(this.node, module, depth, name, external, outlet);
};
Block.prototype._include = function(module, layout, depth) {
return layout.include(this.node, module, depth);
};
Block.prototype._link = function(module, layout, depth) {
var block, ext, key, orig, outlet, parent, _i, _len, _ref, _ref1, _ref2, _results;
debug && console.log('block::_link', this.toString(), module.namespace);
_ref = module.symbols;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
ext = module.externals[key];
outlet = this.node.get(ext.name);
if (!outlet) {
throw new OutletError("External not found on " + (this._info(ext.name)));
}
if (outlet.meta.child != null) {
continue;
}
_ref1 = [outlet, outlet, null], orig = _ref1[0], parent = _ref1[1], block = _ref1[2];
while (!block && parent) {
_ref2 = [outlet.meta.parent, parent], parent = _ref2[0], outlet = _ref2[1];
}
block = Block.previous(outlet);
if (!block) {
throw new OutletError("Missing connection on " + (this._info(ext.name)));
}
debug && console.log('callback -> ', this.toString(), ext.name, outlet);
block.callback(layout, depth + 1, key, ext, outlet.input);
_results.push(block != null ? block["export"](layout, depth + 1) : void 0);
}
return _results;
};
Block.prototype._trace = function(module, layout, depth) {
var arg, outlet, _i, _len, _ref, _ref1, _results;
debug && console.log('block::_trace', this.toString(), module.namespace);
_ref = module.main.signature;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
outlet = this.node.get(arg.name);
_results.push((_ref1 = Block.previous(outlet)) != null ? _ref1["export"](layout, depth + 1) : void 0);
}
return _results;
};
return Block;
})();
OutletError = function(message) {
var e;
e = new Error(message);
e.name = 'OutletError';
return e;
};
OutletError.prototype = new Error;
module.exports = Block;
},{"../graph":25,"../linker":30}],6:[function(require,module,exports){
var Block, Call,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Block = require('./block');
Call = (function(_super) {
__extends(Call, _super);
function Call(snippet) {
this.snippet = snippet;
this.namespace = this.snippet.namespace;
Call.__super__.constructor.apply(this, arguments);
}
Call.prototype.clone = function() {
return new Call(this.snippet);
};
Call.prototype.makeOutlets = function() {
var callbacks, externals, key, main, outlet, params, symbols;
main = this.snippet.main.signature;
externals = this.snippet.externals;
symbols = this.snippet.symbols;
params = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = main.length; _i < _len; _i++) {
outlet = main[_i];
_results.push(this._outlet(outlet, {
callback: false
}));
}
return _results;
}).call(this);
callbacks = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = symbols.length; _i < _len; _i++) {
key = symbols[_i];
_results.push(this._outlet(externals[key], {
callback: true
}));
}
return _results;
}).call(this);
return params.concat(callbacks);
};
Call.prototype.call = function(program, depth) {
this._call(this.snippet, program, depth);
return this._inputs(this.snippet, program, depth);
};
Call.prototype["export"] = function(layout, depth) {
if (!layout.visit(this.namespace, depth)) {
return;
}
this._link(this.snippet, layout, depth);
return this._trace(this.snippet, layout, depth);
};
return Call;
})(Block);
module.exports = Call;
},{"./block":5}],7:[function(require,module,exports){
var Block, Callback, Graph,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Graph = require('../graph');
Block = require('./block');
/*
Re-use a subgraph as a callback
*/
Callback = (function(_super) {
__extends(Callback, _super);
function Callback(graph) {
this.graph = graph;
Callback.__super__.constructor.apply(this, arguments);
}
Callback.prototype.refresh = function() {
Callback.__super__.refresh.apply(this, arguments);
return delete this.subroutine;
};
Callback.prototype.clone = function() {
return new Callback(this.graph);
};
Callback.prototype.makeOutlets = function() {
var handle, ins, outlet, outlets, outs, type, _i, _j, _len, _len1, _ref, _ref1;
this.make();
outlets = [];
ins = [];
outs = [];
handle = (function(_this) {
return function(outlet, list) {
var dupe, _base;
if (outlet.meta.callback) {
if (outlet.inout === Graph.IN) {
dupe = outlet.dupe();
if ((_base = dupe.meta).child == null) {
_base.child = outlet;
}
outlet.meta.parent = dupe;
return outlets.push(dupe);
}
} else {
return list.push(outlet.type);
}
};
})(this);
_ref = this.graph.inputs();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
handle(outlet, ins);
}
_ref1 = this.graph.outputs();
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
handle(outlet, outs);
}
ins = ins.join(',');
outs = outs.join(',');
type = "(" + ins + ")(" + outs + ")";
outlets.push({
name: 'callback',
type: type,
inout: Graph.OUT,
meta: {
callback: true,
def: this.subroutine.main
}
});
return outlets;
};
Callback.prototype.make = function() {
return this.subroutine = this.graph.compile(this.namespace);
};
Callback.prototype["export"] = function(layout, depth) {
if (!layout.visit(this.namespace, depth)) {
return;
}
this._link(this.subroutine, layout, depth);
return this.graph["export"](layout, depth);
};
Callback.prototype.call = function(program, depth) {
return this._require(this.subroutine, program, depth);
};
Callback.prototype.callback = function(layout, depth, name, external, outlet) {
this._include(this.subroutine, layout, depth);
return this._callback(this.subroutine, layout, depth, name, external, outlet);
};
return Callback;
})(Block);
module.exports = Callback;
},{"../graph":25,"./block":5}],8:[function(require,module,exports){
exports.Block = require('./block');
exports.Call = require('./call');
exports.Callback = require('./callback');
exports.Isolate = require('./isolate');
exports.Join = require('./join');
},{"./block":5,"./call":6,"./callback":7,"./isolate":9,"./join":10}],9:[function(require,module,exports){
var Block, Graph, Isolate,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Graph = require('../graph');
Block = require('./block');
/*
Isolate a subgraph as a single node
*/
Isolate = (function(_super) {
__extends(Isolate, _super);
function Isolate(graph) {
this.graph = graph;
Isolate.__super__.constructor.apply(this, arguments);
}
Isolate.prototype.refresh = function() {
Isolate.__super__.refresh.apply(this, arguments);
return delete this.subroutine;
};
Isolate.prototype.clone = function() {
return new Isolate(this.graph);
};
Isolate.prototype.makeOutlets = function() {
var done, dupe, name, outlet, outlets, seen, set, _base, _i, _j, _len, _len1, _ref, _ref1, _ref2;
this.make();
outlets = [];
seen = {};
done = {};
_ref = ['inputs', 'outputs'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
set = _ref[_i];
_ref1 = this.graph[set]();
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
name = void 0;
if (((_ref2 = outlet.hint) === 'return' || _ref2 === 'callback') && outlet.inout === Graph.OUT) {
name = outlet.hint;
}
if (seen[name] != null) {
name = void 0;
}
dupe = outlet.dupe(name);
if ((_base = dupe.meta).child == null) {
_base.child = outlet;
}
outlet.meta.parent = dupe;
if (name != null) {
seen[name] = true;
}
done[outlet.name] = dupe;
outlets.push(dupe);
}
}
return outlets;
};
Isolate.prototype.make = function() {
return this.subroutine = this.graph.compile(this.namespace);
};
Isolate.prototype.call = function(program, depth) {
this._call(this.subroutine, program, depth);
return this._inputs(this.subroutine, program, depth);
};
Isolate.prototype["export"] = function(layout, depth) {
if (!layout.visit(this.namespace, depth)) {
return;
}
this._link(this.subroutine, layout, depth);
this._trace(this.subroutine, layout, depth);
return this.graph["export"](layout, depth);
};
Isolate.prototype.callback = function(layout, depth, name, external, outlet) {
outlet = outlet.meta.child;
return outlet.node.owner.callback(layout, depth, name, external, outlet);
};
return Isolate;
})(Block);
module.exports = Isolate;
},{"../graph":25,"./block":5}],10:[function(require,module,exports){
var Block, Join,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Block = require('./block');
/*
Join multiple disconnected nodes
*/
Join = (function(_super) {
__extends(Join, _super);
function Join(nodes) {
this.nodes = nodes;
Join.__super__.constructor.apply(this, arguments);
}
Join.prototype.clone = function() {
return new Join(this.nodes);
};
Join.prototype.makeOutlets = function() {
return [];
};
Join.prototype.call = function(program, depth) {
var block, node, _i, _len, _ref, _results;
_ref = this.nodes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
block = node.owner;
_results.push(block.call(program, depth));
}
return _results;
};
Join.prototype["export"] = function(layout, depth) {
var block, node, _i, _len, _ref, _results;
_ref = this.nodes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
block = node.owner;
_results.push(block["export"](layout, depth));
}
return _results;
};
return Join;
})(Block);
module.exports = Join;
},{"./block":5}],11:[function(require,module,exports){
/*
Cache decorator
Fetches snippets once, clones for reuse
Inline code is hashed to avoid bloat
*/
var cache, hash, queue;
queue = require('./queue');
hash = require('./hash');
cache = function(fetch) {
var cached, push;
cached = {};
push = queue(100);
return function(name) {
var expire, key;
key = name.length > 32 ? '##' + hash(name).toString(16) : name;
expire = push(key);
if (expire != null) {
delete cached[expire];
}
if (cached[key] == null) {
cached[key] = fetch(name);
}
return cached[key].clone();
};
};
module.exports = cache;
},{"./hash":13,"./queue":17}],12:[function(require,module,exports){
var Block, Factory, Graph, State, Visualize;
Graph = require('../graph').Graph;
Block = require('../block');
Visualize = require('../visualize');
/*
Chainable factory
Exposes methods to build a graph incrementally
*/
Factory = (function() {
function Factory(language, fetch, config) {
this.language = language;
this.fetch = fetch;
this.config = config;
this.graph();
}
Factory.prototype.pipe = function(name, uniforms, namespace, defines) {
if (name instanceof Factory) {
this._concat(name);
} else if (name != null) {
this._call(name, uniforms, namespace, defines);
}
return this;
};
Factory.prototype.call = function(name, uniforms, namespace, defines) {
return this.pipe(name, uniforms, namespace, defines);
};
Factory.prototype.require = function(name, uniforms, namespace, defines) {
if (name instanceof Factory) {
this._import(name);
} else if (name != null) {
this.callback();
this._call(name, uniforms, namespace, defines);
this.end();
}
return this;
};
Factory.prototype["import"] = function(name, uniforms, namespace, defines) {
return this.require(name, uniforms, namespace, defines);
};
Factory.prototype.split = function() {
this._group('_combine', true);
return this;
};
Factory.prototype.fan = function() {
this._group('_combine', false);
return this;
};
Factory.prototype.isolate = function() {
this._group('_isolate');
return this;
};
Factory.prototype.callback = function() {
this._group('_callback');
return this;
};
Factory.prototype.next = function() {
this._next();
return this;
};
Factory.prototype.pass = function() {
var pass;
pass = this._stack[2].end;
this.end();
this._state.end = this._state.end.concat(pass);
return this;
};
Factory.prototype.end = function() {
var main, op, sub, _ref;
_ref = this._exit(), sub = _ref[0], main = _ref[1];
op = sub.op;
if (this[op]) {
this[op](sub, main);
}
return this;
};
Factory.prototype.join = function() {
return this.end();
};
Factory.prototype.graph = function() {
var graph, _ref;
while (((_ref = this._stack) != null ? _ref.length : void 0) > 1) {
this.end();
}
if (this._graph) {
this._tail(this._state, this._graph);
}
graph = this._graph;
this._graph = new Graph;
this._state = new State;
this._stack = [this._state];
return graph;
};
Factory.prototype.compile = function(namespace) {
if (namespace == null) {
namespace = 'main';
}
return this.graph().compile(namespace);
};
Factory.prototype.link = function(namespace) {
if (namespace == null) {
namespace = 'main';
}
return this.graph().link(namespace);
};
Factory.prototype.serialize = function() {
return Visualize.serialize(this._graph);
};
Factory.prototype.empty = function() {
return this._graph.nodes.length === 0;
};
Factory.prototype._concat = function(factory) {
var block, error;
if (factory._state.nodes.length === 0) {
return this;
}
this._tail(factory._state, factory._graph);
try {
block = new Block.Isolate(factory._graph);
} catch (_error) {
error = _error;
if (this.config.autoInspect) {
Visualize.inspect(error, this._graph, factory);
}
throw error;
}
this._auto(block);
return this;
};
Factory.prototype._import = function(factory) {
var block, error;
if (factory._state.nodes.length === 0) {
throw "Can't import empty callback";
}
this._tail(factory._state, factory._graph);
try {
block = new Block.Callback(factory._graph);
} catch (_error) {
error = _error;
if (this.config.autoInspect) {
Visualize.inspect(error, this._graph, factory);
}
throw error;
}
this._auto(block);
return this;
};
Factory.prototype._combine = function(sub, main) {
var from, to, _i, _j, _len, _len1, _ref, _ref1;
_ref = sub.start;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
to = _ref[_i];
_ref1 = main.end;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
from = _ref1[_j];
from.connect(to, sub.multi);
}
}
main.end = sub.end;
return main.nodes = main.nodes.concat(sub.nodes);
};
Factory.prototype._isolate = function(sub, main) {
var block, error, subgraph;
if (sub.nodes.length) {
subgraph = this._subgraph(sub);
this._tail(sub, subgraph);
try {
block = new Block.Isolate(subgraph);
} catch (_error) {
error = _error;
if (this.config.autoInspect) {
Visualize.inspect(error, this._graph, subgraph);
}
throw error;
}
return this._auto(block);
}
};
Factory.prototype._callback = function(sub, main) {
var block, error, subgraph;
if (sub.nodes.length) {
subgraph = this._subgraph(sub);
this._tail(sub, subgraph);
try {
block = new Block.Callback(subgraph);
} catch (_error) {
error = _error;
if (this.config.autoInspect) {
Visualize.inspect(error, this._graph, subgraph);
}
throw error;
}
return this._auto(block);
}
};
Factory.prototype._call = function(name, uniforms, namespace, defines) {
var block, snippet;
snippet = this.fetch(name);
snippet.bind(this.config, uniforms, namespace, defines);
block = new Block.Call(snippet);
return this._auto(block);
};
Factory.prototype._subgraph = function(sub) {
var subgraph;
subgraph = new Graph(null, this._graph);
subgraph.adopt(sub.nodes);
return subgraph;
};
Factory.prototype._tail = function(state, graph) {
var tail;
tail = state.end.concat(state.tail);
tail = tail.filter(function(node, i) {
return tail.indexOf(node) === i;
});
if (tail.length > 1) {
tail = new Block.Join(tail);
tail = [tail.node];
this._graph.add(tail);
}
graph.tail = tail[0];
state.end = tail;
state.tail = [];
if (!graph.tail) {
throw new Error("Cannot finalize empty graph");
}
graph.compile = (function(_this) {
return function(namespace) {
var error;
if (namespace == null) {
namespace = 'main';
}
try {
return graph.tail.owner.compile(_this.language, namespace);
} catch (_error) {
error = _error;
if (_this.config.autoInspect) {
graph.inspect(error);
}
throw error;
}
};
})(this);
graph.link = (function(_this) {
return function(namespace) {
var error;
if (namespace == null) {
namespace = 'main';
}
try {
return graph.tail.owner.link(_this.language, namespace);
} catch (_error) {
error = _error;
if (_this.config.autoInspect) {
graph.inspect(error);
}
throw error;
}
};
})(this);
graph["export"] = (function(_this) {
return function(layout, depth) {
return graph.tail.owner["export"](layout, depth);
};
})(this);
return graph.inspect = function(message) {
if (message == null) {
message = null;
}
return Visualize.inspect(message, graph);
};
};
Factory.prototype._group = function(op, multi) {
this._push(op, multi);
this._push();
return this;
};
Factory.prototype._next = function() {
var sub;
sub = this._pop();
this._state.start = this._state.start.concat(sub.start);
this._state.end = this._state.end.concat(sub.end);
this._state.nodes = this._state.nodes.concat(sub.nodes);
this._state.tail = this._state.tail.concat(sub.tail);
return this._push();
};
Factory.prototype._exit = function() {
this._next();
this._pop();
return [this._pop(), this._state];
};
Factory.prototype._push = function(op, multi) {
this._stack.unshift(new State(op, multi));
return this._state = this._stack[0];
};
Factory.prototype._pop = function() {
var _ref;
this._state = this._stack[1];
if (this._state == null) {
this._state = new State;
}
return (_ref = this._stack.shift()) != null ? _ref : new State;
};
Factory.prototype._auto = function(block) {
if (block.node.inputs.length) {
return this._append(block);
} else {
return this._insert(block);
}
};
Factory.prototype._append = function(block) {
var end, node, _i, _len, _ref;
node = block.node;
this._graph.add(node);
_ref = this._state.end;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
end = _ref[_i];
end.connect(node);
}
if (!this._state.start.length) {
this._state.start = [node];
}
this._state.end = [node];
this._state.nodes.push(node);
if (!node.outputs.length) {
return this._state.tail.push(node);
}
};
Factory.prototype._prepend = function(block) {
var node, start, _i, _len, _ref;
node = block.node;
this._graph.add(node);
_ref = this._state.start;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
start = _ref[_i];
node.connect(start);
}
if (!this._state.end.length) {
this._state.end = [node];
}
this._state.start = [node];
this._state.nodes.push(node);
if (!node.outputs.length) {
return this._state.tail.push(node);
}
};
Factory.prototype._insert = function(block) {
var node;
node = block.node;
this._graph.add(node);
this._state.start.push(node);
this._state.end.push(node);
this._state.nodes.push(node);
if (!node.outputs.length) {
return this._state.tail.push(node);
}
};
return Factory;
})();
State = (function() {
function State(op, multi, start, end, nodes, tail) {
this.op = op != null ? op : null;
this.multi = multi != null ? multi : false;
this.start = start != null ? start : [];
this.end = end != null ? end : [];
this.nodes = nodes != null ? nodes : [];
this.tail = tail != null ? tail : [];
}
return State;
})();
module.exports = Factory;
},{"../block":8,"../graph":25,"../visualize":36}],13:[function(require,module,exports){
var c1, c2, c3, c4, c5, hash, imul, test;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
c3 = 0xe6546b64;
c4 = 0x85ebca6b;
c5 = 0xc2b2ae35;
imul = function(a, b) {
var ah, al, bh, bl;
ah = (a >>> 16) & 0xffff;
al = a & 0xffff;
bh = (b >>> 16) & 0xffff;
bl = b & 0xffff;
return (al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0;
};
if (Math.imul != null) {
test = Math.imul(0xffffffff, 5);
if (test === -5) {
imul = Math.imul;
}
}
hash = function(string) {
var h, iterate, j, m, n, next;
n = string.length;
m = Math.floor(n / 2);
j = h = 0;
next = function() {
return string.charCodeAt(j++);
};
iterate = function(a, b) {
var k;
k = a | (b << 16);
k ^= k << 9;
k = imul(k, c1);
k = (k << 15) | (k >>> 17);
k = imul(k, c2);
h ^= k;
h = (h << 13) | (h >>> 19);
h = imul(h, 5);
return h = (h + c3) | 0;
};
while (m--) {
iterate(next(), next());
}
if (n & 1) {
iterate(next(), 0);
}
h ^= n;
h ^= h >>> 16;
h = imul(h, c4);
h ^= h >>> 13;
h = imul(h, c5);
return h ^= h >>> 16;
};
module.exports = hash;
},{}],14:[function(require,module,exports){
exports.Factory = require('./factory');
exports.Material = require('./material');
exports.library = require('./library');
exports.cache = require('./cache');
exports.queue = require('./queue');
exports.hash = require('./hash');
},{"./cache":11,"./factory":12,"./hash":13,"./library":15,"./material":16,"./queue":17}],15:[function(require,module,exports){
/*
Snippet library
Takes:
- Hash of snippets: named library
- (name) -> getter: dynamic lookup
- nothing: no library, only pass in inline source code
If 'name' contains any of "{;(#" it is assumed to be direct GLSL code.
*/
var library;
library = function(language, snippets, load) {
var callback, fetch, inline, used;
callback = null;
used = {};
if (snippets != null) {
if (typeof snippets === 'function') {
callback = function(name) {
return load(language, name, snippets(name));
};
} else if (typeof snippets === 'object') {
callback = function(name) {
if (snippets[name] == null) {
throw new Error("Unknown snippet `" + name + "`");
}
return load(language, name, snippets[name]);
};
}
}
inline = function(code) {
return load(language, '', code);
};
if (callback == null) {
return inline;
}
fetch = function(name) {
if (name.match(/[{;]/)) {
return inline(name);
}
used[name] = true;
return callback(name);
};
fetch.used = function(_used) {
if (_used == null) {
_used = used;
}
return used = _used;
};
return fetch;
};
module.exports = library;
},{}],16:[function(require,module,exports){
var Material, Visualize, debug, tick;
debug = false;
Visualize = require('../visualize');
tick = function() {
var now;
now = +(new Date);
return function(label) {
var delta;
delta = +new Date() - now;
console.log(label, delta + " ms");
return delta;
};
};
Material = (function() {
function Material(vertex, fragment) {
this.vertex = vertex;
this.fragment = fragment;
if (debug) {
this.tock = tick();
}
}
Material.prototype.build = function(options) {
return this.link(options);
};
Material.prototype.link = function(options) {
var attributes, fragment, key, shader, uniforms, value, varyings, vertex, _i, _len, _ref, _ref1, _ref2, _ref3;
if (options == null) {
options = {};
}
uniforms = {};
varyings = {};
attributes = {};
vertex = this.vertex.link('main');
fragment = this.fragment.link('main');
_ref = [vertex, fragment];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
shader = _ref[_i];
_ref1 = shader.uniforms;
for (key in _ref1) {
value = _ref1[key];
uniforms[key] = value;
}
_ref2 = shader.varyings;
for (key in _ref2) {
value = _ref2[key];
varyings[key] = value;
}
_ref3 = shader.attributes;
for (key in _ref3) {
value = _ref3[key];
attributes[key] = value;
}
}
options.vertexShader = vertex.code;
options.vertexGraph = vertex.graph;
options.fragmentShader = fragment.code;
options.fragmentGraph = fragment.graph;
options.attributes = attributes;
options.uniforms = uniforms;
options.varyings = varyings;
options.inspect = function() {
return Visualize.inspect('Vertex Shader', vertex, 'Fragment Shader', fragment.graph);
};
if (debug) {
this.tock('Material build');
}
return options;
};
Material.prototype.inspect = function() {
return Visualize.inspect('Vertex Shader', this.vertex, 'Fragment Shader', this.fragment.graph);
};
return Material;
})();
module.exports = Material;
},{"../visualize":36}],17:[function(require,module,exports){
var queue;
queue = function(limit) {
var add, count, head, map, remove, tail;
if (limit == null) {
limit = 100;
}
map = {};
head = null;
tail = null;
count = 0;
add = function(item) {
item.prev = null;
item.next = head;
if (head != null) {
head.prev = item;
}
head = item;
if (tail == null) {
return tail = item;
}
};
remove = function(item) {
var next, prev;
prev = item.prev;
next = item.next;
if (prev != null) {
prev.next = next;
}
if (next != null) {
next.prev = prev;
}
if (head === item) {
head = next;
}
if (tail === item) {
return tail = prev;
}
};
return function(key) {
var dead, item;
if (item = map[key] && item !== head) {
remove(item);
add(item);
} else {
if (count === limit) {
dead = tail.key;
remove(tail);
delete map[dead];
} else {
count++;
}
item = {
next: head,
prev: null,
key: key
};
add(item);
map[key] = item;
}
return dead;
};
};
module.exports = queue;
},{}],18:[function(require,module,exports){
/*
Compile snippet back into GLSL, but with certain symbols replaced by prefixes / placeholders
*/
var compile, replaced, string_compiler, tick;
compile = function(program) {
var assembler, ast, code, placeholders, signatures;
ast = program.ast, code = program.code, signatures = program.signatures;
placeholders = replaced(signatures);
assembler = string_compiler(code, placeholders);
return [signatures, assembler];
};
tick = function() {
var now;
now = +(new Date);
return function(label) {
var delta;
delta = +new Date() - now;
console.log(label, delta + " ms");
return delta;
};
};
replaced = function(signatures) {
var key, out, s, sig, _i, _j, _len, _len1, _ref, _ref1;
out = {};
s = function(sig) {
return out[sig.name] = true;
};
s(signatures.main);
_ref = ['external', 'internal', 'varying', 'uniform', 'attribute'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
_ref1 = signatures[key];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
sig = _ref1[_j];
s(sig);
}
}
return out;
};
/*
String-replacement based compiler
*/
string_compiler = function(code, placeholders) {
var key, re;
re = new RegExp('\\b(' + ((function() {
var _results;
_results = [];
for (key in placeholders) {
_results.push(key);
}
return _results;
})()).join('|') + ')\\b', 'g');
code = code.replace(/\/\/[^\n]*/g, '');
code = code.replace(/\/\*([^*]|\*[^\/])*\*\//g, '');
return function(prefix, exceptions, defines) {
var compiled, defs, replace, value;
if (prefix == null) {
prefix = '';
}
if (exceptions == null) {
exceptions = {};
}
if (defines == null) {
defines = {};
}
replace = {};
for (key in placeholders) {
replace[key] = exceptions[key] != null ? key : prefix + key;
}
compiled = code.replace(re, function(key) {
return replace[key];
});
defs = (function() {
var _results;
_results = [];
for (key in defines) {
value = defines[key];
_results.push("#define " + key + " " + value);
}
return _results;
})();
if (defs.length) {
defs.push('');
}
return defs.join("\n") + compiled;
};
};
module.exports = compile;
},{}],19:[function(require,module,exports){
module.exports = {
SHADOW_ARG: '_i_o',
RETURN_ARG: 'return'
};
},{}],20:[function(require,module,exports){
var Definition, decl, defaults, get, three, threejs, win;
module.exports = decl = {};
decl["in"] = 0;
decl.out = 1;
decl.inout = 2;
get = function(n) {
return n.token.data;
};
decl.node = function(node) {
var _ref, _ref1;
if (((_ref = node.children[5]) != null ? _ref.type : void 0) === 'function') {
return decl["function"](node);
} else if (((_ref1 = node.token) != null ? _ref1.type : void 0) === 'keyword') {
return decl.external(node);
}
};
decl.external = function(node) {
var c, i, ident, list, next, out, quant, storage, struct, type, _i, _len, _ref;
c = node.children;
storage = get(c[1]);
struct = get(c[3]);
type = get(c[4]);
list = c[5];
if (storage !== 'attribute' && storage !== 'uniform' && storage !== 'varying') {
storage = 'global';
}
out = [];
_ref = list.children;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
c = _ref[i];
if (c.type === 'ident') {
ident = get(c);
next = list.children[i + 1];
quant = (next != null ? next.type : void 0) === 'quantifier';
out.push({
decl: 'external',
storage: storage,
type: type,
ident: ident,
quant: !!quant,
count: quant
});
}
}
return out;
};
decl["function"] = function(node) {
var args, body, c, child, decls, func, ident, storage, struct, type;
c = node.children;
storage = get(c[1]);
struct = get(c[3]);
type = get(c[4]);
func = c[5];
ident = get(func.children[0]);
args = func.children[1];
body = func.children[2];
decls = (function() {
var _i, _len, _ref, _results;
_ref = args.children;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
_results.push(decl.argument(child));
}
return _results;
})();
return [
{
decl: 'function',
storage: storage,
type: type,
ident: ident,
body: !!body,
args: decls
}
];
};
decl.argument = function(node) {
var c, count, ident, inout, list, quant, storage, type;
c = node.children;
storage = get(c[1]);
inout = get(c[2]);
type = get(c[4]);
list = c[5];
ident = get(list.children[0]);
quant = list.children[1];
count = quant ? quant.children[0].token.data : void 0;
return {
decl: 'argument',
storage: storage,
inout: inout,
type: type,
ident: ident,
quant: !!quant,
count: count
};
};
decl.param = function(dir, storage, spec, quant, count) {
var f, prefix, suffix;
prefix = [];
if (storage != null) {
prefix.push(storage);
}
if (spec != null) {
prefix.push(spec);
}
prefix.push('');
prefix = prefix.join(' ');
suffix = quant ? '[' + count + ']' : '';
if (dir !== '') {
dir += ' ';
}
f = function(name, long) {
return (long ? dir : '') + ("" + prefix + name + suffix);
};
f.split = function(dir) {
return decl.param(dir, storage, spec, quant, count);
};
return f;
};
win = typeof window !== 'undefined';
threejs = win && !!window.THREE;
defaults = {
int: 0,
float: 0,
vec2: threejs ? THREE.Vector2 : null,
vec3: threejs ? THREE.Vector3 : null,
vec4: threejs ? THREE.Vector4 : null,
mat2: null,
mat3: threejs ? THREE.Matrix3 : null,
mat4: threejs ? THREE.Matrix4 : null,
sampler2D: 0,
samplerCube: 0
};
three = {
int: 'i',
float: 'f',
vec2: 'v2',
vec3: 'v3',
vec4: 'v4',
mat2: 'm2',
mat3: 'm3',
mat4: 'm4',
sampler2D: 't',
samplerCube: 't'
};
decl.type = function(name, spec, quant, count, dir, storage) {
var dirs, inout, param, storages, type, value, _ref;
dirs = {
"in": decl["in"],
out: decl.out,
inout: decl.inout
};
storages = {
"const": 'const'
};
type = three[spec];
if (quant) {
type += 'v';
}
value = defaults[spec];
if (value != null ? value.call : void 0) {
value = new value;
}
if (quant) {
value = [value];
}
inout = (_ref = dirs[dir]) != null ? _ref : dirs["in"];
storage = storages[storage];
param = decl.param(dir, storage, spec, quant, count);
return new Definition(name, type, spec, param, value, inout);
};
Definition = (function() {
function Definition(name, type, spec, param, value, inout, meta) {
this.name = name;
this.type = type;
this.spec = spec;
this.param = param;
this.value = value;
this.inout = inout;
this.meta = meta;
}
Definition.prototype.split = function() {
var dir, inout, isIn, param;
isIn = this.meta.shadowed != null;
dir = isIn ? 'in' : 'out';
inout = isIn ? decl["in"] : decl.out;
param = this.param.split(dir);
return new Definition(this.name, this.type, this.spec, param, this.value, inout);
};
Definition.prototype.copy = function(name, meta) {
var def;
return def = new Definition(name != null ? name : this.name, this.type, this.spec, this.param, this.value, this.inout, meta);
};
return Definition;
})();
},{}],21:[function(require,module,exports){
var $, Graph, _;
Graph = require('../graph');
$ = require('./constants');
/*
GLSL code generator for compiler and linker stubs
*/
module.exports = _ = {
unshadow: function(name) {
var real;
real = name.replace($.SHADOW_ARG, '');
if (real !== name) {
return real;
} else {
return null;
}
},
lines: function(lines) {
return lines.join('\n');
},
list: function(lines) {
return lines.join(', ');
},
statements: function(lines) {
return lines.join(';\n');
},
body: function(entry) {
return {
entry: entry,
type: 'void',
params: [],
signature: [],
"return": '',
vars: {},
calls: [],
post: [],
chain: {}
};
},
define: function(a, b) {
return "#define " + a + " " + b;
},
"function": function(type, entry, params, vars, calls) {
return "" + type + " " + entry + "(" + params + ") {\n" + vars + calls + "}";
},
invoke: function(ret, entry, args) {
ret = ret ? "" + ret + " = " : '';
args = _.list(args);
return " " + ret + entry + "(" + args + ")";
},
same: function(a, b) {
var A, B, i, _i, _len;
for (i = _i = 0, _len = a.length; _i < _len; i = ++_i) {
A = a[i];
B = b[i];
if (!B) {
return false;
}
if (A.type !== B.type) {
return false;
}
if ((A.name === $.RETURN_ARG) !== (B.name === $.RETURN_ARG)) {
return false;
}
}
return true;
},
call: function(lookup, dangling, entry, signature, body) {
var arg, args, copy, id, inout, isReturn, meta, name, omit, op, other, ret, rets, shadow, _i, _len, _ref, _ref1;
args = [];
ret = '';
rets = 1;
for (_i = 0, _len = signature.length; _i < _len; _i++) {
arg = signature[_i];
name = arg.name;
copy = id = lookup(name);
other = null;
meta = null;
omit = false;
inout = arg.inout;
isReturn = name === $.RETURN_ARG;
if (shadow = (_ref = arg.meta) != null ? _ref.shadowed : void 0) {
other = lookup(shadow);
if (other) {
body.vars[other] = " " + arg.param(other);
body.calls.push(" " + other + " = " + id);
if (!dangling(shadow)) {
arg = arg.split();
} else {
meta = {
shadowed: other
};
}
}
}
if (shadow = (_ref1 = arg.meta) != null ? _ref1.shadow : void 0) {
other = lookup(shadow);
if (other) {
if (!dangling(shadow)) {
arg = arg.split();
omit = true;
} else {
meta = {
shadow: other
};
continue;
}
}
}
if (isReturn) {
ret = id;
} else if (!omit) {
args.push(other != null ? other : id);
}
if (dangling(name)) {
op = 'push';
if (isReturn) {
if (body["return"] === '') {
op = 'unshift';
copy = name;
body.type = arg.spec;
body["return"] = " return " + id;
body.vars[id] = " " + arg.param(id);
} else {
body.vars[id] = " " + arg.param(id);
body.params.push(arg.param(id, true));
}
} else {
body.params.push(arg.param(id, true));
}
arg = arg.copy(copy, meta);
body.signature[op](arg);
} else {
body.vars[id] = " " + arg.param(id);
}
}
return body.calls.push(_.invoke(ret, entry, args));
},
build: function(body, calls) {
var a, b, code, decl, entry, params, post, ret, type, v, vars;
entry = body.entry;
code = null;
if (calls && calls.length === 1 && entry !== 'main') {
a = body;
b = calls[0].module;
if (_.same(body.signature, b.main.signature)) {
code = _.define(entry, b.entry);
}
}
if (code == null) {
vars = (function() {
var _ref, _results;
_ref = body.vars;
_results = [];
for (v in _ref) {
decl = _ref[v];
_results.push(decl);
}
return _results;
})();
calls = body.calls;
post = body.post;
params = body.params;
type = body.type;
ret = body["return"];
calls = calls.concat(post);
if (ret !== '') {
calls.push(ret);
}
calls.push('');
if (vars.length) {
vars.push('');
vars = _.statements(vars) + '\n';
} else {
vars = '';
}
calls = _.statements(calls);
params = _.list(params);
code = _["function"](type, entry, params, vars, calls);
}
return {
signature: body.signature,
code: code,
name: entry
};
},
links: function(links) {
var l, out, _i, _len;
out = {
defs: [],
bodies: []
};
for (_i = 0, _len = links.length; _i < _len; _i++) {
l = links[_i];
_.link(l, out);
}
out.defs = _.lines(out.defs);
out.bodies = _.statements(out.bodies);
if (out.defs === '') {
delete out.defs;
}
if (out.bodies === '') {
delete out.bodies;
}
return out;
},
link: (function(_this) {
return function(link, out) {
var arg, entry, external, inner, ins, list, main, map, module, name, other, outer, outs, returnVar, wrapper, _dangling, _i, _j, _len, _len1, _lookup, _name, _ref, _ref1;
module = link.module, name = link.name, external = link.external;
main = module.main;
entry = module.entry;
if (_.same(main.signature, external.signature)) {
return out.defs.push(_.define(name, entry));
}
ins = [];
outs = [];
map = {};
returnVar = [module.namespace, $.RETURN_ARG].join('');
_ref = external.signature;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
list = arg.inout === Graph.IN ? ins : outs;
list.push(arg);
}
_ref1 = main.signature;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
arg = _ref1[_j];
list = arg.inout === Graph.IN ? ins : outs;
other = list.shift();
_name = other.name;
if (_name === $.RETURN_ARG) {
_name = returnVar;
}
map[arg.name] = _name;
}
_lookup = function(name) {
return map[name];
};
_dangling = function() {
return true;
};
inner = _.body();
_.call(_lookup, _dangling, entry, main.signature, inner);
inner.entry = entry;
map = {
"return": returnVar
};
_lookup = function(name) {
var _ref2;
return (_ref2 = map[name]) != null ? _ref2 : name;
};
outer = _.body();
wrapper = _.call(_lookup, _dangling, entry, external.signature, outer);
outer.calls = inner.calls;
outer.entry = name;
out.bodies.push(_.build(inner).code.split(' {')[0]);
return out.bodies.push(_.build(outer).code);
};
})(this),
defuse: function(code) {
var b, blocks, hash, head, i, j, level, line, re, rest, strip, _i, _j, _len, _len1;
re = /([A-Za-z0-9_]+\s+)?[A-Za-z0-9_]+\s+[A-Za-z0-9_]+\s*\([^)]*\)\s*;\s*/mg;
strip = function(code) {
return code.replace(re, function(m) {
return '';
});
};
blocks = code.split(/(?=[{}])/g);
level = 0;
for (i = _i = 0, _len = blocks.length; _i < _len; i = ++_i) {
b = blocks[i];
switch (b[0]) {
case '{':
level++;
break;
case '}':
level--;
}
if (level === 0) {
hash = b.split(/^[ \t]*#/m);
for (j = _j = 0, _len1 = hash.length; _j < _len1; j = ++_j) {
line = hash[j];
if (j > 0) {
line = line.split(/\n/);
head = line.shift();
rest = line.join("\n");
hash[j] = [head, strip(rest)].join('\n');
} else {
hash[j] = strip(line);
}
}
blocks[i] = hash.join('#');
}
}
return code = blocks.join('');
},
dedupe: function(code) {
var map, re;
map = {};
re = /((attribute|uniform|varying)\s+)[A-Za-z0-9_]+\s+([A-Za-z0-9_]+)\s*(\[[^\]]*\]\s*)?;\s*/mg;
return code.replace(re, function(m, qual, type, name, struct) {
if (map[name]) {
return '';
}
map[name] = true;
return m;
});
},
hoist: function(code) {
var defs, line, lines, list, out, re, _i, _len;
re = /^#define ([^ ]+ _pg_[0-9]+_|_pg_[0-9]+_ [^ ]+)$/;
lines = code.split(/\n/g);
defs = [];
out = [];
for (_i = 0, _len = lines.length; _i < _len; _i++) {
line = lines[_i];
list = line.match(re) ? defs : out;
list.push(line);
}
return defs.concat(out).join("\n");
}
};
},{"../graph":25,"./constants":19}],22:[function(require,module,exports){
var k, v, _i, _len, _ref;
exports.compile = require('./compile');
exports.parse = require('./parse');
exports.generate = require('./generate');
_ref = require('./constants');
for (v = _i = 0, _len = _ref.length; _i < _len; v = ++_i) {
k = _ref[v];
exports[k] = v;
}
},{"./compile":18,"./constants":19,"./generate":21,"./parse":23}],23:[function(require,module,exports){
var $, collect, debug, decl, extractSignatures, mapSymbols, parse, parseGLSL, parser, processAST, sortSymbols, tick, tokenizer, walk;
tokenizer = require('../../vendor/glsl-tokenizer');
parser = require('../../vendor/glsl-parser');
decl = require('./decl');
$ = require('./constants');
debug = false;
/*
parse GLSL into AST
extract all global symbols and make type signatures
*/
parse = function(name, code) {
var ast, program;
ast = parseGLSL(name, code);
return program = processAST(ast, code);
};
parseGLSL = function(name, code) {
var ast, e, error, errors, fmt, tock, _i, _len, _ref, _ref1;
if (debug) {
tock = tick();
}
try {
_ref = tokenizer().process(parser(), code), (_ref1 = _ref[0], ast = _ref1[0]), errors = _ref[1];
} catch (_error) {
e = _error;
errors = [
{
message: e
}
];
}
if (debug) {
tock('GLSL Tokenize & Parse');
}
fmt = function(code) {
var max, pad;
code = code.split("\n");
max = ("" + code.length).length;
pad = function(v) {
if ((v = "" + v).length < max) {
return (" " + v).slice(-max);
} else {
return v;
}
};
return code.map(function(line, i) {
return "" + (pad(i + 1)) + ": " + line;
}).join("\n");
};
if (!ast || errors.length) {
if (!name) {
name = '(inline code)';
}
console.warn(fmt(code));
for (_i = 0, _len = errors.length; _i < _len; _i++) {
error = errors[_i];
console.error("" + name + " -", error.message);
}
throw new Error("GLSL parse error");
}
return ast;
};
processAST = function(ast, code) {
var externals, internals, main, signatures, symbols, tock, _ref;
if (debug) {
tock = tick();
}
symbols = [];
walk(mapSymbols, collect(symbols), ast, '');
_ref = sortSymbols(symbols), main = _ref[0], internals = _ref[1], externals = _ref[2];
signatures = extractSignatures(main, internals, externals);
if (debug) {
tock('GLSL AST');
}
return {
ast: ast,
code: code,
signatures: signatures
};
};
mapSymbols = function(node, collect) {
switch (node.type) {
case 'decl':
collect(decl.node(node));
return false;
}
return true;
};
collect = function(out) {
return function(value) {
var obj, _i, _len, _results;
if (value != null) {
_results = [];
for (_i = 0, _len = value.length; _i < _len; _i++) {
obj = value[_i];
_results.push(out.push(obj));
}
return _results;
}
};
};
sortSymbols = function(symbols) {
var e, externals, found, internals, main, maybe, s, _i, _len;
main = null;
internals = [];
externals = [];
maybe = {};
found = false;
for (_i = 0, _len = symbols.length; _i < _len; _i++) {
s = symbols[_i];
if (!s.body) {
if (s.storage === 'global') {
internals.push(s);
} else {
externals.push(s);
maybe[s.ident] = true;
}
} else {
if (maybe[s.ident]) {
externals = (function() {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = externals.length; _j < _len1; _j++) {
e = externals[_j];
if (e.ident !== s.ident) {
_results.push(e);
}
}
return _results;
})();
delete maybe[s.ident];
}
internals.push(s);
if (s.ident === 'main') {
main = s;
found = true;
} else if (!found) {
main = s;
}
}
}
return [main, internals, externals];
};
extractSignatures = function(main, internals, externals) {
var def, defn, func, sigs, symbol, _i, _j, _len, _len1;
sigs = {
uniform: [],
attribute: [],
varying: [],
external: [],
internal: [],
global: [],
main: null
};
defn = function(symbol) {
return decl.type(symbol.ident, symbol.type, symbol.quant, symbol.count, symbol.inout, symbol.storage);
};
func = function(symbol, inout) {
var a, arg, b, d, def, inTypes, outTypes, signature, type, _i, _len;
signature = (function() {
var _i, _len, _ref, _results;
_ref = symbol.args;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
_results.push(defn(arg));
}
return _results;
})();
for (_i = 0, _len = signature.length; _i < _len; _i++) {
d = signature[_i];
if (!(d.inout === decl.inout)) {
continue;
}
a = d;
b = d.copy();
a.inout = decl["in"];
b.inout = decl.out;
b.meta = {
shadow: a.name
};
b.name += $.SHADOW_ARG;
a.meta = {
shadowed: b.name
};
signature.push(b);
}
if (symbol.type !== 'void') {
signature.unshift(decl.type($.RETURN_ARG, symbol.type, false, '', 'out'));
}
inTypes = ((function() {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = signature.length; _j < _len1; _j++) {
d = signature[_j];
if (d.inout === decl["in"]) {
_results.push(d.type);
}
}
return _results;
})()).join(',');
outTypes = ((function() {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = signature.length; _j < _len1; _j++) {
d = signature[_j];
if (d.inout === decl.out) {
_results.push(d.type);
}
}
return _results;
})()).join(',');
type = "(" + inTypes + ")(" + outTypes + ")";
return def = {
name: symbol.ident,
type: type,
signature: signature,
inout: inout,
spec: symbol.type
};
};
sigs.main = func(main, decl.out);
for (_i = 0, _len = internals.length; _i < _len; _i++) {
symbol = internals[_i];
sigs.internal.push({
name: symbol.ident
});
}
for (_j = 0, _len1 = externals.length; _j < _len1; _j++) {
symbol = externals[_j];
switch (symbol.decl) {
case 'external':
def = defn(symbol);
sigs[symbol.storage].push(def);
break;
case 'function':
def = func(symbol, decl["in"]);
sigs.external.push(def);
}
}
return sigs;
};
debug = false;
walk = function(map, collect, node, indent) {
var child, i, recurse, _i, _len, _ref, _ref1, _ref2;
debug && console.log(indent, node.type, (_ref = node.token) != null ? _ref.data : void 0, (_ref1 = node.token) != null ? _ref1.type : void 0);
recurse = map(node, collect);
if (recurse) {
_ref2 = node.children;
for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
child = _ref2[i];
walk(map, collect, child, indent + ' ', debug);
}
}
return null;
};
tick = function() {
var now;
now = +(new Date);
return function(label) {
var delta;
delta = +new Date() - now;
console.log(label, delta + " ms");
return delta;
};
};
module.exports = walk;
module.exports = parse;
},{"../../vendor/glsl-parser":39,"../../vendor/glsl-tokenizer":43,"./constants":19,"./decl":20}],24:[function(require,module,exports){
/*
Graph of nodes with outlets
*/
var Graph;
Graph = (function() {
Graph.index = 0;
Graph.id = function(name) {
return ++Graph.index;
};
Graph.IN = 0;
Graph.OUT = 1;
function Graph(nodes, parent) {
this.parent = parent != null ? parent : null;
this.id = Graph.id();
this.nodes = [];
nodes && this.add(nodes);
}
Graph.prototype.inputs = function() {
var inputs, node, outlet, _i, _j, _len, _len1, _ref, _ref1;
inputs = [];
_ref = this.nodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
_ref1 = node.inputs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
if (outlet.input === null) {
inputs.push(outlet);
}
}
}
return inputs;
};
Graph.prototype.outputs = function() {
var node, outlet, outputs, _i, _j, _len, _len1, _ref, _ref1;
outputs = [];
_ref = this.nodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
_ref1 = node.outputs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
if (outlet.output.length === 0) {
outputs.push(outlet);
}
}
}
return outputs;
};
Graph.prototype.getIn = function(name) {
var outlet;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.inputs();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
if (outlet.name === name) {
_results.push(outlet);
}
}
return _results;
}).call(this))[0];
};
Graph.prototype.getOut = function(name) {
var outlet;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.outputs();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
if (outlet.name === name) {
_results.push(outlet);
}
}
return _results;
}).call(this))[0];
};
Graph.prototype.add = function(node, ignore) {
var _i, _len, _node;
if (node.length) {
for (_i = 0, _len = node.length; _i < _len; _i++) {
_node = node[_i];
this.add(_node);
}
return;
}
if (node.graph && !ignore) {
throw new Error("Adding node to two graphs at once");
}
node.graph = this;
return this.nodes.push(node);
};
Graph.prototype.remove = function(node, ignore) {
var _i, _len, _node;
if (node.length) {
for (_i = 0, _len = node.length; _i < _len; _i++) {
_node = node[_i];
this.remove(_node);
}
return;
}
if (node.graph !== this) {
throw new Error("Removing node from wrong graph.");
}
ignore || node.disconnect();
this.nodes.splice(this.nodes.indexOf(node), 1);
return node.graph = null;
};
Graph.prototype.adopt = function(node) {
var _i, _len, _node;
if (node.length) {
for (_i = 0, _len = node.length; _i < _len; _i++) {
_node = node[_i];
this.adopt(_node);
}
return;
}
node.graph.remove(node, true);
return this.add(node, true);
};
return Graph;
})();
module.exports = Graph;
},{}],25:[function(require,module,exports){
exports.Graph = require('./graph');
exports.Node = require('./node');
exports.Outlet = require('./outlet');
exports.IN = exports.Graph.IN;
exports.OUT = exports.Graph.OUT;
},{"./graph":24,"./node":26,"./outlet":27}],26:[function(require,module,exports){
var Graph, Node, Outlet;
Graph = require('./graph');
Outlet = require('./outlet');
/*
Node in graph.
*/
Node = (function() {
Node.index = 0;
Node.id = function(name) {
return ++Node.index;
};
function Node(owner, outlets) {
this.owner = owner;
this.graph = null;
this.inputs = [];
this.outputs = [];
this.all = [];
this.outlets = null;
this.id = Node.id();
this.setOutlets(outlets);
}
Node.prototype.getIn = function(name) {
var outlet;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.inputs;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
if (outlet.name === name) {
_results.push(outlet);
}
}
return _results;
}).call(this))[0];
};
Node.prototype.getOut = function(name) {
var outlet;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.outputs;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
if (outlet.name === name) {
_results.push(outlet);
}
}
return _results;
}).call(this))[0];
};
Node.prototype.get = function(name) {
return this.getIn(name) || this.getOut(name);
};
Node.prototype.setOutlets = function(outlets) {
var existing, hash, key, match, outlet, _i, _j, _k, _len, _len1, _len2, _ref;
if (outlets != null) {
if (this.outlets == null) {
this.outlets = {};
for (_i = 0, _len = outlets.length; _i < _len; _i++) {
outlet = outlets[_i];
if (!(outlet instanceof Outlet)) {
outlet = Outlet.make(outlet);
}
this._add(outlet);
}
return;
}
hash = function(outlet) {
return [outlet.name, outlet.inout, outlet.type].join('-');
};
match = {};
for (_j = 0, _len1 = outlets.length; _j < _len1; _j++) {
outlet = outlets[_j];
match[hash(outlet)] = true;
}
_ref = this.outlets;
for (key in _ref) {
outlet = _ref[key];
key = hash(outlet);
if (match[key]) {
match[key] = outlet;
} else {
this._remove(outlet);
}
}
for (_k = 0, _len2 = outlets.length; _k < _len2; _k++) {
outlet = outlets[_k];
existing = match[hash(outlet)];
if (existing instanceof Outlet) {
this._morph(existing, outlet);
} else {
if (!(outlet instanceof Outlet)) {
outlet = Outlet.make(outlet);
}
this._add(outlet);
}
}
this;
}
return this.outlets;
};
Node.prototype.connect = function(node, empty, force) {
var dest, dests, hint, hints, list, outlets, source, sources, type, typeHint, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2;
outlets = {};
hints = {};
typeHint = function(outlet) {
return type + '/' + outlet.hint;
};
_ref = node.inputs;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
dest = _ref[_i];
if (!force && dest.input) {
continue;
}
type = dest.type;
hint = typeHint(dest);
if (!hints[hint]) {
hints[hint] = dest;
}
outlets[type] = list = outlets[type] || [];
list.push(dest);
}
sources = this.outputs;
sources = sources.filter(function(outlet) {
return !(empty && outlet.output.length);
});
_ref1 = sources.slice();
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
source = _ref1[_j];
type = source.type;
hint = typeHint(source);
dests = outlets[type];
if (dest = hints[hint]) {
source.connect(dest);
delete hints[hint];
dests.splice(dests.indexOf(dest), 1);
sources.splice(sources.indexOf(source), 1);
}
}
if (!sources.length) {
return this;
}
_ref2 = sources.slice();
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
source = _ref2[_k];
type = source.type;
dests = outlets[type];
if (dests && dests.length) {
source.connect(dests.shift());
}
}
return this;
};
Node.prototype.disconnect = function(node) {
var outlet, _i, _j, _len, _len1, _ref, _ref1;
_ref = this.inputs;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
outlet.disconnect();
}
_ref1 = this.outputs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
outlet.disconnect();
}
return this;
};
Node.prototype._key = function(outlet) {
return [outlet.name, outlet.inout].join('-');
};
Node.prototype._add = function(outlet) {
var key;
key = this._key(outlet);
if (outlet.node) {
throw new Error("Adding outlet to two nodes at once.");
}
if (this.outlets[key]) {
throw new Error("Adding two identical outlets to same node. (" + key + ")");
}
outlet.node = this;
if (outlet.inout === Graph.IN) {
this.inputs.push(outlet);
}
if (outlet.inout === Graph.OUT) {
this.outputs.push(outlet);
}
this.all.push(outlet);
return this.outlets[key] = outlet;
};
Node.prototype._morph = function(existing, outlet) {
var key;
key = this._key(outlet);
delete this.outlets[key];
existing.morph(outlet);
key = this._key(outlet);
return this.outlets[key] = outlet;
};
Node.prototype._remove = function(outlet) {
var inout, key;
key = this._key(outlet);
inout = outlet.inout;
if (outlet.node !== this) {
throw new Error("Removing outlet from wrong node.");
}
outlet.disconnect();
outlet.node = null;
delete this.outlets[key];
if (outlet.inout === Graph.IN) {
this.inputs.splice(this.inputs.indexOf(outlet), 1);
}
if (outlet.inout === Graph.OUT) {
this.outputs.splice(this.outputs.indexOf(outlet), 1);
}
this.all.splice(this.all.indexOf(outlet), 1);
return this;
};
return Node;
})();
module.exports = Node;
},{"./graph":24,"./outlet":27}],27:[function(require,module,exports){
var Graph, Outlet;
Graph = require('./graph');
/*
In/out outlet on node
*/
Outlet = (function() {
Outlet.make = function(outlet, extra) {
var key, meta, value, _ref;
if (extra == null) {
extra = {};
}
meta = extra;
if (outlet.meta != null) {
_ref = outlet.meta;
for (key in _ref) {
value = _ref[key];
meta[key] = value;
}
}
return new Outlet(outlet.inout, outlet.name, outlet.hint, outlet.type, meta);
};
Outlet.index = 0;
Outlet.id = function(name) {
return "_io_" + (++Outlet.index) + "_" + name;
};
Outlet.hint = function(name) {
name = name.replace(/^_io_[0-9]+_/, '');
name = name.replace(/_i_o$/, '');
return name = name.replace(/(In|Out|Inout|InOut)$/, '');
};
function Outlet(inout, name, hint, type, meta, id) {
this.inout = inout;
this.name = name;
this.hint = hint;
this.type = type;
this.meta = meta != null ? meta : {};
this.id = id;
if (this.hint == null) {
this.hint = Outlet.hint(name);
}
this.node = null;
this.input = null;
this.output = [];
if (this.id == null) {
this.id = Outlet.id(this.hint);
}
}
Outlet.prototype.morph = function(outlet) {
this.inout = outlet.inout;
this.name = outlet.name;
this.hint = outlet.hint;
this.type = outlet.type;
return this.meta = outlet.meta;
};
Outlet.prototype.dupe = function(name) {
var outlet;
if (name == null) {
name = this.id;
}
outlet = Outlet.make(this);
outlet.name = name;
return outlet;
};
Outlet.prototype.connect = function(outlet) {
if (this.inout === Graph.IN && outlet.inout === Graph.OUT) {
return outlet.connect(this);
}
if (this.inout !== Graph.OUT || outlet.inout !== Graph.IN) {
throw new Error("Can only connect out to in.");
}
if (outlet.input === this) {
return;
}
outlet.disconnect();
outlet.input = this;
return this.output.push(outlet);
};
Outlet.prototype.disconnect = function(outlet) {
var index, _i, _len, _ref;
if (this.input) {
this.input.disconnect(this);
}
if (this.output.length) {
if (outlet) {
index = this.output.indexOf(outlet);
if (index >= 0) {
this.output.splice(index, 1);
return outlet.input = null;
}
} else {
_ref = this.output;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
outlet = _ref[_i];
outlet.input = null;
}
return this.output = [];
}
}
};
return Outlet;
})();
module.exports = Outlet;
},{"./graph":24}],28:[function(require,module,exports){
var Block, Factory, GLSL, Graph, Linker, ShaderGraph, Snippet, Visualize, cache, inspect, library, merge, visualize;
Block = require('./block');
Factory = require('./factory');
GLSL = require('./glsl');
Graph = require('./graph');
Linker = require('./linker');
Visualize = require('./visualize');
library = Factory.library;
cache = Factory.cache;
visualize = Visualize.visualize;
inspect = Visualize.inspect;
Snippet = Linker.Snippet;
merge = function(a, b) {
var key, out, value, _ref;
if (b == null) {
b = {};
}
out = {};
for (key in a) {
value = a[key];
out[key] = (_ref = b[key]) != null ? _ref : a[key];
}
return out;
};
ShaderGraph = (function() {
function ShaderGraph(snippets, config) {
var defaults;
if (!(this instanceof ShaderGraph)) {
return new ShaderGraph(snippets, config);
}
defaults = {
globalUniforms: false,
globalVaryings: true,
globalAttributes: true,
globals: [],
autoInspect: false
};
this.config = merge(defaults, config);
this.fetch = cache(library(GLSL, snippets, Snippet.load));
}
ShaderGraph.prototype.shader = function(config) {
var _config;
if (config == null) {
config = {};
}
_config = merge(this.config, config);
return new Factory.Factory(GLSL, this.fetch, _config);
};
ShaderGraph.prototype.material = function(config) {
return new Factory.Material(this.shader(config), this.shader(config));
};
ShaderGraph.prototype.overlay = function(shader) {
return ShaderGraph.overlay(shader);
};
ShaderGraph.prototype.visualize = function(shader) {
return ShaderGraph.visualize(shader);
};
ShaderGraph.Block = Block;
ShaderGraph.Factory = Factory;
ShaderGraph.GLSL = GLSL;
ShaderGraph.Graph = Graph;
ShaderGraph.Linker = Linker;
ShaderGraph.Visualize = Visualize;
ShaderGraph.inspect = function(shader) {
return inspect(shader);
};
ShaderGraph.visualize = function(shader) {
return visualize(shader);
};
return ShaderGraph;
})();
module.exports = ShaderGraph;
if (typeof window !== 'undefined') {
window.ShaderGraph = ShaderGraph;
}
},{"./block":8,"./factory":14,"./glsl":22,"./graph":25,"./linker":30,"./visualize":36}],29:[function(require,module,exports){
var Graph, Priority, assemble;
Graph = require('../graph');
Priority = require('./priority');
/*
Program assembler
Builds composite program that can act as new module/snippet
Unconnected input/outputs and undefined callbacks are exposed in the new global/main scope
If there is only one call with an identical call signature, a #define is output instead.
*/
assemble = function(language, namespace, calls, requires) {
var adopt, attributes, externals, generate, handle, include, isDangling, library, lookup, process, required, symbols, uniforms, varyings;
generate = language.generate;
externals = {};
symbols = [];
uniforms = {};
varyings = {};
attributes = {};
library = {};
process = function() {
var body, code, includes, lib, main, ns, r, sorted, _ref;
for (ns in requires) {
r = requires[ns];
required(r.node, r.module);
}
_ref = handle(calls), body = _ref[0], calls = _ref[1];
if (namespace != null) {
body.entry = namespace;
}
main = generate.build(body, calls);
sorted = ((function() {
var _results;
_results = [];
for (ns in library) {
lib = library[ns];
_results.push(lib);
}
return _results;
})()).sort(function(a, b) {
return Priority.compare(a.priority, b.priority);
});
includes = sorted.map(function(x) {
return x.code;
});
includes.push(main.code);
code = generate.lines(includes);
return {
namespace: main.name,
library: library,
body: main.code,
code: code,
main: main,
entry: main.name,
symbols: symbols,
externals: externals,
uniforms: uniforms,
varyings: varyings,
attributes: attributes
};
};
handle = (function(_this) {
return function(calls) {
var body, c, call, ns, _i, _len;
calls = (function() {
var _results;
_results = [];
for (ns in calls) {
c = calls[ns];
_results.push(c);
}
return _results;
})();
calls.sort(function(a, b) {
return b.priority - a.priority;
});
call = function(node, module, priority) {
var entry, main, _dangling, _lookup;
include(node, module, priority);
main = module.main;
entry = module.entry;
_lookup = function(name) {
return lookup(node, name);
};
_dangling = function(name) {
return isDangling(node, name);
};
return generate.call(_lookup, _dangling, entry, main.signature, body);
};
body = generate.body();
for (_i = 0, _len = calls.length; _i < _len; _i++) {
c = calls[_i];
call(c.node, c.module, c.priority);
}
return [body, calls];
};
})(this);
adopt = function(namespace, code, priority) {
var record;
record = library[namespace];
if (record != null) {
return record.priority = Priority.max(record.priority, priority);
} else {
return library[namespace] = {
code: code,
priority: priority
};
}
};
include = function(node, module, priority) {
var def, key, lib, ns, _ref, _ref1, _ref2, _ref3;
priority = Priority.make(priority);
_ref = module.library;
for (ns in _ref) {
lib = _ref[ns];
adopt(ns, lib.code, Priority.nest(priority, lib.priority));
}
adopt(module.namespace, module.body, priority);
_ref1 = module.uniforms;
for (key in _ref1) {
def = _ref1[key];
uniforms[key] = def;
}
_ref2 = module.varyings;
for (key in _ref2) {
def = _ref2[key];
varyings[key] = def;
}
_ref3 = module.attributes;
for (key in _ref3) {
def = _ref3[key];
attributes[key] = def;
}
return required(node, module);
};
required = function(node, module) {
var copy, ext, k, key, v, _i, _len, _ref, _results;
_ref = module.symbols;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
ext = module.externals[key];
if (isDangling(node, ext.name)) {
copy = {};
for (k in ext) {
v = ext[k];
copy[k] = v;
}
copy.name = lookup(node, ext.name);
externals[key] = copy;
_results.push(symbols.push(key));
} else {
_results.push(void 0);
}
}
return _results;
};
isDangling = function(node, name) {
var outlet;
outlet = node.get(name);
if (outlet.inout === Graph.IN) {
return outlet.input === null;
} else if (outlet.inout === Graph.OUT) {
return outlet.output.length === 0;
}
};
lookup = function(node, name) {
var outlet;
outlet = node.get(name);
if (!outlet) {
return null;
}
if (outlet.input) {
outlet = outlet.input;
}
name = outlet.name;
return outlet.id;
};
return process();
};
module.exports = assemble;
},{"../graph":25,"./priority":33}],30:[function(require,module,exports){
exports.Snippet = require('./snippet');
exports.Program = require('./program');
exports.Layout = require('./layout');
exports.assemble = require('./assemble');
exports.link = require('./link');
exports.priority = require('./priority');
exports.load = exports.Snippet.load;
},{"./assemble":29,"./layout":31,"./link":32,"./priority":33,"./program":34,"./snippet":35}],31:[function(require,module,exports){
var Layout, Snippet, debug, link;
Snippet = require('./snippet');
link = require('./link');
debug = false;
/*
Program linkage layout
Entry points are added to its dependency graph
Callbacks are linked either with a go-between function
or a #define if the signatures are identical.
*/
Layout = (function() {
function Layout(language, graph) {
this.language = language;
this.graph = graph;
this.links = [];
this.includes = [];
this.modules = {};
this.visits = {};
}
Layout.prototype.callback = function(node, module, priority, name, external) {
return this.links.push({
node: node,
module: module,
priority: priority,
name: name,
external: external
});
};
Layout.prototype.include = function(node, module, priority) {
var m;
if ((m = this.modules[module.namespace]) != null) {
return m.priority = Math.max(priority, m.priority);
} else {
this.modules[module.namespace] = true;
return this.includes.push({
node: node,
module: module,
priority: priority
});
}
};
Layout.prototype.visit = function(namespace) {
debug && console.log('Visit', namespace, !this.visits[namespace]);
if (this.visits[namespace]) {
return false;
}
return this.visits[namespace] = true;
};
Layout.prototype.link = function(module) {
var data, key, snippet;
data = link(this.language, this.links, this.includes, module);
snippet = new Snippet;
for (key in data) {
snippet[key] = data[key];
}
snippet.graph = this.graph;
return snippet;
};
return Layout;
})();
module.exports = Layout;
},{"./link":32,"./snippet":35}],32:[function(require,module,exports){
var Graph, Priority, link;
Graph = require('../graph');
Priority = require('./priority');
/*
Callback linker
Imports given modules and generates linkages for registered callbacks.
Builds composite program with single module as exported entry point
*/
link = function(language, links, modules, exported) {
var adopt, attributes, externals, generate, include, includes, isDangling, library, process, symbols, uniforms, varyings;
generate = language.generate;
includes = [];
symbols = [];
externals = {};
uniforms = {};
attributes = {};
varyings = {};
library = {};
process = function() {
var code, e, exports, header, lib, m, ns, sorted, _i, _len;
exports = generate.links(links);
header = [];
if (exports.defs != null) {
header.push(exports.defs);
}
if (exports.bodies != null) {
header.push(exports.bodies);
}
for (_i = 0, _len = modules.length; _i < _len; _i++) {
m = modules[_i];
include(m.node, m.module, m.priority);
}
sorted = ((function() {
var _results;
_results = [];
for (ns in library) {
lib = library[ns];
_results.push(lib);
}
return _results;
})()).sort(function(a, b) {
return Priority.compare(a.priority, b.priority);
});
includes = sorted.map(function(x) {
return x.code;
});
code = generate.lines(includes);
code = generate.defuse(code);
if (header.length) {
code = [generate.lines(header), code].join("\n");
}
code = generate.hoist(code);
code = generate.dedupe(code);
e = exported;
return {
namespace: e.main.name,
code: code,
main: e.main,
entry: e.main.name,
externals: externals,
uniforms: uniforms,
attributes: attributes,
varyings: varyings
};
};
adopt = function(namespace, code, priority) {
var record;
record = library[namespace];
if (record != null) {
return record.priority = Priority.max(record.priority, priority);
} else {
return library[namespace] = {
code: code,
priority: priority
};
}
};
include = function(node, module, priority) {
var def, ext, key, lib, ns, _i, _len, _ref, _ref1, _ref2, _ref3, _ref4, _results;
priority = Priority.make(priority);
_ref = module.library;
for (ns in _ref) {
lib = _ref[ns];
adopt(ns, lib.code, Priority.nest(priority, lib.priority));
}
adopt(module.namespace, module.body, priority);
_ref1 = module.uniforms;
for (key in _ref1) {
def = _ref1[key];
uniforms[key] = def;
}
_ref2 = module.varyings;
for (key in _ref2) {
def = _ref2[key];
varyings[key] = def;
}
_ref3 = module.attributes;
for (key in _ref3) {
def = _ref3[key];
attributes[key] = def;
}
_ref4 = module.symbols;
_results = [];
for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
key = _ref4[_i];
ext = module.externals[key];
if (isDangling(node, ext.name)) {
externals[key] = ext;
_results.push(symbols.push(key));
} else {
_results.push(void 0);
}
}
return _results;
};
isDangling = function(node, name) {
var module, outlet, _ref, _ref1;
outlet = node.get(name);
if (!outlet) {
module = (_ref = (_ref1 = node.owner.snippet) != null ? _ref1._name : void 0) != null ? _ref : node.owner.namespace;
throw new Error("Unable to link program. Unlinked callback `" + name + "` on `" + module + "`");
}
if (outlet.inout === Graph.IN) {
return outlet.input === null;
} else if (outlet.inout === Graph.OUT) {
return outlet.output.length === 0;
}
};
return process();
};
module.exports = link;
},{"../graph":25,"./priority":33}],33:[function(require,module,exports){
exports.make = function(x) {
if (x == null) {
x = [];
}
if (!(x instanceof Array)) {
x = [+x != null ? +x : 0];
}
return x;
};
exports.nest = function(a, b) {
return a.concat(b);
};
exports.compare = function(a, b) {
var i, n, p, q, _i;
n = Math.min(a.length, b.length);
for (i = _i = 0; 0 <= n ? _i < n : _i > n; i = 0 <= n ? ++_i : --_i) {
p = a[i];
q = b[i];
if (p > q) {
return -1;
}
if (p < q) {
return 1;
}
}
a = a.length;
b = b.length;
if (a > b) {
return -1;
} else if (a < b) {
return 1;
} else {
return 0;
}
};
exports.max = function(a, b) {
if (exports.compare(a, b) > 0) {
return b;
} else {
return a;
}
};
},{}],34:[function(require,module,exports){
var Program, Snippet, assemble;
Snippet = require('./snippet');
assemble = require('./assemble');
/*
Program assembly model
Snippets are added to its queue, registering calls and code includes.
Calls are de-duped and scheduled at the earliest point required for correct data flow.
When assemble() is called, it builds a main() function to
execute all calls in final order.
The result is a new instance of Snippet that acts as if it
was parsed from the combined source of the component
nodes.
*/
Program = (function() {
Program.index = 0;
Program.entry = function() {
return "_pg_" + (++Program.index) + "_";
};
function Program(language, namespace, graph) {
this.language = language;
this.namespace = namespace;
this.graph = graph;
this.calls = {};
this.requires = {};
}
Program.prototype.call = function(node, module, priority) {
var exists, ns;
ns = module.namespace;
if (exists = this.calls[ns]) {
exists.priority = Math.max(exists.priority, priority);
} else {
this.calls[ns] = {
node: node,
module: module,
priority: priority
};
}
return this;
};
Program.prototype.require = function(node, module) {
var ns;
ns = module.namespace;
return this.requires[ns] = {
node: node,
module: module
};
};
Program.prototype.assemble = function() {
var data, key, snippet, _ref;
data = assemble(this.language, (_ref = this.namespace) != null ? _ref : Program.entry, this.calls, this.requires);
snippet = new Snippet;
for (key in data) {
snippet[key] = data[key];
}
snippet.graph = this.graph;
return snippet;
};
return Program;
})();
module.exports = Program;
},{"./assemble":29,"./snippet":35}],35:[function(require,module,exports){
var Snippet;
Snippet = (function() {
Snippet.index = 0;
Snippet.namespace = function() {
return "_sn_" + (++Snippet.index) + "_";
};
Snippet.load = function(language, name, code) {
var compiler, program, sigs, _ref;
program = language.parse(name, code);
_ref = language.compile(program), sigs = _ref[0], compiler = _ref[1];
return new Snippet(language, sigs, compiler, name, code);
};
function Snippet(language, _signatures, _compiler, _name, _original) {
var _ref;
this.language = language;
this._signatures = _signatures;
this._compiler = _compiler;
this._name = _name;
this._original = _original;
this.namespace = null;
this.code = null;
this.main = null;
this.entry = null;
this.uniforms = null;
this.externals = null;
this.symbols = null;
this.attributes = null;
this.varyings = null;
if (!this.language) {
delete this.language;
}
if (!this._signatures) {
delete this._signatures;
}
if (!this._compiler) {
delete this._compiler;
}
if (!this._original) {
delete this._original;
}
if (!this._name) {
this._name = (_ref = this._signatures) != null ? _ref.main.name : void 0;
}
}
Snippet.prototype.clone = function() {
return new Snippet(this.language, this._signatures, this._compiler, this._name, this._original);
};
Snippet.prototype.bind = function(config, uniforms, namespace, defines) {
var a, def, defs, e, exceptions, exist, global, k, key, local, name, redef, u, v, x, _a, _e, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _u, _v;
if (uniforms === '' + uniforms) {
_ref = [uniforms, namespace != null ? namespace : {}, defines != null ? defines : {}], namespace = _ref[0], uniforms = _ref[1], defines = _ref[2];
} else if (namespace !== '' + namespace) {
_ref1 = [namespace != null ? namespace : {}, void 0], defines = _ref1[0], namespace = _ref1[1];
}
this.main = this._signatures.main;
this.namespace = (_ref2 = namespace != null ? namespace : this.namespace) != null ? _ref2 : Snippet.namespace();
this.entry = this.namespace + this.main.name;
this.uniforms = {};
this.varyings = {};
this.attributes = {};
this.externals = {};
this.symbols = [];
exist = {};
exceptions = {};
global = function(name) {
exceptions[name] = true;
return name;
};
local = (function(_this) {
return function(name) {
return _this.namespace + name;
};
})(this);
if (config.globals) {
_ref3 = config.globals;
for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
key = _ref3[_i];
global(key);
}
}
_u = config.globalUniforms ? global : local;
_v = config.globalVaryings ? global : local;
_a = config.globalAttributes ? global : local;
_e = local;
x = (function(_this) {
return function(def) {
return exist[def.name] = true;
};
})(this);
u = (function(_this) {
return function(def, name) {
return _this.uniforms[_u(name != null ? name : def.name)] = def;
};
})(this);
v = (function(_this) {
return function(def) {
return _this.varyings[_v(def.name)] = def;
};
})(this);
a = (function(_this) {
return function(def) {
return _this.attributes[_a(def.name)] = def;
};
})(this);
e = (function(_this) {
return function(def) {
var name;
name = _e(def.name);
_this.externals[name] = def;
return _this.symbols.push(name);
};
})(this);
redef = function(def) {
return {
type: def.type,
name: def.name,
value: def.value
};
};
_ref4 = this._signatures.uniform;
for (_j = 0, _len1 = _ref4.length; _j < _len1; _j++) {
def = _ref4[_j];
x(def);
}
_ref5 = this._signatures.uniform;
for (_k = 0, _len2 = _ref5.length; _k < _len2; _k++) {
def = _ref5[_k];
u(redef(def));
}
_ref6 = this._signatures.varying;
for (_l = 0, _len3 = _ref6.length; _l < _len3; _l++) {
def = _ref6[_l];
v(redef(def));
}
_ref7 = this._signatures.external;
for (_m = 0, _len4 = _ref7.length; _m < _len4; _m++) {
def = _ref7[_m];
e(def);
}
_ref8 = this._signatures.attribute;
for (_n = 0, _len5 = _ref8.length; _n < _len5; _n++) {
def = _ref8[_n];
a(redef(def));
}
for (name in uniforms) {
def = uniforms[name];
if (exist[name]) {
u(def, name);
}
}
this.body = this.code = this._compiler(this.namespace, exceptions, defines);
if (defines) {
defs = ((function() {
var _results;
_results = [];
for (k in defines) {
v = defines[k];
_results.push("#define " + k + " " + v);
}
return _results;
})()).join('\n');
if (defs.length) {
this._original = [defs, "//----------------------------------------", this._original].join("\n");
}
}
return null;
};
return Snippet;
})();
module.exports = Snippet;
},{}],36:[function(require,module,exports){
var Graph, markup, merge, resolve, serialize, visualize;
Graph = require('../Graph').Graph;
exports.serialize = serialize = require('./serialize');
exports.markup = markup = require('./markup');
visualize = function(graph) {
var data;
if (!graph) {
return;
}
if (!graph.nodes) {
return graph;
}
data = serialize(graph);
return markup.process(data);
};
resolve = function(arg) {
if (arg == null) {
return arg;
}
if (arg instanceof Array) {
return arg.map(resolve);
}
if ((arg.vertex != null) && (arg.fragment != null)) {
return [resolve(arg.vertex, resolve(arg.fragment))];
}
if (arg._graph != null) {
return arg._graph;
}
if (arg.graph != null) {
return arg.graph;
}
return arg;
};
merge = function(args) {
var arg, out, _i, _len;
out = [];
for (_i = 0, _len = args.length; _i < _len; _i++) {
arg = args[_i];
if (arg instanceof Array) {
out = out.concat(merge(arg));
} else if (arg != null) {
out.push(arg);
}
}
return out;
};
exports.visualize = function() {
var graph, list;
list = merge(resolve([].slice.call(arguments)));
return markup.merge((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = list.length; _i < _len; _i++) {
graph = list[_i];
if (graph) {
_results.push(visualize(graph));
}
}
return _results;
})());
};
exports.inspect = function() {
var contents, el, element, _i, _len, _ref;
contents = exports.visualize.apply(null, arguments);
element = markup.overlay(contents);
_ref = document.querySelectorAll('.shadergraph-overlay');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
el = _ref[_i];
el.remove();
}
document.body.appendChild(element);
contents.update();
return element;
};
},{"../Graph":2,"./markup":37,"./serialize":38}],37:[function(require,module,exports){
var connect, cssColor, escapeText, hash, hashColor, makeSVG, merge, overlay, path, process, sqr, trim, wrap, _activate, _markup, _order;
hash = require('../factory/hash');
trim = function(string) {
return ("" + string).replace(/^\s+|\s+$/g, '');
};
cssColor = function(r, g, b, alpha) {
return 'rgba(' + [r, g, b, alpha].join(', ') + ')';
};
hashColor = function(string, alpha) {
var b, color, g, max, min, norm, r;
if (alpha == null) {
alpha = 1;
}
color = hash(string) ^ 0x123456;
r = color & 0xFF;
g = (color >>> 8) & 0xFF;
b = (color >>> 16) & 0xFF;
max = Math.max(r, g, b);
norm = 140 / max;
min = Math.round(max / 3);
r = Math.min(255, Math.round(norm * Math.max(r, min)));
g = Math.min(255, Math.round(norm * Math.max(g, min)));
b = Math.min(255, Math.round(norm * Math.max(b, min)));
return cssColor(r, g, b, alpha);
};
escapeText = function(string) {
string = string != null ? string : "";
return string.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/"/g, '"');
};
process = function(data) {
var el, links;
links = [];
el = _markup(data, links);
el.update = function() {
return connect(el, links);
};
_activate(el);
return el;
};
_activate = function(el) {
var code, codes, _i, _len, _results;
codes = el.querySelectorAll('.shadergraph-code');
_results = [];
for (_i = 0, _len = codes.length; _i < _len; _i++) {
code = codes[_i];
_results.push((function() {
var popup;
popup = code;
popup.parentNode.classList.add('shadergraph-has-code');
return popup.parentNode.addEventListener('click', function(event) {
return popup.style.display = {
block: 'none',
none: 'block'
}[popup.style.display || 'none'];
});
})());
}
return _results;
};
_order = function(data) {
var link, linkMap, node, nodeMap, recurse, _i, _j, _k, _len, _len1, _len2, _name, _ref, _ref1, _ref2;
nodeMap = {};
linkMap = {};
_ref = data.nodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
nodeMap[node.id] = node;
}
_ref1 = data.links;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
link = _ref1[_j];
if (linkMap[_name = link.from] == null) {
linkMap[_name] = [];
}
linkMap[link.from].push(link);
}
recurse = function(node, depth) {
var next, _k, _len2, _ref2;
if (depth == null) {
depth = 0;
}
node.depth = Math.max((_ref2 = node.depth) != null ? _ref2 : 0, depth);
if (next = linkMap[node.id]) {
for (_k = 0, _len2 = next.length; _k < _len2; _k++) {
link = next[_k];
recurse(nodeMap[link.to], depth + 1);
}
}
return null;
};
_ref2 = data.nodes;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
node = _ref2[_k];
if (node.depth == null) {
recurse(node);
}
}
return null;
};
_markup = function(data, links) {
var addOutlet, block, clear, color, column, columns, div, link, node, outlet, outlets, wrapper, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref, _ref1, _ref2, _ref3;
_order(data);
wrapper = document.createElement('div');
wrapper.classList.add('shadergraph-graph');
columns = [];
outlets = {};
_ref = data.nodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
block = document.createElement('div');
block.classList.add("shadergraph-node");
block.classList.add("shadergraph-node-" + node.type);
block.innerHTML = "<div class=\"shadergraph-header\">" + (escapeText(node.name)) + "</div>";
addOutlet = function(outlet, inout) {
var color, div;
color = hashColor(outlet.type);
div = document.createElement('div');
div.classList.add('shadergraph-outlet');
div.classList.add("shadergraph-outlet-" + inout);
div.innerHTML = "<div class=\"shadergraph-point\" style=\"background: " + color + "\"></div>\n<div class=\"shadergraph-type\" style=\"color: " + color + "\">" + (escapeText(outlet.type)) + "</div>\n<div class=\"shadergraph-name\">" + (escapeText(outlet.name)) + "</div>";
block.appendChild(div);
return outlets[outlet.id] = div.querySelector('.shadergraph-point');
};
_ref1 = node.inputs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
addOutlet(outlet, 'in');
}
_ref2 = node.outputs;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
outlet = _ref2[_k];
addOutlet(outlet, 'out');
}
if (node.graph != null) {
block.appendChild(_markup(node.graph, links));
} else {
clear = document.createElement('div');
clear.classList.add('shadergraph-clear');
block.appendChild(clear);
}
if (node.code != null) {
div = document.createElement('div');
div.classList.add('shadergraph-code');
div.innerHTML = escapeText(trim(node.code));
block.appendChild(div);
}
column = columns[node.depth];
if (column == null) {
column = document.createElement('div');
column.classList.add('shadergraph-column');
columns[node.depth] = column;
}
column.appendChild(block);
}
for (_l = 0, _len3 = columns.length; _l < _len3; _l++) {
column = columns[_l];
if (column != null) {
wrapper.appendChild(column);
}
}
_ref3 = data.links;
for (_m = 0, _len4 = _ref3.length; _m < _len4; _m++) {
link = _ref3[_m];
color = hashColor(link.type);
links.push({
color: color,
out: outlets[link.out],
"in": outlets[link["in"]]
});
}
return wrapper;
};
sqr = function(x) {
return x * x;
};
path = function(x1, y1, x2, y2) {
var d, dx, dy, f, h, mx, my, vert;
dx = x2 - x1;
dy = y2 - y1;
d = Math.sqrt(sqr(dx) + sqr(dy));
vert = Math.abs(dy) > Math.abs(dx);
if (vert) {
mx = (x1 + x2) / 2;
my = (y1 + y2) / 2;
f = dy > 0 ? .3 : -.3;
h = Math.min(Math.abs(dx) / 2, 20 + d / 8);
return ['M', x1, y1, 'C', x1 + h, y1 + ',', mx, my - d * f, mx, my, 'C', mx, my + d * f, x2 - h, y2 + ',', x2, y2].join(' ');
} else {
h = Math.min(Math.abs(dx) / 2.5, 20 + d / 4);
return ['M', x1, y1, 'C', x1 + h, y1 + ',', x2 - h, y2 + ',', x2, y2].join(' ');
}
};
makeSVG = function(tag) {
if (tag == null) {
tag = 'svg';
}
return document.createElementNS('http://www.w3.org/2000/svg', tag);
};
connect = function(element, links) {
var a, b, box, c, line, link, ref, svg, _i, _j, _len, _len1;
if (element.parentNode == null) {
return;
}
ref = element.getBoundingClientRect();
for (_i = 0, _len = links.length; _i < _len; _i++) {
link = links[_i];
a = link.out.getBoundingClientRect();
b = link["in"].getBoundingClientRect();
link.coords = {
x1: (a.left + a.right) / 2 - ref.left,
y1: (a.top + a.bottom) / 2 - ref.top,
x2: (b.left + b.right) / 2 - ref.left,
y2: (b.top + b.bottom) / 2 - ref.top
};
}
svg = element.querySelector('svg');
if (svg != null) {
element.removeChild(svg);
}
box = element;
while (box.parentNode && box.offsetHeight === 0) {
box = box.parentNode;
}
svg = makeSVG();
svg.setAttribute('width', box.offsetWidth);
svg.setAttribute('height', box.offsetHeight);
for (_j = 0, _len1 = links.length; _j < _len1; _j++) {
link = links[_j];
c = link.coords;
line = makeSVG('path');
line.setAttribute('d', path(c.x1, c.y1, c.x2, c.y2));
line.setAttribute('stroke', link.color);
line.setAttribute('stroke-width', 3);
line.setAttribute('fill', 'transparent');
svg.appendChild(line);
}
return element.appendChild(svg);
};
overlay = function(contents) {
var close, div, inside, view;
div = document.createElement('div');
div.setAttribute('class', 'shadergraph-overlay');
close = document.createElement('div');
close.setAttribute('class', 'shadergraph-close');
close.innerHTML = '×';
view = document.createElement('div');
view.setAttribute('class', 'shadergraph-view');
inside = document.createElement('div');
inside.setAttribute('class', 'shadergraph-inside');
inside.appendChild(contents);
view.appendChild(inside);
div.appendChild(view);
div.appendChild(close);
close.addEventListener('click', function() {
return div.parentNode.removeChild(div);
});
return div;
};
wrap = function(markup) {
var p;
if (markup instanceof Node) {
return markup;
}
p = document.createElement('span');
p.innerText = markup != null ? markup : '';
return p;
};
merge = function(markup) {
var div, el, _i, _len;
if (markup.length !== 1) {
div = document.createElement('div');
for (_i = 0, _len = markup.length; _i < _len; _i++) {
el = markup[_i];
div.appendChild(wrap(el));
}
div.update = function() {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = markup.length; _j < _len1; _j++) {
el = markup[_j];
_results.push(typeof el.update === "function" ? el.update() : void 0);
}
return _results;
};
return div;
} else {
return wrap(markup[0]);
}
};
module.exports = {
process: process,
merge: merge,
overlay: overlay
};
},{"../factory/hash":13}],38:[function(require,module,exports){
var Block, isCallback, serialize;
Block = require('../block');
isCallback = function(outlet) {
return outlet.type[0] === '(';
};
serialize = function(graph) {
var block, format, inputs, links, node, nodes, other, outlet, outputs, record, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3;
nodes = [];
links = [];
_ref = graph.nodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
record = {
id: node.id,
name: null,
type: null,
depth: null,
graph: null,
inputs: [],
outputs: []
};
nodes.push(record);
inputs = record.inputs;
outputs = record.outputs;
block = node.owner;
if (block instanceof Block.Call) {
record.name = block.snippet._name;
record.type = 'call';
record.code = block.snippet._original;
} else if (block instanceof Block.Callback) {
record.name = "Callback";
record.type = 'callback';
record.graph = serialize(block.graph);
} else if (block instanceof Block.Isolate) {
record.name = 'Isolate';
record.type = 'isolate';
record.graph = serialize(block.graph);
} else if (block instanceof Block.Join) {
record.name = 'Join';
record.type = 'join';
}
format = function(type) {
type = type.replace(")(", ")→(");
return type = type.replace("()", "");
};
_ref1 = node.inputs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
outlet = _ref1[_j];
inputs.push({
id: outlet.id,
name: outlet.name,
type: format(outlet.type),
open: outlet.input == null
});
}
_ref2 = node.outputs;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
outlet = _ref2[_k];
outputs.push({
id: outlet.id,
name: outlet.name,
type: format(outlet.type),
open: !outlet.output.length
});
_ref3 = outlet.output;
for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
other = _ref3[_l];
links.push({
from: node.id,
out: outlet.id,
to: other.node.id,
"in": other.id,
type: format(outlet.type)
});
}
}
}
return {
nodes: nodes,
links: links
};
};
module.exports = serialize;
},{"../block":8}],39:[function(require,module,exports){
module.exports = require('./lib/index')
},{"./lib/index":41}],40:[function(require,module,exports){
var state
, token
, tokens
, idx
var original_symbol = {
nud: function() { return this.children && this.children.length ? this : fail('unexpected')() }
, led: fail('missing operator')
}
var symbol_table = {}
function itself() {
return this
}
symbol('(ident)').nud = itself
symbol('(keyword)').nud = itself
symbol('(builtin)').nud = itself
symbol('(literal)').nud = itself
symbol('(end)')
symbol(':')
symbol(';')
symbol(',')
symbol(')')
symbol(']')
symbol('}')
infixr('&&', 30)
infixr('||', 30)
infix('|', 43)
infix('^', 44)
infix('&', 45)
infix('==', 46)
infix('!=', 46)
infix('<', 47)
infix('<=', 47)
infix('>', 47)
infix('>=', 47)
infix('>>', 48)
infix('<<', 48)
infix('+', 50)
infix('-', 50)
infix('*', 60)
infix('/', 60)
infix('%', 60)
infix('?', 20, function(left) {
this.children = [left, expression(0), (advance(':'), expression(0))]
this.type = 'ternary'
return this
})
infix('.', 80, function(left) {
token.type = 'literal'
state.fake(token)
this.children = [left, token]
advance()
return this
})
infix('[', 80, function(left) {
this.children = [left, expression(0)]
this.type = 'binary'
advance(']')
return this
})
infix('(', 80, function(left) {
this.children = [left]
this.type = 'call'
if(token.data !== ')') while(1) {
this.children.push(expression(0))
if(token.data !== ',') break
advance(',')
}
advance(')')
return this
})
prefix('-')
prefix('+')
prefix('!')
prefix('~')
prefix('defined')
prefix('(', function() {
this.type = 'group'
this.children = [expression(0)]
advance(')')
return this
})
prefix('++')
prefix('--')
suffix('++')
suffix('--')
assignment('=')
assignment('+=')
assignment('-=')
assignment('*=')
assignment('/=')
assignment('%=')
assignment('&=')
assignment('|=')
assignment('^=')
assignment('>>=')
assignment('<<=')
module.exports = function(incoming_state, incoming_tokens) {
state = incoming_state
tokens = incoming_tokens
idx = 0
var result
if(!tokens.length) return
advance()
result = expression(0)
result.parent = state[0]
emit(result)
if(idx < tokens.length) {
throw new Error('did not use all tokens')
}
result.parent.children = [result]
function emit(node) {
state.unshift(node, false)
for(var i = 0, len = node.children.length; i < len; ++i) {
emit(node.children[i])
}
state.shift()
}
}
function symbol(id, binding_power) {
var sym = symbol_table[id]
binding_power = binding_power || 0
if(sym) {
if(binding_power > sym.lbp) {
sym.lbp = binding_power
}
} else {
sym = Object.create(original_symbol)
sym.id = id
sym.lbp = binding_power
symbol_table[id] = sym
}
return sym
}
function expression(rbp) {
var left, t = token
advance()
left = t.nud()
while(rbp < token.lbp) {
t = token
advance()
left = t.led(left)
}
return left
}
function infix(id, bp, led) {
var sym = symbol(id, bp)
sym.led = led || function(left) {
this.children = [left, expression(bp)]
this.type = 'binary'
return this
}
}
function infixr(id, bp, led) {
var sym = symbol(id, bp)
sym.led = led || function(left) {
this.children = [left, expression(bp - 1)]
this.type = 'binary'
return this
}
return sym
}
function prefix(id, nud) {
var sym = symbol(id)
sym.nud = nud || function() {
this.children = [expression(70)]
this.type = 'unary'
return this
}
return sym
}
function suffix(id) {
var sym = symbol(id, 150)
sym.led = function(left) {
this.children = [left]
this.type = 'suffix'
return this
}
}
function assignment(id) {
return infixr(id, 10, function(left) {
this.children = [left, expression(9)]
this.assignment = true
this.type = 'assign'
return this
})
}
function advance(id) {
var next
, value
, type
, output
if(id && token.data !== id) {
return state.unexpected('expected `'+ id + '`, got `'+token.data+'`')
}
if(idx >= tokens.length) {
token = symbol_table['(end)']
return
}
next = tokens[idx++]
value = next.data
type = next.type
if(type === 'ident') {
output = state.scope.find(value) || state.create_node()
type = output.type
} else if(type === 'builtin') {
output = symbol_table['(builtin)']
} else if(type === 'keyword') {
output = symbol_table['(keyword)']
} else if(type === 'operator') {
output = symbol_table[value]
if(!output) {
return state.unexpected('unknown operator `'+value+'`')
}
} else if(type === 'float' || type === 'integer') {
type = 'literal'
output = symbol_table['(literal)']
} else {
return state.unexpected('unexpected token.')
}
if(output) {
if(!output.nud) { output.nud = itself }
if(!output.children) { output.children = [] }
}
output = Object.create(output)
output.token = next
output.type = type
if(!output.data) output.data = value
return token = output
}
function fail(message) {
return function() { return state.unexpected(message) }
}
},{}],41:[function(require,module,exports){
module.exports = parser
var through = require('../../through')
, full_parse_expr = require('./expr')
, Scope = require('./scope')
// singleton!
var Advance = new Object
var DEBUG = false
var _ = 0
, IDENT = _++
, STMT = _++
, STMTLIST = _++
, STRUCT = _++
, FUNCTION = _++
, FUNCTIONARGS = _++
, DECL = _++
, DECLLIST = _++
, FORLOOP = _++
, WHILELOOP = _++
, IF = _++
, EXPR = _++
, PRECISION = _++
, COMMENT = _++
, PREPROCESSOR = _++
, KEYWORD = _++
, KEYWORD_OR_IDENT = _++
, RETURN = _++
, BREAK = _++
, CONTINUE = _++
, DISCARD = _++
, DOWHILELOOP = _++
, PLACEHOLDER = _++
, QUANTIFIER = _++
var DECL_ALLOW_ASSIGN = 0x1
, DECL_ALLOW_COMMA = 0x2
, DECL_REQUIRE_NAME = 0x4
, DECL_ALLOW_INVARIANT = 0x8
, DECL_ALLOW_STORAGE = 0x10
, DECL_NO_INOUT = 0x20
, DECL_ALLOW_STRUCT = 0x40
, DECL_STATEMENT = 0xFF
, DECL_FUNCTION = DECL_STATEMENT & ~(DECL_ALLOW_ASSIGN | DECL_ALLOW_COMMA | DECL_NO_INOUT | DECL_ALLOW_INVARIANT | DECL_REQUIRE_NAME)
, DECL_STRUCT = DECL_STATEMENT & ~(DECL_ALLOW_ASSIGN | DECL_ALLOW_INVARIANT | DECL_ALLOW_STORAGE | DECL_ALLOW_STRUCT)
var QUALIFIERS = ['const', 'attribute', 'uniform', 'varying']
var NO_ASSIGN_ALLOWED = false
, NO_COMMA_ALLOWED = false
// map of tokens to stmt types
var token_map = {
'block-comment': COMMENT
, 'line-comment': COMMENT
, 'preprocessor': PREPROCESSOR
}
// map of stmt types to human
var stmt_type = _ = [
'ident'
, 'stmt'
, 'stmtlist'
, 'struct'
, 'function'
, 'functionargs'
, 'decl'
, 'decllist'
, 'forloop'
, 'whileloop'
, 'i'+'f'
, 'expr'
, 'precision'
, 'comment'
, 'preprocessor'
, 'keyword'
, 'keyword_or_ident'
, 'return'
, 'break'
, 'continue'
, 'discard'
, 'do-while'
, 'placeholder'
, 'quantifier'
]
function parser() {
var stmtlist = n(STMTLIST)
, stmt = n(STMT)
, decllist = n(DECLLIST)
, precision = n(PRECISION)
, ident = n(IDENT)
, keyword_or_ident = n(KEYWORD_OR_IDENT)
, fn = n(FUNCTION)
, fnargs = n(FUNCTIONARGS)
, forstmt = n(FORLOOP)
, ifstmt = n(IF)
, whilestmt = n(WHILELOOP)
, returnstmt = n(RETURN)
, dowhilestmt = n(DOWHILELOOP)
, quantifier = n(QUANTIFIER)
var parse_struct
, parse_precision
, parse_quantifier
, parse_forloop
, parse_if
, parse_return
, parse_whileloop
, parse_dowhileloop
, parse_function
, parse_function_args
var stream = through(write, end)
, check = arguments.length ? [].slice.call(arguments) : []
, depth = 0
, state = []
, tokens = []
, whitespace = []
, errored = false
, program
, token
, node
// setup state
state.shift = special_shift
state.unshift = special_unshift
state.fake = special_fake
state.unexpected = unexpected
state.scope = new Scope(state)
state.create_node = function() {
var n = mknode(IDENT, token)
n.parent = stream.program
return n
}
setup_stative_parsers()
// setup root node
node = stmtlist()
node.expecting = '(eof)'
node.mode = STMTLIST
node.token = {type: '(program)', data: '(program)'}
program = node
stream.program = program
stream.scope = function(scope) {
if(arguments.length === 1) {
state.scope = scope
}
return state.scope
}
state.unshift(node)
return stream
// stream functions ---------------------------------------------
function write(input) {
if(input.type === 'whitespace' || input.type === 'line-comment' || input.type === 'block-comment') {
whitespace.push(input)
return
}
tokens.push(input)
token = token || tokens[0]
if(token && whitespace.length) {
token.preceding = token.preceding || []
token.preceding = token.preceding.concat(whitespace)
whitespace = []
}
while(take()) switch(state[0].mode) {
case STMT: parse_stmt(); break
case STMTLIST: parse_stmtlist(); break
case DECL: parse_decl(); break
case DECLLIST: parse_decllist(); break
case EXPR: parse_expr(); break
case STRUCT: parse_struct(true, true); break
case PRECISION: parse_precision(); break
case IDENT: parse_ident(); break
case KEYWORD: parse_keyword(); break
case KEYWORD_OR_IDENT: parse_keyword_or_ident(); break
case FUNCTION: parse_function(); break
case FUNCTIONARGS: parse_function_args(); break
case FORLOOP: parse_forloop(); break
case WHILELOOP: parse_whileloop(); break
case DOWHILELOOP: parse_dowhileloop(); break
case RETURN: parse_return(); break
case IF: parse_if(); break
case QUANTIFIER: parse_quantifier(); break
}
}
function end(tokens) {
if(arguments.length) {
write(tokens)
}
if(state.length > 1) {
unexpected('unexpected EOF')
return
}
stream.emit('end')
}
function take() {
if(errored || !state.length)
return false
return (token = tokens[0]) && !stream.paused
}
// ----- state manipulation --------
function special_fake(x) {
state.unshift(x)
state.shift()
}
function special_unshift(_node, add_child) {
_node.parent = state[0]
var ret = [].unshift.call(this, _node)
add_child = add_child === undefined ? true : add_child
if(DEBUG) {
var pad = ''
for(var i = 0, len = this.length - 1; i < len; ++i) {
pad += ' |'
}
console.log(pad, '\\'+_node.type, _node.token.data)
}
if(add_child && node !== _node) node.children.push(_node)
node = _node
return ret
}
function special_shift() {
var _node = [].shift.call(this)
, okay = check[this.length]
, emit = false
if(DEBUG) {
var pad = ''
for(var i = 0, len = this.length; i < len; ++i) {
pad += ' |'
}
console.log(pad, '/'+_node.type)
}
if(check.length) {
if(typeof check[0] === 'function') {
emit = check[0](_node)
} else if(okay !== undefined) {
emit = okay.test ? okay.test(_node.type) : okay === _node.type
}
} else {
emit = true
}
if(emit) stream.emit('data', _node)
node = _node.parent
return _node
}
// parse states ---------------
function parse_stmtlist() {
// determine the type of the statement
// and then start parsing
return stative(
function() { state.scope.enter(); return Advance }
, normal_mode
)()
function normal_mode() {
if(token.data === state[0].expecting) {
return state.scope.exit(), state.shift()
}
switch(token.type) {
case 'preprocessor':
state.fake(adhoc())
tokens.shift()
return
default:
state.unshift(stmt())
return
}
}
}
function parse_stmt() {
if(state[0].brace) {
if(token.data !== '}') {
return unexpected('expected `}`, got '+token.data)
}
state[0].brace = false
return tokens.shift(), state.shift()
}
switch(token.type) {
case 'eof': return state.shift()
case 'keyword':
switch(token.data) {
case 'for': return state.unshift(forstmt());
case 'if': return state.unshift(ifstmt());
case 'while': return state.unshift(whilestmt());
case 'do': return state.unshift(dowhilestmt());
case 'break': return state.fake(mknode(BREAK, token)), tokens.shift()
case 'continue': return state.fake(mknode(CONTINUE, token)), tokens.shift()
case 'discard': return state.fake(mknode(DISCARD, token)), tokens.shift()
case 'return': return state.unshift(returnstmt());
case 'precision': return state.unshift(precision());
}
return state.unshift(decl(DECL_STATEMENT))
case 'ident':
var lookup
if(lookup = state.scope.find(token.data)) {
if(lookup.parent.type === 'struct') {
// this is strictly untrue, you could have an
// expr that starts with a struct constructor.
// ... sigh
return state.unshift(decl(DECL_STATEMENT))
}
return state.unshift(expr(';'))
}
case 'operator':
if(token.data === '{') {
state[0].brace = true
var n = stmtlist()
n.expecting = '}'
return tokens.shift(), state.unshift(n)
}
if(token.data === ';') {
return tokens.shift(), state.shift()
}
default: return state.unshift(expr(';'))
}
}
function parse_decl() {
var stmt = state[0]
return stative(
invariant_or_not,
storage_or_not,
parameter_or_not,
precision_or_not,
struct_or_type,
maybe_name,
maybe_lparen, // lparen means we're a function
is_decllist,
done
)()
function invariant_or_not() {
if(token.data === 'invariant') {
if(stmt.flags & DECL_ALLOW_INVARIANT) {
state.unshift(keyword())
return Advance
} else {
return unexpected('`invariant` is not allowed here')
}
} else {
state.fake(mknode(PLACEHOLDER, {data: '', position: token.position}))
return Advance
}
}
function storage_or_not() {
if(is_storage(token)) {
if(stmt.flags & DECL_ALLOW_STORAGE) {
state.unshift(keyword())
return Advance
} else {
return unexpected('storage is not allowed here')
}
} else {
state.fake(mknode(PLACEHOLDER, {data: '', position: token.position}))
return Advance
}
}
function parameter_or_not() {
if(is_parameter(token)) {
if(!(stmt.flags & DECL_NO_INOUT)) {
state.unshift(keyword())
return Advance
} else {
return unexpected('parameter is not allowed here')
}
} else {
state.fake(mknode(PLACEHOLDER, {data: '', position: token.position}))
return Advance
}
}
function precision_or_not() {
if(is_precision(token)) {
state.unshift(keyword())
return Advance
} else {
state.fake(mknode(PLACEHOLDER, {data: '', position: token.position}))
return Advance
}
}
function struct_or_type() {
if(token.data === 'struct') {
if(!(stmt.flags & DECL_ALLOW_STRUCT)) {
return unexpected('cannot nest structs')
}
state.unshift(struct())
return Advance
}
if(token.type === 'keyword') {
state.unshift(keyword())
return Advance
}
var lookup = state.scope.find(token.data)
if(lookup) {
state.fake(Object.create(lookup))
tokens.shift()
return Advance
}
return unexpected('expected user defined type, struct or keyword, got '+token.data)
}
function maybe_name() {
if(token.data === ',' && !(stmt.flags & DECL_ALLOW_COMMA)) {
return state.shift()
}
if(token.data === '[') {
// oh lord.
state.unshift(quantifier())
return
}
if(token.data === ')') return state.shift()
if(token.data === ';') {
return stmt.stage + 3
}
if(token.type !== 'ident') {
console.log(token);
return unexpected('expected identifier, got '+token.data)
}
stmt.collected_name = tokens.shift()
return Advance
}
function maybe_lparen() {
if(token.data === '(') {
tokens.unshift(stmt.collected_name)
delete stmt.collected_name
state.unshift(fn())
return stmt.stage + 2
}
return Advance
}
function is_decllist() {
tokens.unshift(stmt.collected_name)
delete stmt.collected_name
state.unshift(decllist())
return Advance
}
function done() {
return state.shift()
}
}
function parse_decllist() {
// grab ident
if(token.type === 'ident') {
var name = token.data
state.unshift(ident())
state.scope.define(name)
return
}
if(token.type === 'operator') {
if(token.data === ',') {
// multi-decl!
if(!(state[1].flags & DECL_ALLOW_COMMA)) {
return state.shift()
}
return tokens.shift()
} else if(token.data === '=') {
if(!(state[1].flags & DECL_ALLOW_ASSIGN)) return unexpected('`=` is not allowed here.')
tokens.shift()
state.unshift(expr(',', ';'))
return
} else if(token.data === '[') {
state.unshift(quantifier())
return
}
}
return state.shift()
}
function parse_keyword_or_ident() {
if(token.type === 'keyword') {
state[0].type = 'keyword'
state[0].mode = KEYWORD
return
}
if(token.type === 'ident') {
state[0].type = 'ident'
state[0].mode = IDENT
return
}
return unexpected('expected keyword or user-defined name, got '+token.data)
}
function parse_keyword() {
if(token.type !== 'keyword') {
return unexpected('expected keyword, got '+token.data)
}
return state.shift(), tokens.shift()
}
function parse_ident() {
if(token.type !== 'ident') {
return unexpected('expected user-defined name, got '+token.data)
}
state[0].data = token.data
return state.shift(), tokens.shift()
}
function parse_expr() {
var expecting = state[0].expecting
state[0].tokens = state[0].tokens || []
if(state[0].parenlevel === undefined) {
state[0].parenlevel = 0
state[0].bracelevel = 0
}
if(state[0].parenlevel < 1 && expecting.indexOf(token.data) > -1) {
return parseexpr(state[0].tokens)
}
if(token.data === '(') {
++state[0].parenlevel
} else if(token.data === ')') {
--state[0].parenlevel
}
switch(token.data) {
case '{': ++state[0].bracelevel; break
case '}': --state[0].bracelevel; break
case '(': ++state[0].parenlevel; break
case ')': --state[0].parenlevel; break
}
if(state[0].parenlevel < 0) return unexpected('unexpected `)`')
if(state[0].bracelevel < 0) return unexpected('unexpected `}`')
state[0].tokens.push(tokens.shift())
return
function parseexpr(tokens) {
return full_parse_expr(state, tokens), state.shift()
}
}
// node types ---------------
function n(type) {
// this is a function factory that suffices for most kinds of expressions and statements
return function() {
return mknode(type, token)
}
}
function adhoc() {
return mknode(token_map[token.type], token, node)
}
function decl(flags) {
var _ = mknode(DECL, token, node)
_.flags = flags
return _
}
function struct(allow_assign, allow_comma) {
var _ = mknode(STRUCT, token, node)
_.allow_assign = allow_assign === undefined ? true : allow_assign
_.allow_comma = allow_comma === undefined ? true : allow_comma
return _
}
function expr() {
var n = mknode(EXPR, token, node)
n.expecting = [].slice.call(arguments)
return n
}
function keyword(default_value) {
var t = token
if(default_value) {
t = {'type': '(implied)', data: '(default)', position: t.position}
}
return mknode(KEYWORD, t, node)
}
// utils ----------------------------
function unexpected(str) {
errored = true
stream.emit('error', new Error(
(str || 'unexpected '+state) +
' at line '+state[0].token.line
))
}
function assert(type, data) {
return 1,
assert_null_string_or_array(type, token.type) &&
assert_null_string_or_array(data, token.data)
}
function assert_null_string_or_array(x, y) {
switch(typeof x) {
case 'string': if(y !== x) {
unexpected('expected `'+x+'`, got '+y+'\n'+token.data);
} return !errored
case 'object': if(x && x.indexOf(y) === -1) {
unexpected('expected one of `'+x.join('`, `')+'`, got '+y);
} return !errored
}
return true
}
// stative ----------------------------
function stative() {
var steps = [].slice.call(arguments)
, step
, result
return function() {
var current = state[0]
current.stage || (current.stage = 0)
step = steps[current.stage]
if(!step) return unexpected('parser in undefined state!')
result = step()
if(result === Advance) return ++current.stage
if(result === undefined) return
current.stage = result
}
}
function advance(op, t) {
t = t || 'operator'
return function() {
if(!assert(t, op)) return
var last = tokens.shift()
, children = state[0].children
, last_node = children[children.length - 1]
if(last_node && last_node.token && last.preceding) {
last_node.token.succeeding = last_node.token.succeeding || []
last_node.token.succeeding = last_node.token.succeeding.concat(last.preceding)
}
return Advance
}
}
function advance_expr(until) {
return function() { return state.unshift(expr(until)), Advance }
}
function advance_ident(declare) {
return declare ? function() {
var name = token.data
return assert('ident') && (state.unshift(ident()), state.scope.define(name), Advance)
} : function() {
if(!assert('ident')) return
var s = Object.create(state.scope.find(token.data))
s.token = token
return (tokens.shift(), Advance)
}
}
function advance_stmtlist() {
return function() {
var n = stmtlist()
n.expecting = '}'
return state.unshift(n), Advance
}
}
function maybe_stmtlist(skip) {
return function() {
var current = state[0].stage
if(token.data !== '{') { return state.unshift(stmt()), current + skip }
return tokens.shift(), Advance
}
}
function popstmt() {
return function() { return state.shift(), state.shift() }
}
function setup_stative_parsers() {
// could also be
// struct { } decllist
parse_struct =
stative(
advance('struct', 'keyword')
, function() {
if(token.data === '{') {
state.fake(mknode(IDENT, {data:'', position: token.position, type:'ident'}))
return Advance
}
return advance_ident(true)()
}
, function() { state.scope.enter(); return Advance }
, advance('{')
, function() {
if(token.data === '}') {
state.scope.exit()
tokens.shift()
return state.shift()
}
if(token.data === ';') { tokens.shift(); return }
state.unshift(decl(DECL_STRUCT))
}
)
parse_precision =
stative(
function() { return tokens.shift(), Advance }
, function() {
return assert(
'keyword', ['lowp', 'mediump', 'highp']
) && (state.unshift(keyword()), Advance)
}
, function() { return (state.unshift(keyword()), Advance) }
, function() { return state.shift() }
)
parse_quantifier =
stative(
advance('[')
, advance_expr(']')
, advance(']')
, function() { return state.shift() }
)
parse_forloop =
stative(
advance('for', 'keyword')
, advance('(')
, function() {
var lookup
if(token.type === 'ident') {
if(!(lookup = state.scope.find(token.data))) {
lookup = state.create_node()
}
if(lookup.parent.type === 'struct') {
return state.unshift(decl(DECL_STATEMENT)), Advance
}
} else if(token.type === 'builtin' || token.type === 'keyword') {
return state.unshift(decl(DECL_STATEMENT)), Advance
}
return advance_expr(';')()
}
, advance(';')
, advance_expr(';')
, advance(';')
, advance_expr(')')
, advance(')')
, maybe_stmtlist(3)
, advance_stmtlist()
, advance('}')
, popstmt()
)
parse_if =
stative(
advance('if', 'keyword')
, advance('(')
, advance_expr(')')
, advance(')')
, maybe_stmtlist(3)
, advance_stmtlist()
, advance('}')
, function() {
if(token.data === 'else') {
return tokens.shift(), state.unshift(stmt()), Advance
}
return popstmt()()
}
, popstmt()
)
parse_return =
stative(
advance('return', 'keyword')
, function() {
if(token.data === ';') return Advance
return state.unshift(expr(';')), Advance
}
, function() { tokens.shift(), popstmt()() }
)
parse_whileloop =
stative(
advance('while', 'keyword')
, advance('(')
, advance_expr(')')
, advance(')')
, maybe_stmtlist(3)
, advance_stmtlist()
, advance('}')
, popstmt()
)
parse_dowhileloop =
stative(
advance('do', 'keyword')
, maybe_stmtlist(3)
, advance_stmtlist()
, advance('}')
, advance('while', 'keyword')
, advance('(')
, advance_expr(')')
, advance(')')
, popstmt()
)
parse_function =
stative(
function() {
for(var i = 1, len = state.length; i < len; ++i) if(state[i].mode === FUNCTION) {
return unexpected('function definition is not allowed within another function')
}
return Advance
}
, function() {
if(!assert("ident")) return
var name = token.data
, lookup = state.scope.find(name)
state.unshift(ident())
state.scope.define(name)
state.scope.enter(lookup ? lookup.scope : null)
return Advance
}
, advance('(')
, function() { return state.unshift(fnargs()), Advance }
, advance(')')
, function() {
// forward decl
if(token.data === ';') {
return state.scope.exit(), state.shift(), state.shift()
}
return Advance
}
, advance('{')
, advance_stmtlist()
, advance('}')
, function() { state.scope.exit(); return Advance }
, function() { return state.shift(), state.shift(), state.shift() }
)
parse_function_args =
stative(
function() {
if(token.data === 'void') { state.fake(keyword()); tokens.shift(); return Advance }
if(token.data === ')') { state.shift(); return }
if(token.data === 'struct') {
state.unshift(struct(NO_ASSIGN_ALLOWED, NO_COMMA_ALLOWED))
return Advance
}
state.unshift(decl(DECL_FUNCTION))
return Advance
}
, function() {
if(token.data === ',') { tokens.shift(); return 0 }
if(token.data === ')') { state.shift(); return }
unexpected('expected one of `,` or `)`, got '+token.data)
}
)
}
}
function mknode(mode, sourcetoken) {
return {
mode: mode
, token: sourcetoken
, children: []
, type: stmt_type[mode]
// , id: (Math.random() * 0xFFFFFFFF).toString(16)
}
}
function is_storage(token) {
return token.data === 'const' ||
token.data === 'attribute' ||
token.data === 'uniform' ||
token.data === 'varying'
}
function is_parameter(token) {
return token.data === 'in' ||
token.data === 'inout' ||
token.data === 'out'
}
function is_precision(token) {
return token.data === 'highp' ||
token.data === 'mediump' ||
token.data === 'lowp'
}
},{"../../through":47,"./expr":40,"./scope":42}],42:[function(require,module,exports){
module.exports = scope
function scope(state) {
if(this.constructor !== scope)
return new scope(state)
this.state = state
this.scopes = []
this.current = null
}
var cons = scope
, proto = cons.prototype
proto.enter = function(s) {
this.scopes.push(
this.current = this.state[0].scope = s || {}
)
}
proto.exit = function() {
this.scopes.pop()
this.current = this.scopes[this.scopes.length - 1]
}
proto.define = function(str) {
this.current[str] = this.state[0]
}
proto.find = function(name, fail) {
for(var i = this.scopes.length - 1; i > -1; --i) {
if(this.scopes[i].hasOwnProperty(name)) {
return this.scopes[i][name]
}
}
return null
}
},{}],43:[function(require,module,exports){
module.exports = tokenize
var through = require('../through')
var literals = require('./lib/literals')
, operators = require('./lib/operators')
, builtins = require('./lib/builtins')
var NORMAL = 999 // <-- never emitted
, TOKEN = 9999 // <-- never emitted
, BLOCK_COMMENT = 0
, LINE_COMMENT = 1
, PREPROCESSOR = 2
, OPERATOR = 3
, INTEGER = 4
, FLOAT = 5
, IDENT = 6
, BUILTIN = 7
, KEYWORD = 8
, WHITESPACE = 9
, EOF = 10
, HEX = 11
var map = [
'block-comment'
, 'line-comment'
, 'preprocessor'
, 'operator'
, 'integer'
, 'float'
, 'ident'
, 'builtin'
, 'keyword'
, 'whitespace'
, 'eof'
, 'integer'
]
function tokenize() {
var stream = through(write, end)
var i = 0
, total = 0
, mode = NORMAL
, c
, last
, content = []
, token_idx = 0
, token_offs = 0
, line = 1
, start = 0
, isnum = false
, isoperator = false
, input = ''
, len
return stream
function token(data) {
if(data.length) {
stream.queue({
type: map[mode]
, data: data
, position: start
, line: line
})
}
}
function write(chunk) {
i = 0
input += chunk.toString()
len = input.length
while(c = input[i], i < len) switch(mode) {
case BLOCK_COMMENT: i = block_comment(); break
case LINE_COMMENT: i = line_comment(); break
case PREPROCESSOR: i = preprocessor(); break
case OPERATOR: i = operator(); break
case INTEGER: i = integer(); break
case HEX: i = hex(); break
case FLOAT: i = decimal(); break
case TOKEN: i = readtoken(); break
case WHITESPACE: i = whitespace(); break
case NORMAL: i = normal(); break
}
total += i
input = input.slice(i)
}
function end(chunk) {
if(content.length) {
token(content.join(''))
}
mode = EOF
token('(eof)')
stream.queue(null)
}
function normal() {
content = content.length ? [] : content
if(last === '/' && c === '*') {
start = total + i - 1
mode = BLOCK_COMMENT
last = c
return i + 1
}
if(last === '/' && c === '/') {
start = total + i - 1
mode = LINE_COMMENT
last = c
return i + 1
}
if(c === '#') {
mode = PREPROCESSOR
start = total + i
return i
}
if(/\s/.test(c)) {
mode = WHITESPACE
start = total + i
return i
}
isnum = /\d/.test(c)
isoperator = /[^\w_]/.test(c)
start = total + i
mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN
return i
}
function whitespace() {
if(c === '\n') ++line
if(/[^\s]/g.test(c)) {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function preprocessor() {
if(c === '\n') ++line
if(c === '\n' && last !== '\\') {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function line_comment() {
return preprocessor()
}
function block_comment() {
if(c === '/' && last === '*') {
content.push(c)
token(content.join(''))
mode = NORMAL
return i + 1
}
if(c === '\n') ++line
content.push(c)
last = c
return i + 1
}
function operator() {
if(last === '.' && /\d/.test(c)) {
mode = FLOAT
return i
}
if(last === '/' && c === '*') {
mode = BLOCK_COMMENT
return i
}
if(last === '/' && c === '/') {
mode = LINE_COMMENT
return i
}
if(c === '.' && content.length) {
while(determine_operator(content));
mode = FLOAT
return i
}
if(c === ';') {
if(content.length) while(determine_operator(content));
token(c)
mode = NORMAL
return i + 1
}
var is_composite_operator = content.length === 2 && c !== '='
if(/[\w_\d\s]/.test(c) || is_composite_operator) {
while(determine_operator(content));
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function determine_operator(buf) {
var j = 0
, k = buf.length
, idx
do {
idx = operators.indexOf(buf.slice(0, buf.length + j).join(''))
if(idx === -1) {
j -= 1
k -= 1
if (k < 0) return 0
continue
}
token(operators[idx])
start += operators[idx].length
content = content.slice(operators[idx].length)
return content.length
} while(1)
}
function hex() {
if(/[^a-fA-F0-9]/.test(c)) {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function integer() {
if(c === '.') {
content.push(c)
mode = FLOAT
last = c
return i + 1
}
if(/[eE]/.test(c)) {
content.push(c)
mode = FLOAT
last = c
return i + 1
}
if(c === 'x' && content.length === 1 && content[0] === '0') {
mode = HEX
content.push(c)
last = c
return i + 1
}
if(/[^\d]/.test(c)) {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function decimal() {
if(c === 'f') {
content.push(c)
last = c
i += 1
}
if(/[eE]/.test(c)) {
content.push(c)
last = c
return i + 1
}
if(/[^\d]/.test(c)) {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function readtoken() {
if(/[^\d\w_]/.test(c)) {
var contentstr = content.join('')
if(literals.indexOf(contentstr) > -1) {
mode = KEYWORD
} else if(builtins.indexOf(contentstr) > -1) {
mode = BUILTIN
} else {
mode = IDENT
}
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
}
},{"../through":47,"./lib/builtins":44,"./lib/literals":45,"./lib/operators":46}],44:[function(require,module,exports){
module.exports = [
'gl_Position'
, 'gl_PointSize'
, 'gl_ClipVertex'
, 'gl_FragCoord'
, 'gl_FrontFacing'
, 'gl_FragColor'
, 'gl_FragData'
, 'gl_FragDepth'
, 'gl_Color'
, 'gl_SecondaryColor'
, 'gl_Normal'
, 'gl_Vertex'
, 'gl_MultiTexCoord0'
, 'gl_MultiTexCoord1'
, 'gl_MultiTexCoord2'
, 'gl_MultiTexCoord3'
, 'gl_MultiTexCoord4'
, 'gl_MultiTexCoord5'
, 'gl_MultiTexCoord6'
, 'gl_MultiTexCoord7'
, 'gl_FogCoord'
, 'gl_MaxLights'
, 'gl_MaxClipPlanes'
, 'gl_MaxTextureUnits'
, 'gl_MaxTextureCoords'
, 'gl_MaxVertexAttribs'
, 'gl_MaxVertexUniformComponents'
, 'gl_MaxVaryingFloats'
, 'gl_MaxVertexTextureImageUnits'
, 'gl_MaxCombinedTextureImageUnits'
, 'gl_MaxTextureImageUnits'
, 'gl_MaxFragmentUniformComponents'
, 'gl_MaxDrawBuffers'
, 'gl_ModelViewMatrix'
, 'gl_ProjectionMatrix'
, 'gl_ModelViewProjectionMatrix'
, 'gl_TextureMatrix'
, 'gl_NormalMatrix'
, 'gl_ModelViewMatrixInverse'
, 'gl_ProjectionMatrixInverse'
, 'gl_ModelViewProjectionMatrixInverse'
, 'gl_TextureMatrixInverse'
, 'gl_ModelViewMatrixTranspose'
, 'gl_ProjectionMatrixTranspose'
, 'gl_ModelViewProjectionMatrixTranspose'
, 'gl_TextureMatrixTranspose'
, 'gl_ModelViewMatrixInverseTranspose'
, 'gl_ProjectionMatrixInverseTranspose'
, 'gl_ModelViewProjectionMatrixInverseTranspose'
, 'gl_TextureMatrixInverseTranspose'
, 'gl_NormalScale'
, 'gl_DepthRangeParameters'
, 'gl_DepthRange'
, 'gl_ClipPlane'
, 'gl_PointParameters'
, 'gl_Point'
, 'gl_MaterialParameters'
, 'gl_FrontMaterial'
, 'gl_BackMaterial'
, 'gl_LightSourceParameters'
, 'gl_LightSource'
, 'gl_LightModelParameters'
, 'gl_LightModel'
, 'gl_LightModelProducts'
, 'gl_FrontLightModelProduct'
, 'gl_BackLightModelProduct'
, 'gl_LightProducts'
, 'gl_FrontLightProduct'
, 'gl_BackLightProduct'
, 'gl_FogParameters'
, 'gl_Fog'
, 'gl_TextureEnvColor'
, 'gl_EyePlaneS'
, 'gl_EyePlaneT'
, 'gl_EyePlaneR'
, 'gl_EyePlaneQ'
, 'gl_ObjectPlaneS'
, 'gl_ObjectPlaneT'
, 'gl_ObjectPlaneR'
, 'gl_ObjectPlaneQ'
, 'gl_FrontColor'
, 'gl_BackColor'
, 'gl_FrontSecondaryColor'
, 'gl_BackSecondaryColor'
, 'gl_TexCoord'
, 'gl_FogFragCoord'
, 'gl_Color'
, 'gl_SecondaryColor'
, 'gl_TexCoord'
, 'gl_FogFragCoord'
, 'gl_PointCoord'
, 'radians'
, 'degrees'
, 'sin'
, 'cos'
, 'tan'
, 'asin'
, 'acos'
, 'atan'
, 'pow'
, 'exp'
, 'log'
, 'exp2'
, 'log2'
, 'sqrt'
, 'inversesqrt'
, 'abs'
, 'sign'
, 'floor'
, 'ceil'
, 'fract'
, 'mod'
, 'min'
, 'max'
, 'clamp'
, 'mix'
, 'step'
, 'smoothstep'
, 'length'
, 'distance'
, 'dot'
, 'cross'
, 'normalize'
, 'faceforward'
, 'reflect'
, 'refract'
, 'matrixCompMult'
, 'lessThan'
, 'lessThanEqual'
, 'greaterThan'
, 'greaterThanEqual'
, 'equal'
, 'notEqual'
, 'any'
, 'all'
, 'not'
, 'texture2D'
, 'texture2DProj'
, 'texture2DLod'
, 'texture2DProjLod'
, 'textureCube'
, 'textureCubeLod'
]
},{}],45:[function(require,module,exports){
module.exports = [
// current
'precision'
, 'highp'
, 'mediump'
, 'lowp'
, 'attribute'
, 'const'
, 'uniform'
, 'varying'
, 'break'
, 'continue'
, 'do'
, 'fo'+'r'
, 'whi'+'le'
, 'i'+'f'
, 'else'
, 'in'
, 'out'
, 'inout'
, 'float'
, 'int'
, 'void'
, 'bool'
, 'true'
, 'false'
, 'discard'
, 'return'
, 'mat2'
, 'mat3'
, 'mat4'
, 'vec2'
, 'vec3'
, 'vec4'
, 'ivec2'
, 'ivec3'
, 'ivec4'
, 'bvec2'
, 'bvec3'
, 'bvec4'
, 'sampler1D'
, 'sampler2D'
, 'sampler3D'
, 'samplerCube'
, 'sampler1DShadow'
, 'sampler2DShadow'
, 'struct'
// future
, 'asm'
, 'class'
, 'union'
, 'enum'
, 'typedef'
, 'template'
, 'this'
, 'packed'
, 'goto'
, 'switch'
, 'default'
, 'inline'
, 'noinline'
, 'volatile'
, 'public'
, 'static'
, 'extern'
, 'external'
, 'interface'
, 'long'
, 'short'
, 'double'
, 'half'
, 'fixed'
, 'unsigned'
, 'input'
, 'output'
, 'hvec2'
, 'hvec3'
, 'hvec4'
, 'dvec2'
, 'dvec3'
, 'dvec4'
, 'fvec2'
, 'fvec3'
, 'fvec4'
, 'sampler2DRect'
, 'sampler3DRect'
, 'sampler2DRectShadow'
, 'sizeof'
, 'cast'
, 'namespace'
, 'using'
]
},{}],46:[function(require,module,exports){
module.exports = [
'<<='
, '>>='
, '++'
, '--'
, '<<'
, '>>'
, '<='
, '>='
, '=='
, '!='
, '&&'
, '||'
, '+='
, '-='
, '*='
, '/='
, '%='
, '&='
, '^='
, '|='
, '('
, ')'
, '['
, ']'
, '.'
, '!'
, '~'
, '*'
, '/'
, '%'
, '+'
, '-'
, '<'
, '>'
, '&'
, '^'
, '|'
, '?'
, ':'
, '='
, ','
, ';'
, '{'
, '}'
]
},{}],47:[function(require,module,exports){
var through;
through = function(write, end) {
var errors, output;
output = [];
errors = [];
return {
output: output,
parser: null,
write: write,
end: end,
process: function(parser, data) {
this.parser = parser;
write(data);
this.flush();
return this.parser.flush();
},
flush: function() {
end();
return [output, errors];
},
queue: function(obj) {
var _ref;
if (obj != null) {
return (_ref = this.parser) != null ? _ref.write(obj) : void 0;
}
},
emit: function(type, node) {
if (type === 'data') {
if (node.parent == null) {
output.push(node);
}
}
if (type === 'error') {
return errors.push(node);
}
}
};
};
module.exports = through;
},{}]},{},[28]) |
describe("Adventure", function() {
var adventure;
beforeEach(function() {
// Given some options
var map = {
"root": [{"name": "airports", x: "10px", y: 2},
{"name": "fresh-fruit-juice", x: "10px", y: 4},
{"name": "art-history", x: "10px", y:6}],
"options":[
{
"name": "airports",
"title": "Airports",
"position": {"left": "10px", "top": "20px"},
"content": {
"image": "assets/fullsize/prototype-informs-ux.jpg",
"thumbnail": "assets/thumbnails/prototype-informs-ux.jpg"
},
"notes": ["Who can tell me what this is? It's an example of a dysfunctional queuing strategy." +
"Why is it dusfunctional? Because an airline employee has to keep expediting by " +
"shouting the names of closing flights and pulling people to the front of the queue"],
"links": ["art-history", "limit-queue-sizes", "make-the-work-visible", "feedback"]
},
{
"name": "fresh-fruit-juice",
"title": "Fresh Fruit Juice",
"content": {
"image": "assets/fullsize/prototype-informs-ux.jpg",
},
"notes": ["Man I love Fresh Fruit Juice"]
},
{
"name": "art-history",
"title": "Art History"
},
{
"name": "make-the-work-visible",
"title": "Make the Work Visible"
}
]};
adventure = new Adventure(map);
crossroads.removeAllRoutes();
});
it("should let me drag the options around the screen", function() {
var stage = sandbox();
adventure.setStage(stage);
start(adventure);
adventure.draggable();
for (var i=0; i < adventure.map.root.length; i++) {
var option = stage.find('#' + adventure.map.root[i].name);
// How do we check that the element has been decorated as movable?
}
});
it("should give me some options for my adventure to begin", function() {
// And a template
adventure.setRootTemplate("{{#.}}|{{title}}{{/.}}|");
// I should see this at the root / start of my adventure
var expected_html = "|Airports|Fresh Fruit Juice|Art History|";
expect(adventure.root()).toEqual(expected_html);
});
it("should display a thumbnail for the option if one is available", function() {
var stage = sandbox();
adventure.setStage(stage);
start(adventure);
expect(stage).toContainElement('#airports');
var airports = stage.find('#airports');
expect(airports).toContainElement('img');
});
it("should arrange the options as if they were pinned to a wall", function() {
var stage = sandbox();
adventure.setStage(stage);
start(adventure);
expect(stage).toContainElement('#airports');
var airports = stage.find('#airports');
expect(airports).toHaveCss({'left': '10px'});
});
it("should have a link from an option to its content", function() {
var options = setFixtures(adventure.root());
expect(options.find('a')).toHaveAttr('href', '#/node/airports');
// We should have a route for each of the options
expect(crossroads.getNumRoutes()).toBe(3);
});
it("should put new content on the stage when we navigate to it", function() {
var stage = sandbox();
adventure.setStage(stage);
navigate('airports', adventure);
expect(stage).toContainElement('img');
});
it("should present simple content - a single image", function() {
var airports = setFixtures(adventure.node("airports").html);
// The content image should be displayed
expect(airports).toContainElement('img');
expect(airports.find('img')).toHaveAttr('src', 'assets/fullsize/prototype-informs-ux.jpg');
// This should work for multiple nodes
var fruit_juice = setFixtures(adventure.node("fresh-fruit-juice").html);
// The content image should be displayed
expect(fruit_juice).toContainElement('img');
expect(fruit_juice.find('img')).toHaveAttr('src', 'assets/fullsize/prototype-informs-ux.jpg');
});
it("should present the notes along with the content", function() {
});
it("should still display content even if there are no notes", function() {
});
it("should not explode if there is no content in a node", function() {
var node = adventure.node("does-not-exist");
expect(node).toBeUndefined();
});
it("should give me some options to continue my adventure", function() {
var stage = sandbox();
adventure.setStage(stage);
navigate('airports', adventure);
// Make thse a loop?
expect(stage).toContainElement('div#art-history');
expect(stage).toContainElement('div#limit-queue-sizes');
expect(stage).toContainElement('div#make-the-work-visible');
expect(stage).toContainElement('div#feedback');
});
it("should include a thumbnail image in the links", function() {
var stage = sandbox();
adventure.setStage(stage);
navigate('airports', adventure);
expect(stage).toContainElement('div#art-history');
var link = stage.find('div#art-history');
expect(link).toContainElement('img');
});
it("should just display the title if there is no content", function() {
var stage = sandbox();
adventure.setStage(stage);
navigate('art-history', adventure);
expect(stage).toContainElement('#node-title');
expect(stage.find('#node-title')).toContainText('Art History');
});
it("should display the title of the current content", function() {
var title_header = sandbox();
adventure.setTitleHeader(title_header);
navigate('art-history', adventure);
expect(title_header).toContainElement('#node-title-header');
expect(title_header.find('#node-title-header')).toContainText('Art History');
});
});
|
/*! backbone-repository - v1.0.0 - 2016-01-08
* Copyright (c) 2016 Nacho Codoñer; Licensed MIT */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['backbone', 'underscore'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS
var Backbone = require('backbone'),
_ = require('underscore');
module.exports = factory(Backbone, _);
} else {
// Browser globals
factory(root.Backbone, root._);
}
}(this, function (Backbone, _) {
'use strict';
var Repository = {
// Default backbone sync function.
backboneSync: Backbone.sync,
/**
* Returns an array with the sync mode names.
*/
modes : function () {
return _.keys(syncModes);
},
/**
* Registers a new sync mode.
* @param {String|Object} [mode] Mode name or configuration {mode: fn}
* @param {Function} [fn] Sync method
*/
setMode: function (mode, fn) {
if (_.isObject(mode)) {
_.extend(syncModes, mode);
} else {
syncModes[mode] = fn;
}
},
/**
* Unregisters sync modes.
* @param {String} [mode] Mode name
*/
removeMode: function (mode) {
delete syncModes[mode];
},
/**
* Get sync mode method.
* @param {String} [mode] Mode name
*/
getMode: function (mode) {
if (_.isFunction(mode)) {
return mode;
}
return syncModes[mode];
},
/**
* Gets the default mode.
*/
getDefaultMode: function () {
return defaultMode;
},
/**
* Sets the default mode.
* @param {String|Function} [mode] Mode name or fn
*/
setDefaultMode: function (mode) {
if (_.isFunction(mode)) {
defaultMode = _.findKey(syncModes, function (value) {
return (value === mode);
});
} else {
defaultMode = mode;
}
},
/**
* Resets sync modes.
*/
resetModes: function () {
syncModes = {};
},
VERSION: '1.0.0'
};
// Hash containing sync modes registered.
var syncModes = {};
// Private variable containing defaultMode
var defaultMode;
Backbone.Repository = Repository;
/*! backbone.jsonify - v0.2.0 - 2015-11-14
* Copyright (c) 2015 Nacho Codoñer; Licensed MIT */ (function(Backbone, _) {
"use strict";
Backbone.Jsonify = {};
Backbone.Jsonify.VERSION = "0.2.0";
Backbone.Jsonify.exToJSON = Backbone.Model.prototype.toJSON;
var serializeDeeper = function(object, deepJson) {
_.each(object, function(value, key) {
if (value instanceof Backbone.Model || value instanceof Backbone.Collection) {
object[key] = value.toJSON({
deepJson: deepJson
});
} else if (_.isObject(value) && deepJson) {
object[key] = serializeDeeper(_.clone(value), deepJson);
}
});
return object;
};
Backbone.Model.prototype.exToJSON = Backbone.Jsonify.exToJSON;
Backbone.Model.prototype.toJSON = _.wrap(Backbone.Jsonify.exToJSON, function(exToJSON) {
var options = arguments[1];
options || (options = {});
var output;
if (_.isBoolean(options.omit) && options.omit || _.isBoolean(options.pick) && !options.pick) {
// When 'true' omit, or 'false' pick
return {};
} else if (_.isBoolean(options.pick) && options.pick || _.isBoolean(options.omit) && !options.omit) {
// When 'true' pick, or 'false' omit
output = exToJSON.call(this, options);
} else if (options.pick) {
// `pick` logic
output = _.pick(this.attributes, options.pick);
} else if (options.omit) {
// `omit` logic
output = _.omit(this.attributes, options.omit);
} else {
output = exToJSON.call(this, options);
}
output = serializeDeeper(output, options.deepJson);
return output;
});
})(Backbone, _);
/* Backbone.Repository */
var Model = Backbone.Model;
var previousSet = Backbone.Model.prototype.set;
var previousFetch = Backbone.Model.prototype.fetch;
var previousSave = Backbone.Model.prototype.save;
var previousDestroy = Backbone.Model.prototype.destroy;
var previousToJSON = Backbone.Model.prototype.toJSON;
/**
* Replacement for Backbone.Model. Supports a global track point.
*
* @class Backbone.Model
* @extends Backbone.Model
*/
Backbone.Model = Backbone.Model.extend({
/**
* @property {string} [cidAttribute="cid"] The attribute to store
* the cid in for lookup.
*/
cidAttribute: 'cid',
constructor: function () {
// The constructor is defined for ensuring to create
// the instance without loosing neither the initialization
// logic required by this library nor customized by the user.
if(this.initialize !== Backbone.Model.prototype.initialize) {
var self = this;
var overridedInit = this.initialize;
// Composes new initialize method that contains
// both library and customized initialize method
this.initialize = _.wrap(Backbone.Model.prototype.initialize, function(backboneInit) {
backboneInit.apply(self, _.rest(arguments));
overridedInit.apply(self, _.rest(arguments));
});
}
return Model.apply(this, arguments);
},
initialize: function () {
var self = this;
this.dirtied = {};
this._destroyed = {};
this._fetched = {};
_.each(Backbone.Repository.modes(), function (mode) {
this.dirtied[mode] = {};
this._destroyed[mode] = false;
this._fetched[mode] = false;
}.bind(this));
this._dirtyDestroyed = false;
// Saving dirty attributes
_.each(Backbone.Repository.modes(), function (mode) {
this.dirtied[mode] || (this.dirtied[mode] = {});
_.extend(this.dirtied[mode], _.omit(this.attributes, [this.idAttribute, this.cidAttribute]));
}.bind(this));
// Use `"cid"` for retrieving models by `attributes.cid`.
this.set(this.cidAttribute, this.cid);
// Add the model to `all`.
var ctor = this.constructor;
ctor.register().add(this);
},
/**
* @property {String|Boolean} [versionAttribute=false] Represents
* the attribute used as version stamps for the model. In case 'false',
* versioning is not enabled for the model.
*/
versionAttribute: false,
/**
* @property {Object<String,Boolean>} [_fetched={}] Flag that means if the model
* has been fetched through a mode.
*/
_fetched: {},
/**
* @return {boolean} 'true' if this model has been fetched through the mode,
* 'false' otherwise
*/
isFetched: function (options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
return this._fetched[options.mode] || false;
},
/**
* @property {Object} [dirtied] Internal hash containing all
* attributes that have changed since its last server synchronization.
*/
dirtied: {},
/**
* @return {Object} [dirtiedAttributes] Retrieve a copy of the attributes that have
* changed since the last server synchronization.
*/
dirtiedAttributes: function(options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
return _.clone(this.dirtied[options.mode]) || {};
},
/**
* @param {Array.<String>} [attr] The attribute to check if has been changed.
* @return {boolean} 'true' in case the model changed since its last sever
* synchronization, 'false' otherwise
*/
hasDirtied: function (attr, options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
if (attr == null) return !_.isEmpty(this.dirtied[options.mode]);
return _.has(this.dirtied[options.mode], attr);
},
/**
* @property {boolean} [_dirtyDestroyed="false"] Flag that means if the model
* has been destroyed locally.
*/
_dirtyDestroyed: false,
/**
* @return {boolean} 'true' if this model has been destroyed locally,
* 'false' otherwise
*/
isDirtyDestroyed: function () {
return this._dirtyDestroyed;
},
/**
* Erases dirtied changes of the model, whether attribute change or model destroy.
*/
clearDirtied: function() {
_.each(this.dirtied, function (value, key) {
this.dirtied[key] = {}
}.bind(this));
this.dirtiedDestroyed = false;
},
set: function(key, val, options) {
if (key == null) return this;
var attrs;
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
if(_.isUndefined(options.dirty)) {
options.dirty = true; // Default dirty option.
}
var previousVersion;
if(options.version) {
previousVersion = this.attributes[this.versionAttribute];
}
var output = previousSet.call(this, attrs, options);
if(options.dirty) {
_.each(Backbone.Repository.modes(), function (mode) {
this.dirtied[mode] || (this.dirtied[mode] = {});
_.extend(this.dirtied[mode], _.omit(attrs, [this.idAttribute, this.cidAttribute]));
}.bind(this));
}
// Versioning handler.
if(options.version &&
this.versionAttribute && attrs[this.versionAttribute]) {
var newVersion = attrs[this.versionAttribute];
checkVersion(this, options, newVersion, previousVersion);
}
return output;
},
/**
* @property {boolean} [_destroyed={}] Flag that means if the model
* has been destroyed against the sync mode.
*/
_destroyed: {},
/**
* @return {boolean} 'true' if this model has been destroyed against the sync mode,
* 'false' otherwise
*/
isDestroyed: function (options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
return this._destroyed[options.mode] || false;
},
/**
* Alters fetch method.
*/
fetch: function(options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
return previousFetch.apply(this, [options]);
},
/**
* Alters save method to include changes being set as an option
* for the Repository method.
*/
save: function(key, val, options) {
var attrs;
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
if(options.patch) {
options.changes = attrs;
} else {
options.changes = _.extend(_.clone(this.attributes), attrs);
}
return previousSave.apply(this, [attrs, options]);
},
/**
* Alters destroy method to set diryDestroyed flag.
*/
destroy: function(options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
var model = this;
var success = options.success;
var wait = options.wait;
options.success = function(resp) {
if (wait) model._dirtyDestroyed = true;
if (success) success.call(options.context, model, resp, options);
};
if (!wait) model._dirtyDestroyed = true;
// Forces to execute sync method when the model is new as well.
if (this.isNew()) {
var destroy = function() {
model.stopListening();
model.trigger('destroy', model, model.collection, options);
};
options.success = function(resp) {
if (wait) model._dirtyDestroyed = true;
if (wait) destroy();
if (success) success.call(options.context, model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
};
_.defer(options.success);
if (!wait) destroy();
wrapError(this, options);
return this.sync('delete', this, options);
} else {
return previousDestroy.apply(this, [options]);
}
},
/**
* Fetches the model if it has not been fetched before.
*
* @param {Object} [options]
* @return {Object} xhr
*/
pull: function(options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
var mode = options.mode;
if (this.isFetched(options)) {
_.defer(options.success, this, undefined, options);
return;
}
return this.fetch(options);
},
/**
* Pushes the changes performed to the model; create, update
* or destroy.
*
* @param {Object} [options]
* @return {Object} xhr
*/
push: function(options) {
options || (options = {});
if(this.isDirtyDestroyed()) {
// Model is marked as destroyed, but in case is new, it won't be synchronized.
if(this.isNew()) return;
return this.destroy(options);
} else if(this.isNew()) {
// Model is new, it will be created remotelly.
return this.save(null, options);
} else if(this.hasDirtied(null, options)) {
// Model has dirtied changes, it will be updated remotelly.
return this.save(this.dirtiedAttributes(options), options);
}
},
/**
* @property {String} [checkUrl=""] The checking endpoint for the Model.
*/
checkUrl: '',
/**
* Check method
*
* @param {Object} [options]
* @return {Object} xhr
*/
check: function(options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
var url = options.checkUrl || _.result(this, 'checkUrl');
if (!url) {
throw new Error('The "checkUrl" must be specified.');
}
return this.fetch(_.extend(options, {
url: url,
version: true
}));
},
/**
* Alters toJSON for enabling to remove cid from toJSON response.
*/
toJSON: function (options) {
var output = previousToJSON.call(this, options);
// Include cid?
if (options && !options.cid) {
delete output[this.cidAttribute];
}
return output;
}
}, {
/**
* Factory method that returns a model instance and
* ensures only one is gonna be created with same id.
*
* @param {Object} [attrs] Attributes for the new instance.
* @param {Object} [options] Options for the new instance.
*/
create: function (attrs, options) {
options || (options = {});
// Corrects id attr according to the option passed.
if (options.idAttribute && attrs[options.idAttribute]) {
var tmp = attrs[options.idAttribute];
delete attrs[options.idAttribute];
attrs[this.prototype.idAttribute] = tmp;
}
// Corrects cid attr according to the option passed.
if (options.cidAttribute && attrs[options.cidAttribute]) {
var tmp = attrs[options.cidAttribute];
delete attrs[options.cidAttribute];
attrs[this.prototype.cidAttribute] = tmp;
}
var id = attrs && attrs[this.prototype.idAttribute];
var model = this.find(attrs);
// If found by id, modify and return it.
if(model) {
// Modifies only if `attrs` does not reference to an existing model.
if(attrs !== model.attributes) {
model.set(model.parse(attrs), _.extend(options, {silent: false}));
return model;
}
// Makes validations if required by options
if(options.validate)
model._validate({}, options);
return model;
}
// Ensure attributes are parsed.
options.parse = true;
return new this(attrs, options);
},
/**
* Returns a model by its id or cid from the local cache
* of the model.
*
* @param {Object} [attrs] An id or cid for looking up.
*/
find: function (attrs){
if (!attrs) return false;
var cid = attrs[this.prototype.cidAttribute];
var id = attrs[this.prototype.idAttribute];
return (cid || id) && this.register().get(cid || id) || false;
},
/**
* Returns the collection that represents the local cache
* of the model.
*/
register: function () {
if(!this._register) {
var Constructor = this;
var Register = Backbone.Collection.extend({
model: Constructor
});
var register = this._register = new Register();
register.on("destroy", function(model) {
if (model.isDirtyDestroyed() && !model.isDestroyed())
register.add(model, {silent: true});
});
}
return this._register;
},
/**
* Resets the local cache of the model.
*/
reset: function () {
this.register().reset();
}
});
var prevInitCollection = Backbone.Collection.prototype.initialize;
var prevFetchCollection = Backbone.Collection.prototype.fetch;
/**
* Enhancements for Backbone.Collection.
*
* @class Backbone.Collection
* @extends Backbone.Collection
*/
Backbone.Collection = Backbone.Collection.extend({
/**
* Returns the collection url for specific models
* within the collection.
*
* @param {Array} [ids]
* @return {String}
*/
idsUrl: function (ids) {
return "/"+ids.join(";");
},
/**
* Alters fetch method to enable infinite mode.
*/
fetch: function(options) {
options = _.extend({parse: true}, options);
_.defaults(options, {mode: Repository.getDefaultMode()});
return prevFetchCollection.apply(this, [options]);
},
/**
* Method to save all models from a collection.
*
* @param {Object} [options]
* @return {Array<Object>} outputs
*/
save: function(options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
var success = options.success;
options.originalSuccess = options.success;
var collection = this;
options.success = function(resp) {
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success.call(options.context, collection, resp, options);
collection.trigger('sync', collection, resp, options);
};
return this.sync('update', this, options);
},
/**
* Method to destroy all models from a collection.
*
* @param {Object} [options]
* @return {Array<Object>} outputs
*/
destroy: function(options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
var success = options.success;
options.originalSuccess = options.success;
var collection = this;
options.success = function(resp) {
if (success) success.call(options.context, collection, resp, options);
collection.trigger('sync', collection, resp, options);
};
return this.sync('delete', this, options);
},
/**
* Fetches the collection models that are not fetched.
*
* @param {Object} [options]
* @return {Array<Object>} xhrs
*/
pull: function(options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
var success = options.success;
options.remove = false;
options.modelsToFetch = this.filter(function (model) {
return !model.isNew() && !model.isFetched();
});
if(_.isEmpty(options.modelsToFetch)) {
_.defer(success, this, undefined, options);
return;
}
var idsToFetch = _.map(options.modelsToFetch, function (model) {
return model.id;
});
options.url = _.result(this, 'url')+this.idsUrl(idsToFetch);
return this.fetch(options);
},
/**
* Method to push all models from a collection.
*
* @param {Object} [options]
* @return {Array<Object>} outputs
*/
push: function(options) {
var models = _.clone(this.models);
_.each(models, function (model) {
model.push(options);
});
},
/**
* @property {String} [checkUrl=""] The checking endpoint for Collection.
*/
checkUrl: '',
/**
* Check method
*
* @param {Object} [options]
* @return {Object} xhr
*/
check: function(options) {
options || (options = {});
_.defaults(options, {mode: Repository.getDefaultMode()});
var url = options.checkUrl || _.result(this, 'checkUrl');
if (!url) {
throw new Error('The "checkUrl" must be specified.');
}
return this.fetch(_.extend(options, {
url: url,
version: true
}));
}
});
/**
* Repository's logic for sync methods.
*/
var sync = function (method, model, options) {
options || (options = {});
options.method = method;
var mode = options.mode;
// Wrap success function to handle model states for the mode.
wrapSuccess(method, model, options);
if (mode) {
var syncFn = Repository.getMode(mode);
if (syncFn) {
return syncFn.apply(options.context, [method, model, options]);
} else {
throw new Error('The "mode" passed must be implemented.');
}
} else {
return Repository.backboneSync.apply(options.context, [method, model, options]);
}
}
var wrapSuccess = function (method, model, options) {
var mode = options.mode;
if(model instanceof Backbone.Model) {
switch(method) {
case "create":
case "update":
case "patch":
var success = options.success;
options.success = function (response) {
// Marks the model as fetched in case it is a new one.
if(method === "create") {
model._fetched[mode] = true;
}
// Resolves attributes marked as dirtied.
_.each(options.changes, function (attrVal, attrKey) {
var dirtiedVal = model.dirtied[mode][attrKey];
if(dirtiedVal === attrVal) {
delete model.dirtied[mode][attrKey];
}
});
if(success) success.call(options.context, response);
};
break;
case "delete":
var success = options.success;
// Server mode.
options.success = function (response) {
model._destroyed[mode] = true;
if(success) success.call(options.context, response);
};
break;
case "read":
var success = options.success;
options.success = function (resp) {
// Mark model as fetched.
if(!options.version) {
model._fetched[mode] = true;
}
if(success) success.call(options.context, resp);
};
break;
}
} else if(model instanceof Backbone.Collection) {
var collection = model;
switch(method) {
case "read":
var success = options.success;
options.success = function (resp) {
_.each(collection.models, function (model) {
var searchBy = {};
searchBy[model.idAttribute] = model.id;
var respModel = _.findWhere(resp, searchBy);
// Mark model as fetched.
if(!options.version) {
model._fetched[mode] = true;
}
});
if(success) success.call(options.context, resp);
};
break;
}
}
}
/**
* Sync method for client mode.
*/
var clientSync = function (method, model, options) {
var mode = options.mode;
if(model instanceof Backbone.Model) {
_.defer(options.success);
} else if(model instanceof Backbone.Collection) {
options.success = options.originalSuccess;
var collection = model;
switch(method) {
case "create":
case "update":
case "patch":
collection.each(function (model) {
model.save(null, options);
});
break;
case "delete":
collection.each(function (model) {
model.destroy(options);
});
break;
}
}
}
/**
* Sync method for server mode.
*/
var serverSync = function (method, model, options) {
var mode = options.mode;
if(model instanceof Backbone.Model) {
switch(method) {
case "create":
case "update":
case "patch":
var success = options.success;
options.success = function (response) {
// Avoids set to dirty server attributes.
options.dirty = false;
if(success) success.call(options.context, response);
};
return Repository.backboneSync.apply(this, [method, model, options]);
case "delete":
// Performs nothing in case the model is new.
if (model.isNew()) return false;
// Avoids set to dirty server attributes.
options.dirty = false;
model.constructor.register().remove(model);
return Repository.backboneSync.apply(this, [method, model, options]);
case "read":
// Avoids set to dirty server attributes.
options.dirty = false;
return Repository.backboneSync.apply(this, [method, model, options]);
}
} else if(model instanceof Backbone.Collection) {
var collection = model;
switch(method) {
case "read":
var success = options.success;
options.remove = false;
options.success = function (resp) {
// Avoids set to dirty server attributes.
options.dirty = false;
// Prepares the collection according to the passed option.
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if(success) success.call(options.context, resp);
};
return Repository.backboneSync.apply(this, [method, collection, options]);
case "create":
case "update":
case "patch":
options.success = options.originalSuccess;
collection.each(function (model) {
model.save(null, options);
});
break;
case "delete":
options.success = options.originalSuccess;
var models = _.clone(collection.models);
_.each(models, function (model) {
model.destroy(options);
});
break;
}
}
}
var syncMode = {
client: clientSync,
server: serverSync
};
// Registers syncModes from the library.
Repository.setMode(syncMode);
// Establish default mode.
Repository.setDefaultMode("server");
// Replaces the previous Backbone.sync method by the Repository's one.
Backbone.sync = sync;
/**
* @return {Boolean} Change fetch status whether 'newVersion' is more actual than
* 'currentVersion'.
*/
function checkVersion (model, options, newVersion, currentVersion) {
if (isLaterVersion(newVersion, currentVersion)) {
var mode = options.mode;
if(mode) {
model._fetched[mode] = false;
}
// triggers outdated event
model.trigger("outdated", model, newVersion, options);
}
}
/**
* @return {Boolean} Checks whether 'newVersion' is more actual than
* 'currentVersion'.
*/
function isLaterVersion (newVersion, currentVersion) {
if(_.isUndefined(newVersion)) {
return false;
}
if(_.isUndefined(currentVersion)) {
return true;
}
return newVersion !== currentVersion;
}
var wrapError = function(model, options) {
var error = options.error;
options.error = function(resp) {
if (error) error.call(options.context, model, resp, options);
model.trigger('error', model, resp, options);
};
};
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
}));
|
require.config({
paths: {
'domready' : 'libraries/domReady.min',
'jquery' : 'libraries/jquery-2.1.4.min',
'bootstrap' : 'libraries/bootstrap.min'
},
shim: {
'bootstrap/affix': { deps: ['jquery'], exports: '$.fn.affix' },
'bootstrap/alert': { deps: ['jquery'], exports: '$.fn.alert' },
'bootstrap/button': { deps: ['jquery'], exports: '$.fn.button' },
'bootstrap/carousel': { deps: ['jquery'], exports: '$.fn.carousel' },
'bootstrap/collapse': { deps: ['jquery'], exports: '$.fn.collapse' },
'bootstrap/dropdown': { deps: ['jquery'], exports: '$.fn.dropdown' },
'bootstrap/modal': { deps: ['jquery'], exports: '$.fn.modal' },
'bootstrap/popover': { deps: ['jquery'], exports: '$.fn.popover' },
'bootstrap/scrollspy': { deps: ['jquery'], exports: '$.fn.scrollspy' },
'bootstrap/tab': { deps: ['jquery'], exports: '$.fn.tab' },
'bootstrap/tooltip': { deps: ['jquery'], exports: '$.fn.tooltip' },
'bootstrap/transition': { deps: ['jquery'], exports: '$.fn.transition' }
},
deps: ['Controller']
});
// TODO: Proper AMD loading for Chart JS |
import React from 'react';
import ShallowRenderer from 'react-test-renderer/shallow';
import ActivityShareThumbnail from '.';
const renderer = new ShallowRenderer();
describe('ActivityShareThumbnail post component', () => {
let props;
beforeEach(() => {
props = {
actor: {
displayName: 'Marty McFly'
},
file: {
displayName: 'testImage.js',
url: 'http://cisco.com',
fileSize: 1472837,
objectType: 'js'
},
isFetching: true,
isPending: false,
objectUrl: 'blob:localhost/testFile',
onDownloadClick: jest.fn(),
timestamp: '12:10 PM',
type: 'file'
};
});
it('renders loading state properly', () => {
renderer.render(<ActivityShareThumbnail {...props} />);
const component = renderer.getRenderOutput();
expect(component).toMatchSnapshot();
});
it('renders thumbnail properly', () => {
props.isFetching = true;
renderer.render(<ActivityShareThumbnail {...props} />);
const component = renderer.getRenderOutput();
expect(component).toMatchSnapshot();
});
it('renders pending properly', () => {
props.isPending = true;
renderer.render(<ActivityShareThumbnail {...props} />);
const component = renderer.getRenderOutput();
expect(component).toMatchSnapshot();
});
it('renders loaded thumbnail properly', () => {
props.isFetching = false;
renderer.render(<ActivityShareThumbnail {...props} />);
const component = renderer.getRenderOutput();
expect(component).toMatchSnapshot();
});
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.10.2.6_A2_T10;
* @section: 15.10.2.6;
* @assertion: The production Assertion :: ^ evaluates by returning an internal AssertionTester closure that takes a State argument x and performs the ...;
* @description: Execute /^\d+/m.exec("abc\n123xyz") and check results;
*/
__executed = /^\d+/m.exec("abc\n123xyz");
__expected = ["123"];
__expected.index = 4;
__expected.input = "abc\n123xyz";
//CHECK#1
if (__executed.length !== __expected.length) {
$ERROR('#1: __executed = /^\\d+/m.exec("abc\\n123xyz"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#2
if (__executed.index !== __expected.index) {
$ERROR('#2: __executed = /^\\d+/m.exec("abc\\n123xyz"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#3
if (__executed.input !== __expected.input) {
$ERROR('#3: __executed = /^\\d+/m.exec("abc\\n123xyz"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __executed = /^\\d+/m.exec("abc\\n123xyz"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
|
'use strict';
describe('Messages E2E Tests:', function() {
describe('Test Messages page', function() {
it('Should not include new Messages', function() {
browser.get('http://localhost:3000/#!/messages');
expect(element.all(by.repeater('message in messages')).count()).toEqual(0);
});
});
});
|
var lokijs = require('lokijs'),
lokiNativescriptAdapter = require('lokijs/src/loki-nativescript-adapter'),
dummyjson = require('dummy-json'),
_ = require('lodash');
var LokiDb = (function () {
// private variable
var texto = 'default';
var _db;
var _users;
var _dashboard;
// private function
function log() {
console.log('doo!');
}
function setText(text) {
texto = text;
}
function getText() {
return texto;
}
function getUsers() {
return _users;
}
function getDashboard() {
return _dashboard;
}
function upsert(collection, idField, record) {
var query = {};
query[idField] = record[idField];
var existingRecord = collection.findOne(query);
if (existingRecord) {
// The record exists. Do an update.
var updatedRecord = existingRecord;
// Only update the fields contained in `record`. All fields not contained
// in `record` remain unchanged.
_.forEach(record, function (value, key) {
updatedRecord[key] = value;
});
collection.update(updatedRecord);
} else {
// The record doesn't exist. Do an insert.
collection.insert(record);
}
}
function _init() {
_db = new lokijs('uda.json', {
adapter: new lokiNativescriptAdapter()
});
_users = _db.addCollection('users', {
indices: ['id']
});
_dashboard = _db.addCollection('dashboard', {
indices: ['id']
});
var myHelpers = {
rol: function () {
// Use randomArrayItem to ensure the seeded random number generator is used
return dummyjson.utils.randomArrayItem(['administrador', 'desarrollador', 'espectador', 'informador', 'manager']);
}
};
var template = '[ \
{{#repeat 1000}} \
{\
"id":"{{@index}}",\
"nombre":"{{firstName}}",\
"apellido1":"{{lastName}}",\
"apellido2":"{{lastName}}",\
"ejie":"{{int 0 1}} ",\
"fechaAlta":"{{date \'2010\' \'2014\' \'DD/MM/YYYY\'}}",\
"fechaBaja":"{{date \'2015\' \'2016\' \'DD/MM/YYYY\'}}",\
"rol":"{{rol}}"\
} \
{{/repeat}} \
]';
// for (var i=0;i<10;i++){
var result = dummyjson.parse(template, {
helpers: myHelpers
}); // Returns a string
var obj = JSON.parse(result);
for (var i = 0; i < obj.length; i++) {
_users.insert(obj[i]);
}
// Dashboard
_dashboard.insert({
'id': '1',
'nombre': 'Escritorio 1',
'serializedArray': '[]'
});
_dashboard.insert({
'id': '2',
'nombre': 'Escritorio 2',
'serializedArray': '[]'
});
_dashboard.insert({
'id': '3',
'nombre': 'Escritorio 3',
'serializedArray': '[]'
});
_dashboard.insert({
'id': '4',
'nombre': 'Escritorio 4',
'serializedArray': '[]'
});
_dashboard.insert({
'id': '5',
'nombre': 'Escritorio 5',
'serializedArray': '[]'
});
}
// return public interface
return {
log: function () {
// we have access to the private function here
// as well as the private variable (btw)
log();
},
setText: function (text) {
setText(text);
},
initialize: function () {
_init();
},
getText: function () {
return getText();
},
getUsers: function () {
return getUsers();
},
upsert: function (collection, idField, record) {
return upsert(collection, idField, record);
},
// Dashboard
dashboard: {
getAll: function (userId) {
return getDashboard();
}
}
};
}()); // we import jQuery as a global symbol
module.exports = LokiDb; |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.10.0-master-dd11583
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.tooltip
*/
angular
.module('material.components.tooltip', [ 'material.core' ])
.directive('mdTooltip', MdTooltipDirective);
/**
* @ngdoc directive
* @name mdTooltip
* @module material.components.tooltip
* @description
* Tooltips are used to describe elements that are interactive and primarily graphical (not textual).
*
* Place a `<md-tooltip>` as a child of the element it describes.
*
* A tooltip will activate when the user focuses, hovers over, or touches the parent.
*
* @usage
* <hljs lang="html">
* <md-button class="md-fab md-accent" aria-label="Play">
* <md-tooltip>
* Play Music
* </md-tooltip>
* <md-icon icon="img/icons/ic_play_arrow_24px.svg"></md-icon>
* </md-button>
* </hljs>
*
* @param {expression=} md-visible Boolean bound to whether the tooltip is
* currently visible.
* @param {number=} md-delay How many milliseconds to wait to show the tooltip after the user focuses, hovers, or touches the parent. Defaults to 400ms.
* @param {string=} md-direction Which direction would you like the tooltip to go? Supports left, right, top, and bottom. Defaults to bottom.
* @param {boolean=} md-autohide If present or provided with a boolean value, the tooltip will hide on mouse leave, regardless of focus
*/
function MdTooltipDirective($timeout, $window, $$rAF, $document, $mdUtil, $mdTheming, $rootElement,
$animate, $q) {
var TOOLTIP_SHOW_DELAY = 300;
var TOOLTIP_WINDOW_EDGE_SPACE = 8;
return {
restrict: 'E',
transclude: true,
priority:210, // Before ngAria
template: '\
<div class="md-background"></div>\
<div class="md-content" ng-transclude></div>',
scope: {
visible: '=?mdVisible',
delay: '=?mdDelay',
autohide: '=?mdAutohide'
},
link: postLink
};
function postLink(scope, element, attr) {
$mdTheming(element);
var parent = getParentWithPointerEvents(),
background = angular.element(element[0].getElementsByClassName('md-background')[0]),
content = angular.element(element[0].getElementsByClassName('md-content')[0]),
direction = attr.mdDirection,
current = getNearestContentElement(),
tooltipParent = angular.element(current || document.body),
debouncedOnResize = $$rAF.throttle(function () { if (scope.visible) positionTooltip(); });
return init();
function init () {
setDefaults();
manipulateElement();
bindEvents();
configureWatchers();
addAriaLabel();
}
function setDefaults () {
if (!angular.isDefined(attr.mdDelay)) scope.delay = TOOLTIP_SHOW_DELAY;
}
function configureWatchers () {
scope.$on('$destroy', function() {
scope.visible = false;
element.remove();
angular.element($window).off('resize', debouncedOnResize);
});
scope.$watch('visible', function (isVisible) {
if (isVisible) showTooltip();
else hideTooltip();
});
}
function addAriaLabel () {
if (!parent.attr('aria-label') && !parent.text().trim()) {
parent.attr('aria-label', element.text().trim());
}
}
function manipulateElement () {
element.detach();
element.attr('role', 'tooltip');
}
function getParentWithPointerEvents () {
var parent = element.parent();
while (parent && $window.getComputedStyle(parent[0])['pointer-events'] == 'none') {
parent = parent.parent();
}
return parent;
}
function getNearestContentElement () {
var current = element.parent()[0];
// Look for the nearest parent md-content, stopping at the rootElement.
while (current && current !== $rootElement[0] && current !== document.body) {
current = current.parentNode;
}
return current;
}
function hasComputedStyleValue(key, value) {
// Check if we should show it or not...
var computedStyles = $window.getComputedStyle(element[0]);
return angular.isDefined(computedStyles[key]) && (computedStyles[key] == value);
}
function bindEvents () {
var mouseActive = false;
var enterHandler = function() {
if (!hasComputedStyleValue('pointer-events','none')) {
setVisible(true);
}
};
var leaveHandler = function () {
var autohide = scope.hasOwnProperty('autohide') ? scope.autohide : attr.hasOwnProperty('mdAutohide');
if (autohide || mouseActive || ($document[0].activeElement !== parent[0]) ) {
setVisible(false);
}
mouseActive = false;
};
// to avoid `synthetic clicks` we listen to mousedown instead of `click`
parent.on('mousedown', function() { mouseActive = true; });
parent.on('focus mouseenter touchstart', enterHandler );
parent.on('blur mouseleave touchend touchcancel', leaveHandler );
angular.element($window).on('resize', debouncedOnResize);
}
function setVisible (value) {
setVisible.value = !!value;
if (!setVisible.queued) {
if (value) {
setVisible.queued = true;
$timeout(function() {
scope.visible = setVisible.value;
setVisible.queued = false;
}, scope.delay);
} else {
$timeout(function() { scope.visible = false; });
}
}
}
function showTooltip() {
// Insert the element before positioning it, so we can get the position
// and check if we should display it
tooltipParent.append(element);
// Check if we should display it or not.
// This handles hide-* and show-* along with any user defined css
if ( hasComputedStyleValue('display','none') ) {
scope.visible = false;
element.detach();
return;
}
positionTooltip();
angular.forEach([element, background, content], function (element) {
$animate.addClass(element, 'md-show');
});
}
function hideTooltip() {
$q.all([
$animate.removeClass(content, 'md-show'),
$animate.removeClass(background, 'md-show'),
$animate.removeClass(element, 'md-show')
]).then(function () {
if (!scope.visible) element.detach();
});
}
function positionTooltip() {
var tipRect = $mdUtil.offsetRect(element, tooltipParent);
var parentRect = $mdUtil.offsetRect(parent, tooltipParent);
var newPosition = getPosition(direction);
// If the user provided a direction, just nudge the tooltip onto the screen
// Otherwise, recalculate based on 'top' since default is 'bottom'
if (direction) {
newPosition = fitInParent(newPosition);
} else if (newPosition.top > element.prop('offsetParent').scrollHeight - tipRect.height - TOOLTIP_WINDOW_EDGE_SPACE) {
newPosition = fitInParent(getPosition('top'));
}
element.css({top: newPosition.top + 'px', left: newPosition.left + 'px'});
positionBackground();
function positionBackground () {
var size = direction === 'left' || direction === 'right'
? Math.sqrt(Math.pow(tipRect.width, 2) + Math.pow(tipRect.height / 2, 2)) * 2
: Math.sqrt(Math.pow(tipRect.width / 2, 2) + Math.pow(tipRect.height, 2)) * 2,
position = direction === 'left' ? { left: 100, top: 50 }
: direction === 'right' ? { left: 0, top: 50 }
: direction === 'top' ? { left: 50, top: 100 }
: { left: 50, top: 0 };
background.css({
width: size + 'px',
height: size + 'px',
left: position.left + '%',
top: position.top + '%'
});
}
function fitInParent (pos) {
var newPosition = { left: pos.left, top: pos.top };
newPosition.left = Math.min( newPosition.left, tooltipParent.prop('scrollWidth') - tipRect.width - TOOLTIP_WINDOW_EDGE_SPACE );
newPosition.left = Math.max( newPosition.left, TOOLTIP_WINDOW_EDGE_SPACE );
newPosition.top = Math.min( newPosition.top, tooltipParent.prop('scrollHeight') - tipRect.height - TOOLTIP_WINDOW_EDGE_SPACE );
newPosition.top = Math.max( newPosition.top, TOOLTIP_WINDOW_EDGE_SPACE );
return newPosition;
}
function getPosition (dir) {
return dir === 'left'
? { left: parentRect.left - tipRect.width - TOOLTIP_WINDOW_EDGE_SPACE,
top: parentRect.top + parentRect.height / 2 - tipRect.height / 2 }
: dir === 'right'
? { left: parentRect.left + parentRect.width + TOOLTIP_WINDOW_EDGE_SPACE,
top: parentRect.top + parentRect.height / 2 - tipRect.height / 2 }
: dir === 'top'
? { left: parentRect.left + parentRect.width / 2 - tipRect.width / 2,
top: parentRect.top - tipRect.height - TOOLTIP_WINDOW_EDGE_SPACE }
: { left: parentRect.left + parentRect.width / 2 - tipRect.width / 2,
top: parentRect.top + parentRect.height + TOOLTIP_WINDOW_EDGE_SPACE };
}
}
}
}
MdTooltipDirective.$inject = ["$timeout", "$window", "$$rAF", "$document", "$mdUtil", "$mdTheming", "$rootElement", "$animate", "$q"];
})(window, window.angular); |
(function () {
'use strict';
/**
* @ngdoc overview
* @name ui.grid.treeBase
* @description
*
* # ui.grid.treeBase
*
* <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div>
*
* This module provides base tree handling functions that are shared by other features, notably grouping
* and treeView. It provides a tree view of the data, with nodes in that
* tree and leaves.
*
* Design information:
* -------------------
*
* The raw data that is provided must come with a $$treeLevel on any non-leaf node. Grouping will create
* these on all the group header rows, treeView will expect these to be set in the raw data by the user.
* TreeBase will run a rowsProcessor that:
* - builds `treeBase.tree` out of the provided rows
* - permits a recursive sort of the tree
* - maintains the expand/collapse state of each node
* - provides the expand/collapse all button and the expand/collapse buttons
* - maintains the count of children for each node
*
* Each row is updated with a link to the tree node that represents it. Refer {@link ui.grid.treeBase.grid:treeBase.tree tree documentation}
* for information.
*
* TreeBase adds information to the rows
* - treeLevel: if present and > -1 tells us the level (level 0 is the top level)
* - treeNode: pointer to the node in the grid.treeBase.tree that refers
* to this row, allowing us to manipulate the state
*
* Since the logic is baked into the rowsProcessors, it should get triggered whenever
* row order or filtering or anything like that is changed. We recall the expanded state
* across invocations of the rowsProcessors by the reference to the treeNode on the individual
* rows. We rebuild the tree itself quite frequently, when we do this we use the saved treeNodes to
* get the state, but we overwrite the other data in that treeNode.
*
* By default rows are collapsed, which means all data rows have their visible property
* set to false, and only level 0 group rows are set to visible.
*
* We rely on the rowsProcessors to do the actual expanding and collapsing, so we set the flags we want into
* grid.treeBase.tree, then call refresh. This is because we can't easily change the visible
* row cache without calling the processors, and once we've built the logic into the rowProcessors we may as
* well use it all the time.
*
* Tree base provides sorting (on non-grouped columns).
*
* Sorting works in two passes. The standard sorting is performed for any columns that are important to building
* the tree (for example, any grouped columns). Then after the tree is built, a recursive tree sort is performed
* for the remaining sort columns (including the original sort) - these columns are sorted within each tree level
* (so all the level 1 nodes are sorted, then all the level 2 nodes within each level 1 node etc).
*
* To achieve this we make use of the `ignoreSort` property on the sort configuration. The parent feature (treeView or grouping)
* must provide a rowsProcessor that runs with very low priority (typically in the 60-65 range), and that sets
* the `ignoreSort`on any sort that it wants to run on the tree. TreeBase will clear the ignoreSort on all sorts - so it
* will turn on any sorts that haven't run. It will then call a recursive sort on the tree.
*
* Tree base provides treeAggregation. It checks the treeAggregation configuration on each column, and aggregates based on
* the logic provided as it builds the tree. Footer aggregation from the uiGrid core should not be used with treeBase aggregation,
* since it operates on all visible rows, as opposed to to leaf nodes only. Setting `showColumnFooter: true` will show the
* treeAggregations in the column footer. Aggregation information will be collected in the format:
*
* ```
* {
* type: 'count',
* value: 4,
* label: 'count: ',
* rendered: 'count: 4'
* }
* ```
*
* A callback is provided to format the value once it is finalised (aka a valueFilter).
*
* <br/>
* <br/>
*
* <div doc-module-components="ui.grid.treeBase"></div>
*/
var module = angular.module('ui.grid.treeBase', ['ui.grid']);
/**
* @ngdoc object
* @name ui.grid.treeBase.constant:uiGridTreeBaseConstants
*
* @description constants available in treeBase module.
*
* These constants are manually copied into grouping and treeView,
* as I haven't found a way to simply include them, and it's not worth
* investing time in for something that changes very infrequently.
*
*/
module.constant('uiGridTreeBaseConstants', {
featureName: "treeBase",
rowHeaderColName: 'treeBaseRowHeaderCol',
EXPANDED: 'expanded',
COLLAPSED: 'collapsed',
aggregation: {
COUNT: 'count',
SUM: 'sum',
MAX: 'max',
MIN: 'min',
AVG: 'avg'
}
});
/**
* @ngdoc service
* @name ui.grid.treeBase.service:uiGridTreeBaseService
*
* @description Services for treeBase feature
*/
/**
* @ngdoc object
* @name ui.grid.treeBase.api:ColumnDef
*
* @description ColumnDef for tree feature, these are available to be
* set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
*/
module.service('uiGridTreeBaseService', ['$q', 'uiGridTreeBaseConstants', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'rowSorter',
function ($q, uiGridTreeBaseConstants, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants, rowSorter) {
var service = {
initializeGrid: function (grid, $scope) {
//add feature namespace and any properties to grid for needed
/**
* @ngdoc object
* @name ui.grid.treeBase.grid:treeBase
*
* @description Grid properties and functions added for treeBase
*/
grid.treeBase = {};
/**
* @ngdoc property
* @propertyOf ui.grid.treeBase.grid:treeBase
* @name numberLevels
*
* @description Total number of tree levels currently used, calculated by the rowsProcessor by
* retaining the highest tree level it sees
*/
grid.treeBase.numberLevels = 0;
/**
* @ngdoc property
* @propertyOf ui.grid.treeBase.grid:treeBase
* @name expandAll
*
* @description Whether or not the expandAll box is selected
*/
grid.treeBase.expandAll = false;
/**
* @ngdoc property
* @propertyOf ui.grid.treeBase.grid:treeBase
* @name tree
*
* @description Tree represented as a nested array that holds the state of each node, along with a
* pointer to the row. The array order is material - we will display the children in the order
* they are stored in the array
*
* Each node stores:
*
* - the state of this node
* - an array of children of this node
* - a pointer to the parent of this node (reverse pointer, allowing us to walk up the tree)
* - the number of children of this node
* - aggregation information calculated from the nodes
*
* ```
* [{
* state: 'expanded',
* row: <reference to row>,
* parentRow: null,
* aggregations: [{
* type: 'count',
* col: <gridCol>,
* value: 2,
* label: 'count: ',
* rendered: 'count: 2'
* }],
* children: [
* {
* state: 'expanded',
* row: <reference to row>,
* parentRow: <reference to row>,
* aggregations: [{
* type: 'count',
* col: '<gridCol>,
* value: 4,
* label: 'count: ',
* rendered: 'count: 4'
* }],
* children: [
* { state: 'expanded', row: <reference to row>, parentRow: <reference to row> },
* { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> },
* { state: 'expanded', row: <reference to row>, parentRow: <reference to row> },
* { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> }
* ]
* },
* {
* state: 'collapsed',
* row: <reference to row>,
* parentRow: <reference to row>,
* aggregations: [{
* type: 'count',
* col: <gridCol>,
* value: 3,
* label: 'count: ',
* rendered: 'count: 3'
* }],
* children: [
* { state: 'expanded', row: <reference to row>, parentRow: <reference to row> },
* { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> },
* { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }
* ]
* }
* ]
* }, {<another level 0 node maybe>} ]
* ```
* Missing state values are false - meaning they aren't expanded.
*
* This is used because the rowProcessors run every time the grid is refreshed, so
* we'd lose the expanded state every time the grid was refreshed. This instead gives
* us a reliable lookup that persists across rowProcessors.
*
* This tree is rebuilt every time we run the rowsProcessors. Since each row holds a pointer
* to it's tree node we can persist expand/collapse state across calls to rowsProcessor, we discard
* all transient information on the tree (children, childCount) and recalculate it
*
*/
grid.treeBase.tree = [];
service.defaultGridOptions(grid.options);
grid.registerRowsProcessor(service.treeRows, 410);
grid.registerColumnBuilder( service.treeBaseColumnBuilder );
service.createRowHeader( grid );
/**
* @ngdoc object
* @name ui.grid.treeBase.api:PublicApi
*
* @description Public Api for treeBase feature
*/
var publicApi = {
events: {
treeBase: {
/**
* @ngdoc event
* @eventOf ui.grid.treeBase.api:PublicApi
* @name rowExpanded
* @description raised whenever a row is expanded. If you are dynamically
* rendering your tree you can listen to this event, and then retrieve
* the children of this row and load them into the grid data.
*
* When the data is loaded the grid will automatically refresh to show these new rows
*
* <pre>
* gridApi.treeBase.on.rowExpanded(scope,function(row){})
* </pre>
* @param {gridRow} row the row that was expanded. You can also
* retrieve the grid from this row with row.grid
*/
rowExpanded: {},
/**
* @ngdoc event
* @eventOf ui.grid.treeBase.api:PublicApi
* @name rowCollapsed
* @description raised whenever a row is collapsed. Doesn't really have
* a purpose at the moment, included for symmetry
*
* <pre>
* gridApi.treeBase.on.rowCollapsed(scope,function(row){})
* </pre>
* @param {gridRow} row the row that was collapsed. You can also
* retrieve the grid from this row with row.grid
*/
rowCollapsed: {}
}
},
methods: {
treeBase: {
/**
* @ngdoc function
* @name expandAllRows
* @methodOf ui.grid.treeBase.api:PublicApi
* @description Expands all tree rows
*/
expandAllRows: function () {
service.expandAllRows(grid);
},
/**
* @ngdoc function
* @name collapseAllRows
* @methodOf ui.grid.treeBase.api:PublicApi
* @description collapse all tree rows
*/
collapseAllRows: function () {
service.collapseAllRows(grid);
},
/**
* @ngdoc function
* @name toggleRowTreeState
* @methodOf ui.grid.treeBase.api:PublicApi
* @description call expand if the row is collapsed, collapse if it is expanded
* @param {gridRow} row the row you wish to toggle
*/
toggleRowTreeState: function (row) {
service.toggleRowTreeState(grid, row);
},
/**
* @ngdoc function
* @name expandRow
* @methodOf ui.grid.treeBase.api:PublicApi
* @description expand the immediate children of the specified row
* @param {gridRow} row the row you wish to expand
*/
expandRow: function (row) {
service.expandRow(grid, row);
},
/**
* @ngdoc function
* @name expandRowChildren
* @methodOf ui.grid.treeBase.api:PublicApi
* @description expand all children of the specified row
* @param {gridRow} row the row you wish to expand
*/
expandRowChildren: function (row) {
service.expandRowChildren(grid, row);
},
/**
* @ngdoc function
* @name collapseRow
* @methodOf ui.grid.treeBase.api:PublicApi
* @description collapse the specified row. When
* you expand the row again, all grandchildren will retain their state
* @param {gridRow} row the row you wish to collapse
*/
collapseRow: function ( row ) {
service.collapseRow(grid, row);
},
/**
* @ngdoc function
* @name collapseRowChildren
* @methodOf ui.grid.treeBase.api:PublicApi
* @description collapse all children of the specified row. When
* you expand the row again, all grandchildren will be collapsed
* @param {gridRow} row the row you wish to collapse children for
*/
collapseRowChildren: function ( row ) {
service.collapseRowChildren(grid, row);
},
/**
* @ngdoc function
* @name getTreeState
* @methodOf ui.grid.treeBase.api:PublicApi
* @description Get the tree state for this grid,
* used by the saveState feature
* Returned treeState as an object
* `{ expandedState: { uid: 'expanded', uid: 'collapsed' } }`
* where expandedState is a hash of row uid and the current expanded state
*
* @returns {object} tree state
*
* TODO - this needs work - we need an identifier that persists across instantiations,
* not uid. This really means we need a row identity defined, but that won't work for
* grouping. Perhaps this needs to be moved up to treeView and grouping, rather than
* being in base.
*/
getTreeExpandedState: function () {
return { expandedState: service.getTreeState(grid) };
},
/**
* @ngdoc function
* @name setTreeState
* @methodOf ui.grid.treeBase.api:PublicApi
* @description Set the expanded states of the tree
* @param {object} config the config you want to apply, in the format
* provided by getTreeState
*/
setTreeState: function ( config ) {
service.setTreeState( grid, config );
},
/**
* @ngdoc function
* @name getRowChildren
* @methodOf ui.grid.treeBase.api:PublicApi
* @description Get the children of the specified row
* @param {GridRow} row the row you want the children of
* @returns {Array} array of children of this row, the children
* are all gridRows
*/
getRowChildren: function ( row ){
return row.treeNode.children.map( function( childNode ){
return childNode.row;
});
}
}
}
};
grid.api.registerEventsFromObject(publicApi.events);
grid.api.registerMethodsFromObject(publicApi.methods);
},
defaultGridOptions: function (gridOptions) {
//default option to true unless it was explicitly set to false
/**
* @ngdoc object
* @name ui.grid.treeBase.api:GridOptions
*
* @description GridOptions for treeBase feature, these are available to be
* set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
*/
/**
* @ngdoc object
* @name treeRowHeaderBaseWidth
* @propertyOf ui.grid.treeBase.api:GridOptions
* @description Base width of the tree header, provides for a single level of tree. This
* is incremented by `treeIndent` for each extra level
* <br/>Defaults to 30
*/
gridOptions.treeRowHeaderBaseWidth = gridOptions.treeRowHeaderBaseWidth || 30;
/**
* @ngdoc object
* @name treeIndent
* @propertyOf ui.grid.treeBase.api:GridOptions
* @description Number of pixels of indent for the icon at each tree level, wider indents are visually more pleasing,
* but will make the tree row header wider
* <br/>Defaults to 10
*/
gridOptions.treeIndent = gridOptions.treeIndent || 10;
/**
* @ngdoc object
* @name showTreeRowHeader
* @propertyOf ui.grid.treeBase.api:GridOptions
* @description If set to false, don't create the row header. You'll need to programmatically control the expand
* states
* <br/>Defaults to true
*/
gridOptions.showTreeRowHeader = gridOptions.showTreeRowHeader !== false;
/**
* @ngdoc object
* @name showTreeExpandNoChildren
* @propertyOf ui.grid.treeBase.api:GridOptions
* @description If set to true, show the expand/collapse button even if there are no
* children of a node. You'd use this if you're planning to dynamically load the children
*
* <br/>Defaults to true, grouping overrides to false
*/
gridOptions.showTreeExpandNoChildren = gridOptions.showTreeExpandNoChildren !== false;
/**
* @ngdoc object
* @name treeRowHeaderAlwaysVisible
* @propertyOf ui.grid.treeBase.api:GridOptions
* @description If set to true, row header even if there are no tree nodes
*
* <br/>Defaults to true
*/
gridOptions.treeRowHeaderAlwaysVisible = gridOptions.treeRowHeaderAlwaysVisible !== false;
/**
* @ngdoc object
* @name treeCustomAggregations
* @propertyOf ui.grid.treeBase.api:GridOptions
* @description Define custom aggregation functions. The properties of this object will be
* aggregation types available for use on columnDef with {@link ui.grid.treeBase.api:ColumnDef treeAggregationType} or through the column menu.
* If a function defined here uses the same name as one of the native aggregations, this one will take precedence.
* The object format is:
*
* <pre>
* {
* aggregationName: {
* label: (optional) string,
* aggregationFn: function( aggregation, fieldValue, numValue, row ){...},
* finalizerFn: (optional) function( aggregation ){...}
* },
* mean: {
* label: 'mean',
* aggregationFn: function( aggregation, fieldValue, numValue ){
* aggregation.count = (aggregation.count || 1) + 1;
* aggregation.sum = (aggregation.sum || 0) + numValue;
* },
* finalizerFn: function( aggregation ){
* aggregation.value = aggregation.sum / aggregation.count
* }
* }
* }
* </pre>
*
* <br/>The `finalizerFn` may be used to manipulate the value before rendering, or to
* apply a custom rendered value. If `aggregation.rendered` is left undefined, the value will be
* rendered. Note that the native aggregation functions use an `finalizerFn` to concatenate
* the label and the value.
*
* <br/>Defaults to {}
*/
gridOptions.treeCustomAggregations = gridOptions.treeCustomAggregations || {};
/**
* @ngdoc object
* @name enableExpandAll
* @propertyOf ui.grid.treeBase.api:GridOptions
* @description Enable the expand all button at the top of the row header
*
* <br/>Defaults to true
*/
gridOptions.enableExpandAll = gridOptions.enableExpandAll !== false;
},
/**
* @ngdoc function
* @name treeBaseColumnBuilder
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Sets the tree defaults based on the columnDefs
*
* @param {object} colDef columnDef we're basing on
* @param {GridCol} col the column we're to update
* @param {object} gridOptions the options we should use
* @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved
*/
treeBaseColumnBuilder: function (colDef, col, gridOptions) {
/**
* @ngdoc object
* @name customTreeAggregationFn
* @propertyOf ui.grid.treeBase.api:ColumnDef
* @description A custom function that aggregates rows into some form of
* total. Aggregations run row-by-row, the function needs to be capable of
* creating a running total.
*
* The function will be provided the aggregation item (in which you can store running
* totals), the row value that is to be aggregated, and that same row value converted to
* a number (most aggregations work on numbers)
* @example
* <pre>
* customTreeAggregationFn = function ( aggregation, fieldValue, numValue, row ){
* // calculates the average of the squares of the values
* if ( typeof(aggregation.count) === 'undefined' ){
* aggregation.count = 0;
* }
* aggregation.count++;
*
* if ( !isNaN(numValue) ){
* if ( typeof(aggregation.total) === 'undefined' ){
* aggregation.total = 0;
* }
* aggregation.total = aggregation.total + numValue * numValue;
* }
*
* aggregation.value = aggregation.total / aggregation.count;
* }
* </pre>
* <br/>Defaults to undefined. May be overwritten by treeAggregationType, the two options should not be used together.
*/
if ( typeof(colDef.customTreeAggregationFn) !== 'undefined' ){
col.treeAggregationFn = colDef.customTreeAggregationFn;
}
/**
* @ngdoc object
* @name treeAggregationType
* @propertyOf ui.grid.treeBase.api:ColumnDef
* @description Use one of the native or grid-level aggregation methods for calculating aggregations on this column.
* Native method are in the constants file and include: SUM, COUNT, MIN, MAX, AVG. This may also be the property the
* name of an aggregation function defined with {@link ui.grid.treeBase.api:GridOptions treeCustomAggregations}.
*
* <pre>
* treeAggregationType = uiGridTreeBaseConstants.aggregation.SUM,
* }
* </pre>
*
* If you are using aggregations you should either:
*
* - also use grouping, in which case the aggregations are displayed in the group header, OR
* - use treeView, in which case you can set `treeAggregationUpdateEntity: true` in the colDef, and
* treeBase will store the aggregation information in the entity, or you can set `treeAggregationUpdateEntity: false`
* in the colDef, and you need to manual retrieve the calculated aggregations from the row.treeNode.aggregations
*
* <br/>Takes precendence over a treeAggregationFn, the two options should not be used together.
* <br/>Defaults to undefined.
*/
if ( typeof(colDef.treeAggregationType) !== 'undefined' ){
col.treeAggregation = { type: colDef.treeAggregationType };
if ( typeof(gridOptions.treeCustomAggregations[colDef.treeAggregationType]) !== 'undefined' ){
col.treeAggregationFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].aggregationFn;
col.treeAggregationFinalizerFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].finalizerFn;
col.treeAggregation.label = gridOptions.treeCustomAggregations[colDef.treeAggregationType].label;
} else if ( typeof(service.nativeAggregations()[colDef.treeAggregationType]) !== 'undefined' ){
col.treeAggregationFn = service.nativeAggregations()[colDef.treeAggregationType].aggregationFn;
col.treeAggregation.label = service.nativeAggregations()[colDef.treeAggregationType].label;
}
}
/**
* @ngdoc object
* @name treeAggregationLabel
* @propertyOf ui.grid.treeBase.api:ColumnDef
* @description A custom label to use for this aggregation. If provided we don't use native i18n.
*/
if ( typeof(colDef.treeAggregationLabel) !== 'undefined' ){
if (typeof(col.treeAggregation) === 'undefined' ){
col.treeAggregation = {};
}
col.treeAggregation.label = colDef.treeAggregationLabel;
}
/**
* @ngdoc object
* @name treeAggregationUpdateEntity
* @propertyOf ui.grid.treeBase.api:ColumnDef
* @description Store calculated aggregations into the entity, allowing them
* to be displayed in the grid using a standard cellTemplate. This defaults to true,
* if you are using grouping then you shouldn't set it to false, as then the aggregations won't
* display.
*
* If you are using treeView in most cases you'll want to set this to true. This will result in
* getCellValue returning the aggregation rather than whatever was stored in the cell attribute on
* the entity. If you want to render the underlying entity value (and do something else with the aggregation)
* then you could use a custom cellTemplate to display `row.entity.myAttribute`, rather than using getCellValue.
*
* <br/>Defaults to true
*
* @example
* <pre>
* gridOptions.columns = [{
* name: 'myCol',
* treeAggregation: { type: uiGridTreeBaseConstants.aggregation.SUM },
* treeAggregationUpdateEntity: true
* cellTemplate: '<div>{{row.entity.myCol + " " + row.treeNode.aggregations[0].rendered}}</div>'
* }];
* </pre>
*/
col.treeAggregationUpdateEntity = colDef.treeAggregationUpdateEntity !== false;
/**
* @ngdoc object
* @name customTreeAggregationFinalizerFn
* @propertyOf ui.grid.treeBase.api:ColumnDef
* @description A custom function that populates aggregation.rendered, this is called when
* a particular aggregation has been fully calculated, and we want to render the value.
*
* With the native aggregation options we just concatenate `aggregation.label` and
* `aggregation.value`, but if you wanted to apply a filter or otherwise manipulate the label
* or the value, you can do so with this function. This function will be called after the
* the default `finalizerFn`.
*
* @example
* <pre>
* customTreeAggregationFinalizerFn = function ( aggregation ){
* aggregation.rendered = aggregation.label + aggregation.value / 100 + '%';
* }
* </pre>
* <br/>Defaults to undefined.
*/
if ( typeof(col.customTreeAggregationFinalizerFn) === 'undefined' ){
col.customTreeAggregationFinalizerFn = colDef.customTreeAggregationFinalizerFn;
}
},
/**
* @ngdoc function
* @name createRowHeader
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Create the rowHeader. If treeRowHeaderAlwaysVisible then
* set it to visible, otherwise set it to invisible
*
* @param {Grid} grid grid object
*/
createRowHeader: function( grid ){
var rowHeaderColumnDef = {
name: uiGridTreeBaseConstants.rowHeaderColName,
displayName: '',
width: grid.options.treeRowHeaderBaseWidth,
minWidth: 10,
cellTemplate: 'ui-grid/treeBaseRowHeader',
headerCellTemplate: 'ui-grid/treeBaseHeaderCell',
enableColumnResizing: false,
enableColumnMenu: false,
exporterSuppressExport: true,
allowCellFocus: true
};
rowHeaderColumnDef.visible = grid.options.treeRowHeaderAlwaysVisible;
grid.addRowHeaderColumn(rowHeaderColumnDef, -100);
},
/**
* @ngdoc function
* @name expandAllRows
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Expands all nodes in the tree
*
* @param {Grid} grid grid object
*/
expandAllRows: function (grid) {
grid.treeBase.tree.forEach( function( node ) {
service.setAllNodes( grid, node, uiGridTreeBaseConstants.EXPANDED);
});
grid.treeBase.expandAll = true;
grid.queueGridRefresh();
},
/**
* @ngdoc function
* @name collapseAllRows
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Collapses all nodes in the tree
*
* @param {Grid} grid grid object
*/
collapseAllRows: function (grid) {
grid.treeBase.tree.forEach( function( node ) {
service.setAllNodes( grid, node, uiGridTreeBaseConstants.COLLAPSED);
});
grid.treeBase.expandAll = false;
grid.queueGridRefresh();
},
/**
* @ngdoc function
* @name setAllNodes
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Works through a subset of grid.treeBase.rowExpandedStates, setting
* all child nodes (and their descendents) of the provided node to the given state.
*
* Calls itself recursively on all nodes so as to achieve this.
*
* @param {Grid} grid the grid we're operating on (so we can raise events)
* @param {object} treeNode a node in the tree that we want to update
* @param {string} targetState the state we want to set it to
*/
setAllNodes: function (grid, treeNode, targetState) {
if ( typeof(treeNode.state) !== 'undefined' && treeNode.state !== targetState ){
treeNode.state = targetState;
if ( targetState === uiGridTreeBaseConstants.EXPANDED ){
grid.api.treeBase.raise.rowExpanded(treeNode.row);
} else {
grid.api.treeBase.raise.rowCollapsed(treeNode.row);
}
}
// set all child nodes
if ( treeNode.children ){
treeNode.children.forEach(function( childNode ){
service.setAllNodes(grid, childNode, targetState);
});
}
},
/**
* @ngdoc function
* @name toggleRowTreeState
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Toggles the expand or collapse state of this grouped row, if
* it's a parent row
*
* @param {Grid} grid grid object
* @param {GridRow} row the row we want to toggle
*/
toggleRowTreeState: function ( grid, row ){
if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
return;
}
if (row.treeNode.state === uiGridTreeBaseConstants.EXPANDED){
service.collapseRow(grid, row);
} else {
service.expandRow(grid, row);
}
grid.queueGridRefresh();
},
/**
* @ngdoc function
* @name expandRow
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Expands this specific row, showing only immediate children.
*
* @param {Grid} grid grid object
* @param {GridRow} row the row we want to expand
*/
expandRow: function ( grid, row ){
if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
return;
}
if ( row.treeNode.state !== uiGridTreeBaseConstants.EXPANDED ){
row.treeNode.state = uiGridTreeBaseConstants.EXPANDED;
grid.api.treeBase.raise.rowExpanded(row);
grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree);
grid.queueGridRefresh();
}
},
/**
* @ngdoc function
* @name expandRowChildren
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Expands this specific row, showing all children.
*
* @param {Grid} grid grid object
* @param {GridRow} row the row we want to expand
*/
expandRowChildren: function ( grid, row ){
if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
return;
}
service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.EXPANDED);
grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree);
grid.queueGridRefresh();
},
/**
* @ngdoc function
* @name collapseRow
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Collapses this specific row
*
* @param {Grid} grid grid object
* @param {GridRow} row the row we want to collapse
*/
collapseRow: function( grid, row ){
if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
return;
}
if ( row.treeNode.state !== uiGridTreeBaseConstants.COLLAPSED ){
row.treeNode.state = uiGridTreeBaseConstants.COLLAPSED;
grid.treeBase.expandAll = false;
grid.api.treeBase.raise.rowCollapsed(row);
grid.queueGridRefresh();
}
},
/**
* @ngdoc function
* @name collapseRowChildren
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Collapses this specific row and all children
*
* @param {Grid} grid grid object
* @param {GridRow} row the row we want to collapse
*/
collapseRowChildren: function( grid, row ){
if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
return;
}
service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.COLLAPSED);
grid.treeBase.expandAll = false;
grid.queueGridRefresh();
},
/**
* @ngdoc function
* @name allExpanded
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Returns true if all rows are expanded, false
* if they're not. Walks the tree to determine this. Used
* to set the expandAll state.
*
* If the node has no children, then return true (it's immaterial
* whether it is expanded). If the node has children, then return
* false if this node is collapsed, or if any child node is not all expanded
*
* @param {object} tree the grid to check
* @returns {boolean} whether or not the tree is all expanded
*/
allExpanded: function( tree ){
var allExpanded = true;
tree.forEach( function( node ){
if ( !service.allExpandedInternal( node ) ){
allExpanded = false;
}
});
return allExpanded;
},
allExpandedInternal: function( treeNode ){
if ( treeNode.children && treeNode.children.length > 0 ){
if ( treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){
return false;
}
var allExpanded = true;
treeNode.children.forEach( function( node ){
if ( !service.allExpandedInternal( node ) ){
allExpanded = false;
}
});
return allExpanded;
} else {
return true;
}
},
/**
* @ngdoc function
* @name treeRows
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description The rowProcessor that adds the nodes to the tree, and sets the visible
* state of each row based on it's parent state
*
* Assumes it is always called after the sorting processor, and the grouping processor if there is one.
* Performs any tree sorts itself after having built the tree
*
* Processes all the rows in order, setting the group level based on the $$treeLevel in the associated
* entity, and setting the visible state based on the parent's state.
*
* Calculates the deepest level of tree whilst it goes, and updates that so that the header column can be correctly
* sized.
*
* Aggregates if necessary along the way.
*
* @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor
* @returns {array} the updated rows
*/
treeRows: function( renderableRows ) {
if (renderableRows.length === 0){
return renderableRows;
}
var grid = this;
var currentLevel = 0;
var currentState = uiGridTreeBaseConstants.EXPANDED;
var parents = [];
grid.treeBase.tree = service.createTree( grid, renderableRows );
service.updateRowHeaderWidth( grid );
service.sortTree( grid );
service.fixFilter( grid );
return service.renderTree( grid.treeBase.tree );
},
/**
* @ngdoc function
* @name createOrUpdateRowHeaderWidth
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Calculates the rowHeader width.
*
* If rowHeader is always present, updates the width.
*
* If rowHeader is only sometimes present (`treeRowHeaderAlwaysVisible: false`), determines whether there
* should be one, then creates or removes it as appropriate, with the created rowHeader having the
* right width.
*
* If there's never a rowHeader then never creates one: `showTreeRowHeader: false`
*
* @param {Grid} grid the grid we want to set the row header on
*/
updateRowHeaderWidth: function( grid ){
var rowHeader = grid.getColumn(uiGridTreeBaseConstants.rowHeaderColName);
var newWidth = grid.options.treeRowHeaderBaseWidth + grid.options.treeIndent * Math.max(grid.treeBase.numberLevels - 1, 0);
if ( rowHeader && newWidth !== rowHeader.width ){
rowHeader.width = newWidth;
grid.queueRefresh();
}
var newVisibility = true;
if ( grid.options.showTreeRowHeader === false ){
newVisibility = false;
}
if ( grid.options.treeRowHeaderAlwaysVisible === false && grid.treeBase.numberLevels <= 0 ){
newVisibility = false;
}
if ( rowHeader && rowHeader.visible !== newVisibility ) {
rowHeader.visible = newVisibility;
rowHeader.colDef.visible = newVisibility;
grid.queueGridRefresh();
}
},
/**
* @ngdoc function
* @name renderTree
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Creates an array of rows based on the tree, exporting only
* the visible nodes and leaves
*
* @param {array} nodeList the list of nodes - can be grid.treeBase.tree, or can be node.children when
* we're calling recursively
* @returns {array} renderable rows
*/
renderTree: function( nodeList ){
var renderableRows = [];
nodeList.forEach( function ( node ){
if ( node.row.visible ){
renderableRows.push( node.row );
}
if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){
renderableRows = renderableRows.concat( service.renderTree( node.children ) );
}
});
return renderableRows;
},
/**
* @ngdoc function
* @name createTree
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Creates a tree from the renderableRows
*
* @param {Grid} grid the grid
* @param {array} renderableRows the rows we want to create a tree from
* @returns {object} the tree we've build
*/
createTree: function( grid, renderableRows ) {
var currentLevel = -1;
var parents = [];
var currentState;
grid.treeBase.tree = [];
grid.treeBase.numberLevels = 0;
var aggregations = service.getAggregations( grid );
var createNode = function( row ){
if ( typeof(row.entity.$$treeLevel) !== 'undefined' && row.treeLevel !== row.entity.$$treeLevel ){
row.treeLevel = row.entity.$$treeLevel;
}
if ( row.treeLevel <= currentLevel ){
// pop any levels that aren't parents of this level, formatting the aggregation at the same time
while ( row.treeLevel <= currentLevel ){
var lastParent = parents.pop();
service.finaliseAggregations( lastParent );
currentLevel--;
}
// reset our current state based on the new parent, set to expanded if this is a level 0 node
if ( parents.length > 0 ){
currentState = service.setCurrentState(parents);
} else {
currentState = uiGridTreeBaseConstants.EXPANDED;
}
}
// aggregate if this is a leaf node
if ( ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ) && row.visible ){
service.aggregate( grid, row, parents );
}
// add this node to the tree
service.addOrUseNode(grid, row, parents, aggregations);
if ( typeof(row.treeLevel) !== 'undefined' && row.treeLevel !== null && row.treeLevel >= 0 ){
parents.push(row);
currentLevel++;
currentState = service.setCurrentState(parents);
}
// update the tree number of levels, so we can set header width if we need to
if ( grid.treeBase.numberLevels < row.treeLevel + 1){
grid.treeBase.numberLevels = row.treeLevel + 1;
}
};
renderableRows.forEach( createNode );
// finalise remaining aggregations
while ( parents.length > 0 ){
var lastParent = parents.pop();
service.finaliseAggregations( lastParent );
}
return grid.treeBase.tree;
},
/**
* @ngdoc function
* @name addOrUseNode
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Creates a tree node for this row. If this row already has a treeNode
* recorded against it, preserves the state, but otherwise overwrites the data.
*
* @param {grid} grid the grid we're operating on
* @param {gridRow} row the row we want to set
* @param {array} parents an array of the parents this row should have
* @param {array} aggregationBase empty aggregation information
* @returns {undefined} updates the parents array, updates the row to have a treeNode, and updates the
* grid.treeBase.tree
*/
addOrUseNode: function( grid, row, parents, aggregationBase ){
var newAggregations = [];
aggregationBase.forEach( function(aggregation){
newAggregations.push(service.buildAggregationObject(aggregation.col));
});
var newNode = { state: uiGridTreeBaseConstants.COLLAPSED, row: row, parentRow: null, aggregations: newAggregations, children: [] };
if ( row.treeNode ){
newNode.state = row.treeNode.state;
}
if ( parents.length > 0 ){
newNode.parentRow = parents[parents.length - 1];
}
row.treeNode = newNode;
if ( parents.length === 0 ){
grid.treeBase.tree.push( newNode );
} else {
parents[parents.length - 1].treeNode.children.push( newNode );
}
},
/**
* @ngdoc function
* @name setCurrentState
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Looks at the parents array to determine our current state.
* If any node in the hierarchy is collapsed, then return collapsed, otherwise return
* expanded.
*
* @param {array} parents an array of the parents this row should have
* @returns {string} the state we should be setting to any nodes we see
*/
setCurrentState: function( parents ){
var currentState = uiGridTreeBaseConstants.EXPANDED;
parents.forEach( function(parent){
if ( parent.treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){
currentState = uiGridTreeBaseConstants.COLLAPSED;
}
});
return currentState;
},
/**
* @ngdoc function
* @name sortTree
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Performs a recursive sort on the tree nodes, sorting the
* children of each node and putting them back into the children array.
*
* Before doing this it turns back on all the sortIgnore - things that were previously
* ignored we process now. Since we're sorting within the nodes, presumably anything
* that was already sorted is how we derived the nodes, we can keep those sorts too.
*
* We only sort tree nodes that are expanded - no point in wasting effort sorting collapsed
* nodes
*
* @param {Grid} grid the grid to get the aggregation information from
* @returns {array} the aggregation information
*/
sortTree: function( grid ){
grid.columns.forEach( function( column ) {
if ( column.sort && column.sort.ignoreSort ){
delete column.sort.ignoreSort;
}
});
grid.treeBase.tree = service.sortInternal( grid, grid.treeBase.tree );
},
sortInternal: function( grid, treeList ){
var rows = treeList.map( function( node ){
return node.row;
});
rows = rowSorter.sort( grid, rows, grid.columns );
var treeNodes = rows.map( function( row ){
return row.treeNode;
});
treeNodes.forEach( function( node ){
if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){
node.children = service.sortInternal( grid, node.children );
}
});
return treeNodes;
},
/**
* @ngdoc function
* @name fixFilter
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description After filtering has run, we need to go back through the tree
* and make sure the parent rows are always visible if any of the child rows
* are visible (filtering may make a child visible, but the parent may not
* match the filter criteria)
*
* This has a risk of being computationally expensive, we do it by walking
* the tree and remembering whether there are any invisible nodes on the
* way down.
*
* @param {Grid} grid the grid to fix filters on
*/
fixFilter: function( grid ){
var parentsVisible;
grid.treeBase.tree.forEach( function( node ){
if ( node.children && node.children.length > 0 ){
parentsVisible = node.row.visible;
service.fixFilterInternal( node.children, parentsVisible );
}
});
},
fixFilterInternal: function( nodes, parentsVisible) {
nodes.forEach( function( node ){
if ( node.row.visible && !parentsVisible ){
service.setParentsVisible( node );
parentsVisible = true;
}
if ( node.children && node.children.length > 0 ){
if ( service.fixFilterInternal( node.children, ( parentsVisible && node.row.visible ) ) ) {
parentsVisible = true;
}
}
});
return parentsVisible;
},
setParentsVisible: function( node ){
while ( node.parentRow ){
node.parentRow.visible = true;
node = node.parentRow.treeNode;
}
},
/**
* @ngdoc function
* @name buildAggregationObject
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Build the object which is stored on the column for holding meta-data about the aggregation.
* This method should only be called with columns which have an aggregation.
*
* @param {Column} the column which this object relates to
* @returns {object} {col: Column object, label: string, type: string (optional)}
*/
buildAggregationObject: function( column ){
var newAggregation = { col: column };
if ( column.treeAggregation && column.treeAggregation.type ){
newAggregation.type = column.treeAggregation.type;
}
if ( column.treeAggregation && column.treeAggregation.label ){
newAggregation.label = column.treeAggregation.label;
}
return newAggregation;
},
/**
* @ngdoc function
* @name getAggregations
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Looks through the grid columns to find those with aggregations,
* and collates the aggregation information into an array, returns that array
*
* @param {Grid} grid the grid to get the aggregation information from
* @returns {array} the aggregation information
*/
getAggregations: function( grid ){
var aggregateArray = [];
grid.columns.forEach( function(column){
if ( typeof(column.treeAggregationFn) !== 'undefined' ){
aggregateArray.push( service.buildAggregationObject(column) );
if ( grid.options.showColumnFooter && typeof(column.colDef.aggregationType) === 'undefined' && column.treeAggregation ){
// Add aggregation object for footer
column.treeFooterAggregation = service.buildAggregationObject(column);
column.aggregationType = service.treeFooterAggregationType;
}
}
});
return aggregateArray;
},
/**
* @ngdoc function
* @name aggregate
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Accumulate the data from this row onto the aggregations for each parent
*
* Iterate over the parents, then iterate over the aggregations for each of those parents,
* and perform the aggregation for each individual aggregation
*
* @param {Grid} grid grid object
* @param {GridRow} row the row we want to set grouping visibility on
* @param {array} parents the parents that we would want to aggregate onto
*/
aggregate: function( grid, row, parents ){
if ( parents.length === 0 && row.treeNode && row.treeNode.aggregations ){
row.treeNode.aggregations.forEach(function(aggregation){
// Calculate aggregations for footer even if there are no grouped rows
if ( typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ) {
var fieldValue = grid.getCellValue(row, aggregation.col);
var numValue = Number(fieldValue);
aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row);
}
});
}
parents.forEach( function( parent, index ){
if ( parent.treeNode.aggregations ){
parent.treeNode.aggregations.forEach( function( aggregation ){
var fieldValue = grid.getCellValue(row, aggregation.col);
var numValue = Number(fieldValue);
aggregation.col.treeAggregationFn(aggregation, fieldValue, numValue, row);
if ( index === 0 && typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ){
aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row);
}
});
}
});
},
// Aggregation routines - no doco needed as self evident
nativeAggregations: function() {
var nativeAggregations = {
count: {
label: i18nService.get().aggregation.count,
menuTitle: i18nService.get().grouping.aggregate_count,
aggregationFn: function (aggregation, fieldValue, numValue) {
if (typeof(aggregation.value) === 'undefined') {
aggregation.value = 1;
} else {
aggregation.value++;
}
}
},
sum: {
label: i18nService.get().aggregation.sum,
menuTitle: i18nService.get().grouping.aggregate_sum,
aggregationFn: function( aggregation, fieldValue, numValue ) {
if (!isNaN(numValue)) {
if (typeof(aggregation.value) === 'undefined') {
aggregation.value = numValue;
} else {
aggregation.value += numValue;
}
}
}
},
min: {
label: i18nService.get().aggregation.min,
menuTitle: i18nService.get().grouping.aggregate_min,
aggregationFn: function( aggregation, fieldValue, numValue ) {
if (typeof(aggregation.value) === 'undefined') {
aggregation.value = fieldValue;
} else {
if (typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue < aggregation.value || aggregation.value === null)) {
aggregation.value = fieldValue;
}
}
}
},
max: {
label: i18nService.get().aggregation.max,
menuTitle: i18nService.get().grouping.aggregate_max,
aggregationFn: function( aggregation, fieldValue, numValue ){
if ( typeof(aggregation.value) === 'undefined' ){
aggregation.value = fieldValue;
} else {
if ( typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue > aggregation.value || aggregation.value === null)){
aggregation.value = fieldValue;
}
}
}
},
avg: {
label: i18nService.get().aggregation.avg,
menuTitle: i18nService.get().grouping.aggregate_avg,
aggregationFn: function( aggregation, fieldValue, numValue ){
if ( typeof(aggregation.count) === 'undefined' ){
aggregation.count = 1;
} else {
aggregation.count++;
}
if ( isNaN(numValue) ){
return;
}
if ( typeof(aggregation.value) === 'undefined' || typeof(aggregation.sum) === 'undefined' ){
aggregation.value = numValue;
aggregation.sum = numValue;
} else {
aggregation.sum += numValue;
aggregation.value = aggregation.sum / aggregation.count;
}
}
}
};
return nativeAggregations;
},
/**
* @ngdoc function
* @name finaliseAggregation
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Helper function used to finalize aggregation nodes and footer cells
*
* @param {gridRow} row the parent we're finalising
* @param {aggregation} the aggregation object manipulated by the aggregationFn
*/
finaliseAggregation: function(row, aggregation){
if ( aggregation.col.treeAggregationUpdateEntity && typeof(row) !== 'undefined' && typeof(row.entity[ '$$' + aggregation.col.uid ]) !== 'undefined' ){
angular.extend( aggregation, row.entity[ '$$' + aggregation.col.uid ]);
}
if ( typeof(aggregation.col.treeAggregationFinalizerFn) === 'function' ){
aggregation.col.treeAggregationFinalizerFn( aggregation );
}
if ( typeof(aggregation.col.customTreeAggregationFinalizerFn) === 'function' ){
aggregation.col.customTreeAggregationFinalizerFn( aggregation );
}
if ( typeof(aggregation.rendered) === 'undefined' ){
aggregation.rendered = aggregation.label ? aggregation.label + aggregation.value : aggregation.value;
}
},
/**
* @ngdoc function
* @name finaliseAggregations
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Format the data from the aggregation into the rendered text
* e.g. if we had label: 'sum: ' and value: 25, we'd create 'sum: 25'.
*
* As part of this we call any formatting callback routines we've been provided.
*
* We write our aggregation out to the row.entity if treeAggregationUpdateEntity is
* set on the column - we don't overwrite any information that's already there, we append
* to it so that grouping can have set the groupVal beforehand without us overwriting it.
*
* We need to copy the data from the row.entity first before we finalise the aggregation,
* we need that information for the finaliserFn
*
* @param {gridRow} row the parent we're finalising
*/
finaliseAggregations: function( row ){
if ( row == null || typeof(row.treeNode.aggregations) === 'undefined' ){
return;
}
row.treeNode.aggregations.forEach( function( aggregation ) {
service.finaliseAggregation(row, aggregation);
if ( aggregation.col.treeAggregationUpdateEntity ){
var aggregationCopy = {};
angular.forEach( aggregation, function( value, key ){
if ( aggregation.hasOwnProperty(key) && key !== 'col' ){
aggregationCopy[key] = value;
}
});
row.entity[ '$$' + aggregation.col.uid ] = aggregationCopy;
}
});
},
/**
* @ngdoc function
* @name treeFooterAggregationType
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Uses the tree aggregation functions and finalizers to set the
* column footer aggregations.
*
* @param {rows} visible rows. not used, but accepted to match signature of GridColumn.aggregationType
* @param {gridColumn} the column we are finalizing
*/
treeFooterAggregationType: function( rows, column ) {
service.finaliseAggregation(undefined, column.treeFooterAggregation);
if ( typeof(column.treeFooterAggregation.value) === 'undefined' || column.treeFooterAggregation.rendered === null ){
// The was apparently no aggregation performed (perhaps this is a grouped column
return '';
}
return column.treeFooterAggregation.rendered;
}
};
return service;
}]);
/**
* @ngdoc directive
* @name ui.grid.treeBase.directive:uiGridTreeRowHeaderButtons
* @element div
*
* @description Provides the expand/collapse button on rows
*/
module.directive('uiGridTreeBaseRowHeaderButtons', ['$templateCache', 'uiGridTreeBaseService',
function ($templateCache, uiGridTreeBaseService) {
return {
replace: true,
restrict: 'E',
template: $templateCache.get('ui-grid/treeBaseRowHeaderButtons'),
scope: true,
require: '^uiGrid',
link: function($scope, $elm, $attrs, uiGridCtrl) {
var self = uiGridCtrl.grid;
$scope.treeButtonClick = function(row, evt) {
uiGridTreeBaseService.toggleRowTreeState(self, row, evt);
};
}
};
}]);
/**
* @ngdoc directive
* @name ui.grid.treeBase.directive:uiGridTreeBaseExpandAllButtons
* @element div
*
* @description Provides the expand/collapse all button
*/
module.directive('uiGridTreeBaseExpandAllButtons', ['$templateCache', 'uiGridTreeBaseService',
function ($templateCache, uiGridTreeBaseService) {
return {
replace: true,
restrict: 'E',
template: $templateCache.get('ui-grid/treeBaseExpandAllButtons'),
scope: false,
link: function($scope, $elm, $attrs, uiGridCtrl) {
var self = $scope.col.grid;
$scope.headerButtonClick = function(row, evt) {
if ( self.treeBase.expandAll ){
uiGridTreeBaseService.collapseAllRows(self, evt);
} else {
uiGridTreeBaseService.expandAllRows(self, evt);
}
};
}
};
}]);
/**
* @ngdoc directive
* @name ui.grid.treeBase.directive:uiGridViewport
* @element div
*
* @description Stacks on top of ui.grid.uiGridViewport to set formatting on a tree header row
*/
module.directive('uiGridViewport',
['$compile', 'uiGridConstants', 'gridUtil', '$parse',
function ($compile, uiGridConstants, gridUtil, $parse) {
return {
priority: -200, // run after default directive
scope: false,
compile: function ($elm, $attrs) {
var rowRepeatDiv = angular.element($elm.children().children()[0]);
var existingNgClass = rowRepeatDiv.attr("ng-class");
var newNgClass = '';
if ( existingNgClass ) {
newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-tree-header-row': row.treeLevel > -1}";
} else {
newNgClass = "{'ui-grid-tree-header-row': row.treeLevel > -1}";
}
rowRepeatDiv.attr("ng-class", newNgClass);
return {
pre: function ($scope, $elm, $attrs, controllers) {
},
post: function ($scope, $elm, $attrs, controllers) {
}
};
}
};
}]);
})();
|
var fs = require("fs");
var findFile = function (files, regex) {
return files.find(function (file) {
if (regex.test(file)) {
return true;
}
});
};
var verifyFilenameLength = function (filename, expectedNameLength) {
expect(filename).toMatch(new RegExp("^.{" + expectedNameLength + "}$"));
};
module.exports = {
findBundle: function (i, options) {
var files = fs.readdirSync(options.output.path);
var bundleDetects = [
options.amd.expectedChunkFilenameLength && {
regex: new RegExp("^\\d+.bundle" + i, "i"),
expectedNameLength: options.amd.expectedChunkFilenameLength
},
{
regex: new RegExp("^bundle" + i, "i"),
expectedNameLength: options.amd.expectedFilenameLength
}
].filter(Boolean);
var bundleDetect;
var filename;
for (bundleDetect of bundleDetects) {
filename = findFile(files, bundleDetect.regex);
if (!filename) {
throw new Error(
`No file found with correct name (regex: ${
bundleDetect.regex.source
}, files: ${files.join(", ")})`
);
}
verifyFilenameLength(
filename.replace(/^\d+\./, "X."),
bundleDetect.expectedNameLength
);
}
return "./" + filename;
},
afterExecute: () => {
delete global.webpackChunk;
}
};
|
/// @file AdminUserPrivilegesModel.js
/// Sets the layout for the information needed to specify whether user is admin
define([
'jquery',
'marionette',
'backbone',
'underscore'
], function($, Marionette, Backbone, _) {
'use strict';
return Backbone.Model.extend({
initialize: function(){
_.bindAll(this);
},
defaults: {
id: -1,
username: '',
first_name: '',
last_name: '',
email: '',
date_joined: '',
admin_access: false
}
});
}); |
/**
* Simple Layer constructor.
* @constructor
*/
function SimpleLayer(){
this.dom_obj = this.create_block();
document.body.appendChild(this.dom_obj);
this.container = document.createElement('div');
this.container.addClass('simple_layer');
this.dom_obj.appendChild(this.container);
this.base_layer = BaseLayer.prototype;
}
SimpleLayer.prototype = new BaseLayer();
function Scrollable(dom_obj, parent){
this.dom_obj = dom_obj;
this.parent = parent;
this.initScrollbar();
}
Scrollable.prototype.initScrollbar = function(){
this.scrollbar = new scrollbar(this.parent, this.dom_obj);
};
Scrollable.prototype.scrollTop = function(){
this.dom_obj.scrollTop = 0;
this.scrollbar.refresh();
}
Scrollable.prototype.scroll = function(dir){
if (dir > 0){
this.dom_obj.scrollTop = this.dom_obj.scrollTop + 40;
}else{
this.dom_obj.scrollTop = this.dom_obj.scrollTop - 40;
}
this.scrollbar.refresh();
};
Scrollable.prototype.scrollPage = function(dir){
if (dir > 0){
this.dom_obj.scrollTop = this.dom_obj.scrollTop + 200;
}else{
this.dom_obj.scrollTop = this.dom_obj.scrollTop - 200;
}
this.scrollbar.refresh();
};
loader.next(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.